Postgres MCP Server: Let Claude Query Your Database

by Sandlabs Team, Founder, Sandlabs

You know the drill. Someone on the team needs last quarter's churn numbers. You open pgAdmin, write a query, export to CSV, drop it into a spreadsheet, then paste a summary into Slack. Twenty minutes gone for a question that should take twenty seconds.

Now imagine asking Claude: "What was our monthly churn rate for Q1, broken down by pricing tier?" and getting the answer immediately — complete with the SQL it ran and the raw numbers behind it.

That is what the Postgres MCP server does. It gives Claude direct, read-only access to your PostgreSQL database so you can explore data, generate reports, and debug issues through natural language conversation.

What Is a Postgres MCP Server?

A Postgres MCP server is a Model Context Protocol connector that lets AI assistants like Claude query PostgreSQL databases directly. Instead of writing SQL by hand or switching between tools, you describe what you need in plain English and Claude translates that into SQL, executes it against your database, and returns the results in context.

The server sits between Claude and your database. Claude sends a request ("show me the top 10 customers by lifetime value"), the MCP server translates that into a SQL query, runs it against PostgreSQL, and returns structured results. Everything happens through the standardised MCP protocol — no custom API layer or middleware required.

This works with any PostgreSQL-compatible database, including standard PostgreSQL, Supabase, Neon, Amazon RDS, Google Cloud SQL, and Azure Database for PostgreSQL.

What Can You Do With It?

Once connected, Claude can interact with your database in ways that replace several manual workflows:

Data Exploration

  • Browse your schema — list tables, columns, data types, and relationships
  • Run ad hoc queries — ask questions about your data without writing SQL
  • Inspect sample data — look at actual rows to understand data shape and quality
  • Discover patterns — ask Claude to find anomalies, trends, or outliers

Report Generation

  • Pull metrics on demand — revenue, churn, signups, conversion rates
  • Compare time periods — "How did March compare to February?"
  • Segment analysis — break down any metric by user type, region, plan, or custom attribute
  • Export-ready summaries — get formatted tables you can paste directly into docs or Slack

Debugging and Diagnostics

  • Trace data issues — "Why does user #4521 have a null subscription_id?"
  • Check data integrity — find orphaned records, duplicates, or constraint violations
  • Audit recent changes — query audit logs or updated_at timestamps to track what changed
  • Validate migrations — confirm that a schema change applied correctly

Setting Up the Postgres MCP Server: Step-by-Step

This guide uses the community Postgres MCP server (@modelcontextprotocol/server-postgres), which is part of the official MCP server registry.

Step 1: Get Your PostgreSQL Connection String

You need a connection URI in this format:

postgresql://username:password@hostname:5432/database_name

Where to find it:

  • Supabase: Project Settings → Database → Connection string (URI)
  • Neon: Dashboard → Connection Details → Connection string
  • Amazon RDS: Use your endpoint, port, and credentials
  • Local PostgreSQL: Typically postgresql://postgres:password@localhost:5432/mydb

For production databases, create a dedicated read-only user (covered in the security section below).

Step 2: Configure the MCP Server

Add the Postgres MCP server to your Claude Desktop configuration file.

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://readonly_user:[email protected]:5432/your_database"
      ]
    }
  }
}

For Claude Code (CLI), add it to your project's .mcp.json:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://readonly_user:your_password@localhost:5432/your_database"
      ]
    }
  }
}

Step 3: Restart Claude and Test

Close and reopen Claude Desktop (or restart Claude Code). You should see the Postgres tools available in the MCP tool list.

Test with a simple query:

"List all tables in the database"

Claude will run a schema introspection query and return your table names, column definitions, and relationships. If you see your tables, the connection is working.

Supabase MCP Server Alternative

If you are using Supabase, you have two options. You can use the generic Postgres MCP server with your Supabase connection string (as shown above), or you can use the dedicated Supabase MCP server which adds Supabase-specific features like managing auth users, storage buckets, and edge functions.

For pure database querying, the generic Postgres MCP server works perfectly with Supabase. Use the Supabase MCP server when you need to manage Supabase platform features beyond the database.

Security: The Non-Negotiable Checklist

Connecting an AI assistant to a production database demands careful security configuration. Skip none of these.

1. Create a Read-Only Database User

Never use your admin or application credentials. Create a dedicated user with SELECT-only permissions:

-- Create a read-only role
CREATE ROLE claude_readonly WITH LOGIN PASSWORD 'strong_random_password';

-- Grant connect access
GRANT CONNECT ON DATABASE your_database TO claude_readonly;

-- Grant usage on specific schemas
GRANT USAGE ON SCHEMA public TO claude_readonly;

-- Grant SELECT on all existing tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;

-- Grant SELECT on future tables automatically
ALTER DEFAULT PRIVILEGES IN SCHEMA public
  GRANT SELECT ON TABLES TO claude_readonly;

This ensures Claude can read data but cannot insert, update, delete, or modify your schema under any circumstances.

2. Restrict Schema Access

Only expose the schemas Claude needs. If your database has schemas for internal operations, background jobs, or sensitive data, do not grant access to them:

-- Only grant access to the public and analytics schemas
GRANT USAGE ON SCHEMA public, analytics TO claude_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public, analytics TO claude_readonly;

-- Explicitly revoke access to sensitive schemas
REVOKE ALL ON SCHEMA internal FROM claude_readonly;

3. Use Row-Level Security (Supabase and RLS-Enabled Databases)

If you are running PostgreSQL with row-level security, create policies that limit what the read-only user can see:

-- Example: only allow access to non-PII aggregated data
CREATE POLICY claude_access ON customers
  FOR SELECT
  TO claude_readonly
  USING (is_anonymised = true);

4. Set Statement Timeouts and Row Limits

Prevent runaway queries from locking resources or returning massive result sets:

-- Set a 30-second query timeout for this user
ALTER ROLE claude_readonly SET statement_timeout = '30s';

-- Set a work memory limit to prevent expensive sorts
ALTER ROLE claude_readonly SET work_mem = '64MB';

For row limits, instruct Claude through your system prompt or MCP server configuration to always append LIMIT 1000 to queries. Most Postgres MCP server implementations enforce this by default.

5. Never Embed Credentials in Version Control

Use environment variables for connection strings:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "${POSTGRES_MCP_CONNECTION_STRING}"
      ]
    }
  }
}

Set the environment variable in your shell profile or secrets manager. Your connection string stays out of your config files and git history.

Query Optimisation Tips

Claude generates SQL based on your schema and question. Help it write efficient queries with these practices.

Provide Schema Context Up Front

At the start of a session, ask Claude to inspect your schema:

"List all tables with their columns and indexes"

This gives Claude the context it needs to write queries that use the right joins, reference the correct column names, and take advantage of existing indexes.

Guide Complex Queries Incrementally

For multi-step analysis, break it down:

  1. "Show me the schema for the orders and customers tables"
  2. "What is the total revenue per customer segment for Q1 2026?"
  3. "Now add month-over-month growth rates"

This approach produces better SQL than a single complex prompt because Claude builds understanding progressively.

Ask Claude to Explain Its Queries

When you get unexpected results, ask:

"Show me the SQL you ran and explain the joins"

Claude will walk through its query logic. This helps you catch issues like missing WHERE clauses, incorrect join types, or aggregation errors before you act on the data.

Use Views for Repeated Queries

If your team asks the same questions regularly, create database views and tell Claude about them:

CREATE VIEW monthly_revenue AS
SELECT
  date_trunc('month', created_at) AS month,
  plan_tier,
  SUM(amount) AS total_revenue,
  COUNT(DISTINCT customer_id) AS customer_count
FROM payments
WHERE status = 'completed'
GROUP BY 1, 2;

Now Claude can query monthly_revenue directly — simpler, faster, and consistent.

Production Best Practices

Use a Read Replica

Point the Postgres MCP server at a read replica, not your primary database. This eliminates any risk of query load affecting your production application. Every major cloud provider (RDS, Cloud SQL, Supabase) supports read replicas, and the connection string is the only thing that changes.

Audit Query Logs

Enable PostgreSQL query logging for the read-only user so you can review what Claude executes:

ALTER ROLE claude_readonly SET log_statement = 'all';

Review these logs periodically. They also serve as a useful record of what questions your team is asking — which can inform dashboard and reporting priorities.

Separate Environments

Maintain separate MCP configurations for development, staging, and production. Never connect Claude to production during exploratory work. Use a staging replica for experimentation and reserve the production connection for validated, team-approved workflows.

Rotate Credentials on a Schedule

Treat the MCP database user like any service account. Rotate the password quarterly (or more frequently if required by your compliance framework), and update the connection string in your secrets manager.

Monitor Connection Pools

The Postgres MCP server creates a database connection for each session. If multiple team members use it simultaneously, monitor your connection pool limits. Set max_connections appropriately for the read-only user, or use a connection pooler like PgBouncer.

MCP Server Examples: What Teams Are Building

The Postgres MCP server is one of the most practical MCP server examples because nearly every application has a database behind it. Here is what we are seeing teams build:

  • On-demand analytics — product managers querying user behaviour data without waiting for engineering to write reports
  • Customer support tooling — support agents asking Claude to look up account status, subscription history, and usage data in real time
  • Financial reconciliation — finance teams cross-referencing payment records, invoices, and ledger entries through natural language
  • Data quality monitoring — engineering teams running integrity checks and catching data issues before they propagate
  • Sprint planning — pulling feature usage data to prioritise the backlog based on actual user behaviour rather than assumptions

Frequently Asked Questions

Is the Postgres MCP server safe to use with production databases?

Yes, when configured correctly. Use a dedicated read-only database user with SELECT-only permissions, connect through a read replica, set statement timeouts, and restrict schema access. These measures ensure Claude can query data without any ability to modify it. Audit logging adds an additional layer of visibility.

Does the Postgres MCP server work with Supabase?

Yes. Supabase is PostgreSQL under the hood, so the standard Postgres MCP server connects to it using your Supabase connection string. You can also use the dedicated Supabase MCP server if you need to manage platform features like authentication, storage, and edge functions beyond database queries.

Can Claude write data or modify my database schema?

Not if you follow the security configuration above. A read-only database user with only SELECT permissions cannot insert, update, delete, or alter tables. PostgreSQL enforces this at the database level regardless of what Claude attempts. The MCP server simply passes queries through.

What is the difference between a Postgres MCP server and a general SQL MCP server?

A Postgres MCP server is optimised for PostgreSQL-specific features like schemas, extensions, row-level security, and PostgreSQL query syntax. A general SQL MCP server may support multiple database engines (MySQL, SQLite, SQL Server) but might not leverage PostgreSQL-specific capabilities. Use the Postgres-specific server for better schema introspection and query generation.

What Comes Next

The Postgres MCP server handles the most common use case — querying a database. But most teams have data spread across multiple systems: databases, APIs, internal tools, and SaaS platforms. The natural next step is building custom MCP connectors that bring all of those sources into a single Claude conversation.

The pattern is the same every time: identify where you are context-switching, build the bridge, and let AI work with full context instead of fragments.


Need help connecting Claude to your database or building custom MCP integrations? We have shipped Postgres MCP server setups, Supabase integrations, and custom data connectors for teams across fintech, SaaS, and professional services — typically in 2-4 weeks with fixed pricing. Talk to us.

More articles

Claude Cowork vs Chat: What Merges, and the Key Dates

Chat and Cowork are becoming one Claude. Team turns on by default 1 December 2026, the separate experience retires 1 February 2027, and ZDR orgs are excluded.

Read more

Can an Australian Business Claim Its ChatGPT Profile? What Is Actually Available

OpenAI launched Businesses in ChatGPT on 10 November 2026. Business Agents are US-only, and local stores and restaurants can claim US listings only. Here is what an Australian business can do today.

Read more

Let's build something great together.

Melbourne, Australia — serving founders worldwide. [email protected]