Back to Skill Directory

MCP Server

DatabaseRead-Only by DefaultMIT License

Postgres MCP Server

Reference server · modelcontextprotocol/servers

Postgres MCP Server gives your AI coding assistant a safe, read-only view into any PostgreSQL database. Instead of copy-pasting schema into the chat and guessing at column names, the agent inspects the live database — listing tables, describing columns, running EXPLAIN — and writes correct SQL on the first try.

For engineering teams, this collapses a recurring friction point: debugging production data. The agent can join five tables, filter by tenant, and return a summary in the time it used to take to remember whether that timestamp column was created_at or inserted_at.

RO
Transaction Mode
read-only by default
<2min
Setup
connection string + npx
PG 12+
Dialects
incl. RDS, Neon, Supabase
5+
Schema Tools
list, describe, explain

Quick Install

claude mcp add postgres -- npx -y @modelcontextprotocol/server-postgres postgresql://readonly:pass@host:5432/db

Key Features

Run SQL Queries

Execute any SELECT statement the role can run. Results stream back as structured rows the agent can reason about directly.

Inspect Schema

List schemas, tables, views, and materialized views. Agent uses this to orient itself before writing queries against an unfamiliar database.

Describe Tables

Full column metadata including types, nullability, defaults, primary keys, foreign keys, and column comments.

Explain Plans

Run EXPLAIN and EXPLAIN ANALYZE from natural language. Agent can diagnose a slow query by reading the plan itself.

Read-Only Safety

Every query is wrapped in a read-only transaction, blocking INSERT / UPDATE / DELETE / DDL at the database level.

Multi-Database

Register multiple Postgres MCP instances side by side — one for prod replica, one for staging — and the agent picks the right one by name.

Execution Brief

Use this page as a rollout checklist, not just reference text.

Suggest update

Tool Mapping Lens

Organize Tools by Workflow Phase

Catalog-oriented pages work best when users can map discovery, evaluation, and rollout in a clear path instead of reading an undifferentiated list.

  • Define the job-to-be-done first
  • Group tools by stage
  • Prioritize by adoption friction

Actionable Utility Module

Skill Implementation Board

Use this board for Postgres MCP Server before rollout. Capture inputs, apply one decision rule, execute the checklist, and log outcome.

Input: Objective

Deliver one measurable improvement with postgres mcp server claude code sql schema inspection

Input: Baseline Window

20-30 minutes

Input: Fallback Window

8-12 minutes

Decision TriggerActionExpected Output
Input: one workflow objective and release owner are definedRun preview execution with fixed acceptance criteria.Go or hold decision backed by repeatable evidence.
Input: output quality below baseline or retries increaseLimit scope, isolate root issue, and rerun controlled test.One confirmed correction path before wider rollout.
Input: checks pass for two consecutive replay windowsPromote to broader traffic with fallback path active.Stable rollout with low operational surprise.

Execution Steps

  1. Record objective, owner, and stop condition.
  2. Execute one controlled preview run.
  3. Measure quality, latency, and correction burden.
  4. Promote only when pass criteria are stable.

Output Template

tool=postgres mcp server claude code sql schema inspection
objective=
preview_result=pass|fail
primary_metric=
next_step=rollout|patch|hold

What Is Postgres MCP Server?

Postgres MCP Server is a Model Context Protocol server that exposes a PostgreSQL database to any MCP-compatible client. Under the hood it uses the standard node-postgres driver and wraps all queries in a read-only transaction, making it safe to point at production replicas without worrying about accidental writes.

The server turns your database schema into first-class context for the agent. Instead of dumping DDL into the prompt, the agent calls list_schemas, list_tables, and describe_table on demand — pulling just the metadata it needs for the current question. This keeps token usage low and keeps schema information fresh, even when tables change mid-session.

Because it speaks vanilla Postgres over the wire protocol, it works with every hosted provider: AWS RDS, Google Cloud SQL, Azure Database for Postgres, Neon, Supabase, Timescale, Crunchy Bridge, and self-hosted instances. Anywhere psql can connect, this server can connect.

The most common production pattern is to create a dedicated read-only role (CREATE ROLE ai_readonly; GRANT USAGE ON SCHEMA public, GRANT SELECT ON ALL TABLES), connect the MCP server with that role, and point it at a replica. You get an AI-native database debugging workflow with zero blast radius.

How to Calculate Better Results with postgres mcp server claude code sql schema inspection

Create a dedicated read-only role in Postgres. Grant USAGE on the schemas you want exposed and SELECT on the tables within them. Revoke anything sensitive.

Register the server with your MCP client. In Claude Code: claude mcp add postgres -- npx -y @modelcontextprotocol/server-postgres "postgresql://ai_readonly:pw@replica.example.com:5432/app". Store the password in a secret manager if possible.

Verify with a low-risk prompt: "List all tables in the public schema and count the rows in each." If the agent answers correctly, your wiring is good.

Add schema descriptions via COMMENT ON COLUMN — the agent reads these and uses them to pick the right column for ambiguous questions. A small investment in comments pays off every single session.

Treat this page as a decision map. Build a shortlist fast, then run a focused second pass for security, ownership, and operational fit.

When a team keeps one shared selection rubric, tool adoption speeds up because evaluators stop debating criteria every time a new option appears.

Worked Examples

Debugging a customer support ticket

  1. Support forwards a ticket: "User taojianan888@gmail.com sees 0 credits but claims they bought 100"
  2. Ask the agent: "Find this user in the database and show their most recent 10 credit transactions"
  3. Agent calls list_tables, finds users and credit_transactions
  4. Agent describes both tables, notices users.email and credit_transactions.user_id
  5. Agent writes: SELECT ct.* FROM credit_transactions ct JOIN users u ON u.id = ct.user_id WHERE u.email = $1 ORDER BY ct.created_at DESC LIMIT 10
  6. Agent returns a table showing a refund event zeroed out their balance at 03:42 UTC

Outcome: Root-cause identified in 45 seconds without opening psql, pgAdmin, or an internal admin panel.

Diagnosing a slow endpoint

  1. Your /api/dashboard endpoint is p95 = 1.8s and you suspect a missing index
  2. Ask: "Run EXPLAIN ANALYZE on the dashboard query and tell me what index is missing"
  3. Agent runs EXPLAIN ANALYZE via the MCP tool
  4. Agent spots a Seq Scan on events filtering by tenant_id and created_at
  5. Agent suggests: CREATE INDEX idx_events_tenant_created ON events(tenant_id, created_at DESC)
  6. You apply the index in a separate migration tool (not via the read-only MCP)

Outcome: Actionable index recommendation derived from the live query plan, with evidence the agent can point to in the EXPLAIN output.

Frequently Asked Questions

What is the Postgres MCP Server?

Postgres MCP Server is a Model Context Protocol server that connects AI agents to a PostgreSQL database. It exposes tools for listing schemas and tables, describing columns and indexes, and running SQL queries — by default in a read-only transaction — so your agent can answer data questions without risking writes against production.

How do I install it?

The reference implementation ships as @modelcontextprotocol/server-postgres. Register it with your MCP client, passing the connection string: claude mcp add postgres -- npx -y @modelcontextprotocol/server-postgres postgresql://user:pass@host:5432/db. Use a read-only database role in the connection string for maximum safety.

Is it safe to run against production?

The reference server wraps queries in a read-only transaction, which blocks INSERT / UPDATE / DELETE / DDL at the database level. Still, best practice is to connect with a dedicated read-only Postgres role (GRANT SELECT only), point at a replica if you have one, and keep write access on a separate MCP server that requires explicit approval.

What does the agent see when it inspects schema?

The agent can list schemas and tables, describe columns with their types and nullability, see primary and foreign keys, list indexes, and view table and column comments. This is usually enough context for the agent to write correct JOINs without you hand-feeding the schema.

Can it run complex analytics queries?

Yes. The server runs any SELECT the underlying role is allowed to execute, including CTEs, window functions, and EXPLAIN ANALYZE. For very large result sets, ask the agent to LIMIT or aggregate first — most MCP clients truncate responses that exceed a few thousand rows.

How does it compare to Supabase MCP?

Postgres MCP is a generic server for any Postgres instance — RDS, Neon, Supabase, self-hosted, whatever. Supabase MCP is specialized: it also exposes Auth, Storage, and Edge Function tools on top of SQL. Use Postgres MCP for generic DB access, Supabase MCP when you are all-in on the Supabase platform.

Missing a better tool match?

Send the exact workflow you are solving and we will prioritize a new comparison or rollout guide.