Skip to main content
Glama
RachelHuangZW

postgres-mcp

postgres-mcp

An MCP server that connects Claude Desktop to a PostgreSQL database, exposing both direct query tools and an AI-powered query optimization pipeline built on SQL-Surgeon.

What it does

This project wraps two layers of capability into a single MCP server:

Layer 1 — Direct database tools: Claude can execute SQL, inspect execution plans, and query table schemas against a live PostgreSQL database.

Layer 2 — AI query optimization pipeline: Claude can invoke a multi-step LangGraph agent (SQL-Surgeon) that analyzes a slow query, identifies performance bottlenecks, generates optimization advice, self-reviews the advice for quality, and optionally benchmarks the result in a sandbox schema.

The MCP interface means Claude decides which tool to use based on the user's question — no manual tool selection needed.

Related MCP server: @yawlabs/postgres-mcp

Architecture

Claude Desktop
      │
      │  MCP protocol
      ▼
  server.py              ← tool registration + MCP entry point
      │
  tools.py               ← tool logic
      │
  ┌───┴──────────────────────────────────┐
  │                                      │
db.py                            agent/graph.py
(Layer 1: direct tools)          (Layer 2: LangGraph pipeline)
  │                                      │
  ├── execute_query          ┌───────────┼───────────┐
  ├── explain_query          ▼           ▼           ▼
  ├── list_tables       run_explain  identify_issues  generate_advice
  ├── get_table_schema       │           │           │
  └── get_slow_queries       └───────────┴───────────┘
                                         │
                                   review_advice  ←── retry loop (max 2x)
                                         │
                            generate_benchmark_schema (optional)

MCP Tools

Tool

Parameters

Description

execute_query

sql

Run any SQL; SELECT returns JSON rows, DML returns affected row count

explain_query

sql, analyze (bool, default false)

Get query execution plan; analyze=true runs EXPLAIN (ANALYZE, BUFFERS)

list_tables

schema (default "public")

List all tables in a schema

get_table_schema

table_name, schema (default "public")

List columns, types, nullability, defaults, and indexes

get_slow_queries

limit (default 5)

Return the slowest queries by mean execution time from pg_stat_statements

analyze_query

sql, ddl (optional, auto-fetched if omitted), table_name (optional)

Run full SQL-Surgeon optimization pipeline; returns issues, advice, optimized SQL, and optional benchmark

SQL-Surgeon Pipeline

analyze_query invokes a 5-node LangGraph graph:

  1. run_explain — executes EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS, FORMAT JSON) against the real database

  2. identify_issues — sends the execution plan + DDL to Gemini 2.5 Pro; returns a JSON array of identified bottlenecks (missing indexes, sequential scans, row count misestimation, etc.)

  3. generate_advice — generates specific optimization recommendations and a complete optimized SQL script (index DDL + rewritten query)

  4. review_advice — a second LLM call acting as a senior DBA reviewer; returns pass or retry with feedback; retries up to 2 times

  5. generate_benchmark_schema (optional) — clones the target table into a temporary schema, applies the suggested DDL, and re-runs EXPLAIN to compare plans

Project Layout

src/postgres_mcp/
    server.py           # MCP entry point, tool registrations
    tools.py            # Tool logic; calls db.py and agent/
    db.py               # Connection helper (reads DATABASE_URL)
    db_client.py        # DBClient used by the agent pipeline
    agent/
        graph.py        # LangGraph graph definition
        nodes.py        # 5 node functions
        state.py        # AgentState TypedDict
        prompts.py      # System prompts for each LLM node
tests/
    test_tools.py       # Unit tests with mocked DB connections
examples/
    claude_desktop_config.json

Setup

Prerequisites

  • Python 3.10+

  • uvbrew install uv

  • A running PostgreSQL instance

  • Claude Desktop

  • A Google API key (Gemini 2.5 Pro) for analyze_query

Install

git clone https://github.com/RachelHuangZW/postgres-mcp
cd postgres-mcp
uv sync

Configure environment

Create .env in the project root:

DATABASE_URL=postgresql://user:password@localhost:5432/dbname
GOOGLE_API_KEY=your-google-api-key

Register with Claude Desktop

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

{
  "mcpServers": {
    "postgres-mcp": {
      "command": "uv",
      "args": [
        "run",
        "--directory", "/path/to/postgres-mcp",
        "--env-file", "/path/to/postgres-mcp/.env",
        "python", "-m", "postgres_mcp.server"
      ]
    }
  }
}

Fully quit and reopen Claude Desktop after saving.

Verify

Open Claude Desktop and ask:

"What MCP tools do you have available?"

Claude should list all six tools.

Development

uv sync --group dev
uv run pytest

Tests use mocked database connections and do not require a live PostgreSQL instance.

Tech Stack

  • MCP framework: FastMCP

  • Agent framework: LangGraph

  • LLM: Gemini 2.5 Pro via langchain-google-genai

  • Database: PostgreSQL via psycopg2

  • Package manager: uv

How this was built

This project was built with Claude Code as a pair-programming partner. I designed the architecture (two-layer tool exposure, separation of db.py vs db_client.py), made all technical decisions (MCP framework choice, LangGraph integration approach, security boundaries), and iterated on implementation with AI assistance. Every design decision documented in this README reflects my own thinking about MCP server design and enterprise database tool exposure.

Security Note

execute_query runs arbitrary SQL. Use a read-only database role in production or restrict access to trusted users only.

Available Tools

3 tools
execute_queryB

Execute a SQL query against the connected PostgreSQL database and return results as JSON.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3.2/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations exist, so the description must disclose behavioral traits. It mentions JSON output but fails to indicate whether the query can modify data (read-only vs write), what side effects occur, or any authorization requirements. This is insufficient for a potentially destructive operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise (one sentence) and front-loaded with the core action. However, it lacks structure (e.g., no sections or warnings) and could be slightly more informative without losing brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the presence of an output schema and the potential risks of SQL execution, the description is incomplete. It does not clarify read-only status, transaction behavior, error handling, or limitations. A more thorough description is needed for safe and correct agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, yet the description adds no meaning beyond the parameter name and type. There is no guidance on SQL format, statement constraints, or parameterization, leaving the agent to infer from the name alone.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool executes a SQL query against a PostgreSQL database and returns JSON results. It uses specific verbs and resources, and the sibling tools (explain_query, get_table_schema) suggest distinct purposes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No explicit when-to-use or when-not-to-use guidance is provided. The description implies usage for executing SQL queries, but does not contrast with siblings like explain_query or get_table_schema.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

explain_queryA

Return the EXPLAIN execution plan for a SQL query. Set analyze=True to run EXPLAIN ANALYZE (this actually executes the query).

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYes
analyzeNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It discloses the critical behavioral trait that setting analyze=True actually executes the query, but does not discuss other traits like idempotency or potential side effects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with two sentences containing no fluff. Every word adds value.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simple tool with only two parameters and existence of an output schema, the description is largely complete. It could optionally mention what the plan looks like or any limitations, but the output schema likely covers that.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description compensates well by explaining the 'sql' parameter implicitly and the 'analyze' parameter explicitly ('Set analyze=True to run EXPLAIN ANALYZE'). For two parameters, this adds meaningful context beyond the schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it returns the EXPLAIN execution plan for a SQL query, which distinguishes it from sibling tools like execute_query (executes the query) and get_table_schema (retrieves schema).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by mentioning the analyze flag, but it does not explicitly state when to use this tool versus execute_query or provide exclusions. It could add guidance like 'Use when you need the query plan instead of actual results.'

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

get_table_schemaB

Get columns and indexes for a PostgreSQL table.

ParametersJSON Schema
NameRequiredDescriptionDefault
schemaNopublic
table_nameYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

B3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries the full burden of behavioral disclosure. It only states what is retrieved (columns and indexes) but does not mention safety (read-only), required permissions, or limitations (e.g., no constraints or foreign keys).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence—'Get columns and indexes for a PostgreSQL table.'—with no filler or redundancy. It is front-loaded and earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's simplicity, the output schema exists (so return values need not be described), but the description omits important context like default behavior of the 'schema' parameter and the requirement that the table must exist. It is minimally complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, and the description adds no information beyond the parameter names. It does not explain that 'schema' defaults to 'public' or that 'table_name' is case-sensitive, providing no semantic value over the input schema.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb 'Get' and the resource 'columns and indexes for a PostgreSQL table'. It distinguishes from siblings 'execute_query' (execute SQL) and 'explain_query' (show query plan) by specifying exactly what artifact is retrieved.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives like 'execute_query' or 'explain_query'. There is no mention of prerequisites (e.g., table must exist) or context in which this tool is preferred.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A3.5/5.0
Disambiguation5/5

Each tool serves a distinct purpose: executing queries, explaining plans, and retrieving table schema. No overlap exists.

Naming Consistency5/5

All tools follow a consistent verb_noun snake_case pattern (execute_query, explain_query, get_table_schema) with clear, descriptive names.

Tool Count4/5

Three tools is slightly low for a database server, but the scope is focused on query execution and schema inspection, which is reasonable. Could benefit from additional tools like listing tables.

Completeness3/5

Core query execution and schema retrieval are covered, but missing tools to list tables or databases, manage transactions, or modify data directly. Agents would need to rely on raw SQL for many operations.

Maintenance

ActivitySlowing
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables natural language querying of PostgreSQL databases through the Model Context Protocol. It translates user questions into validated SQL, executes read-only queries safely, and returns results to MCP-compatible clients like Claude Desktop.
  • A
    license
    A
    quality
    A
    maintenance
    Query and manage PostgreSQL databases from Claude Code, Cursor, and any MCP client, with read-only by default and built-in schema introspection, EXPLAIN, and performance diagnostics.
    23
    6,977
    3
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/RachelHuangZW/postgres-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server