Blog

Claude Code PostgreSQL MCP Integration Guide

How to connect Claude Code to PostgreSQL via MCP, covering setup, five key workflows, read-only mode, and safety considerations for production databases.

Phos Team ·
claude code

What the PostgreSQL MCP Server Does

The PostgreSQL MCP server creates a direct connection between Claude Code and any Postgres database. Once connected, Claude can inspect your schema, describe tables and indexes, analyze query plans, and execute SQL directly within a session.

This changes the development loop for database-heavy work. Instead of copying schema definitions into prompts or switching between your terminal and Claude, Claude has live access to the database state. If you are new to Claude Code, the Claude Code course covers how to structure prompts and workflows like this effectively. It generates SQL that matches your actual column names, data types, and constraints. It can analyze slow queries against the real execution plan, not a hypothetical one.

The server works with any Postgres-compatible database: PostgreSQL, Aurora Postgres, CockroachDB, Neon, and others.

When Claude has a live connection to your database, it stops guessing at your schema and starts generating SQL that works.


Installation

The most widely used Postgres MCP server is published by the MCP community.

pip install mcp-server-postgres

Alternatively, there is a Node.js version:

npm install -g @modelcontextprotocol/server-postgres

Use whichever matches your local Python or Node.js setup.


Configuration

The server requires a Postgres connection string. Use the standard format:

postgresql://username:password@host:port/database

Add the server to your project’s .mcp.json for project-specific database access:

{
  "mcpServers": {
    "postgres": {
      "command": "python",
      "args": ["-m", "mcp_server_postgres"],
      "env": {
        "DATABASE_URL": "postgresql://dev_user:password@localhost:5432/myapp_dev"
      }
    }
  }
}

For the Node.js version:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://username:password@localhost:5432/myapp"]
    }
  }
}

Restart Claude Code after saving the config. Verify the connection:

What tables exist in the connected database?

Read-Only Mode: A Safety Consideration

Before configuring the server, decide on the access level. Connecting with a full-privilege database user gives Claude write access to your data. For schema exploration and query building, this is unnecessary.

Create a read-only database role:

CREATE ROLE claude_readonly;
GRANT CONNECT ON DATABASE myapp_dev TO claude_readonly;
GRANT USAGE ON SCHEMA public TO claude_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO claude_readonly;

CREATE USER claude_mcp WITH PASSWORD 'secure_password';
GRANT claude_readonly TO claude_mcp;

Use this user’s credentials in the connection string. Claude can inspect the full schema and run any SELECT query but cannot modify data.

For development databases where data modification is acceptable, a standard dev user with limited privileges (not superuser) is a reasonable middle ground.


5 Workflows the PostgreSQL MCP Server Enables

Workflow 1: Schema Inspection

Map the full database structure before starting feature work.

Describe every table in the public schema. Show columns, data types, nullable status, 
default values, and primary keys. Also list all foreign key relationships.

Claude reads the information schema and produces a structured summary. This is especially useful when working with an inherited codebase or a database built by another team.


Workflow 2: Query Generation

Generate complex queries grounded in the actual schema.

Write a query that shows the top 10 customers by total order value in the last 90 days, 
including their name, email, order count, and total spend. 
Use the actual table and column names from the schema.

Claude inspects the schema, identifies the relevant tables and join paths, then writes a query that references real column names. The output runs correctly without manual substitution.


Workflow 3: Data Analysis

Answer business questions about the data by generating and running analytical queries.

How many users signed up each month for the past year? 
Show month, count, and cumulative total. Run the query and show the results.

With permission to execute queries, Claude generates the SQL, runs it, and presents the results in a readable format. This removes the need to switch between Claude and a database client for analytical work.


Workflow 4: Migration Writing

Generate migration SQL based on a description of the desired schema change.

I need to add soft delete support to the products table. 
Add a deleted_at timestamp column (nullable) and an is_deleted boolean (default false).
Also add an index on is_deleted to keep filtered queries fast.
Write the migration SQL.

Claude reads the current table definition and generates migration SQL that accounts for the existing structure, uses the correct column types, and includes appropriate indexes.


Workflow 5: Index Recommendations

Identify missing indexes by analyzing query patterns.

Here are three queries that are running slowly on the orders table. 
Analyze the table's current indexes and recommend which new indexes would 
help each query. Explain the trade-offs.

Claude reads the current index definitions, analyzes the query structure, and recommends indexes with an explanation of why each one helps and what write overhead it adds. You can also ask Claude to run EXPLAIN ANALYZE on a specific query for a concrete execution plan.


Connecting to Multiple Databases

Use distinct keys to connect multiple databases simultaneously.

{
  "mcpServers": {
    "postgres-dev": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://dev_user:pass@localhost:5432/myapp_dev"]
    },
    "postgres-staging": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://readonly:pass@staging-host:5432/myapp"]
    }
  }
}

Reference the correct database by name in your prompt:

Using the staging database, compare the user count to the dev database.

Frequently Asked Questions

Can Claude accidentally delete or modify data?

If you connect with a write-capable user, Claude can execute any SQL including DELETE and UPDATE statements. The safest approach is using a read-only database user as described above. For development databases where some modification is acceptable, be explicit in your prompts about what you want Claude to do. Claude will not modify data unless asked to.

Does the connection stay open during the full session?

Yes. The MCP server maintains a connection pool for the duration of the Claude Code session. The connection closes when Claude Code closes. For databases that enforce connection limits, be aware that each Claude Code session consumes a connection.

Can I use this server with a cloud-hosted Postgres database?

Yes. Any Postgres database reachable from your machine works: Amazon RDS, Google Cloud SQL, Azure Database for PostgreSQL, Neon, PlanetScale, and others. Ensure your IP is in the database’s allowlist and that SSL is configured correctly in the connection string if required.

How is this different from using the Supabase MCP server?

The Supabase MCP server connects through the Supabase Management API and exposes Supabase-specific features like auth, storage, and edge functions. The Postgres MCP server connects directly to the database engine and works with any Postgres database, not just Supabase projects. If your project uses Supabase, either server works for database access. The Supabase server is more appropriate if you also need access to auth and storage.


Ready to give Claude live access to your PostgreSQL database?

Start by creating a read-only database user, configure the connection string, and run through the schema inspection workflow to verify the connection is working.

Path one: set it up yourself. Follow the installation and configuration steps above, begin with read-only access, and expand permissions once you are confident in the setup. The Claude Code course covers how to structure database-heavy workflows effectively.

Path two: work with Phos AI Labs. If you want PostgreSQL MCP integrated as part of a full Claude Code developer workflow, including multi-environment configuration and connecting database access to broader development operations, we handle that implementation. Phos AI Labs is a CCA-F certified Claude implementation partner. Thirty minutes, no deck. Start here.

Related articles

The fastest way to know whether we're the right fit, is a conversation.

STEP 1/2 · ABOUT YOU