Skip to content

Blog Article

PostgreSQL MCP Server for AI Agents

Connect AI coding agents to PostgreSQL via MCP. Schema awareness, migration tracking, and structured queries — without raw SQL access.

By AppHandoff Team · Published · 8 min read

TutorialMCPDatabase

AI coding agents write better code when they know your database schema. Without that context, they guess column names, invent table relationships, and produce queries that fail at runtime. A PostgreSQL MCP server solves this by exposing your schema, constraints, and migration history as structured data that any MCP-compatible agent can consume. Instead of pasting CREATE TABLE statements into a prompt, the agent calls a tool and gets the real schema — current, complete, and typed.

Why Database Context Matters for AI Agents

Consider a typical scenario: you ask an agent to build a user profile endpoint. Without database context, it generates a query against a 'users' table with columns it assumes exist — name, email, created_at. Your actual table is called 'profiles', has a 'display_name' column instead of 'name', stores emails in a separate 'auth.users' table managed by Supabase, and uses 'inserted_at' instead of 'created_at'. The generated code compiles fine but crashes on the first request.

With a PostgreSQL MCP server, the agent calls get_db_schema() before writing a single line. It sees every table, column, type, constraint, and foreign key relationship. It knows that profiles references auth.users via a foreign key on user_id. It knows that display_name is a varchar(255) with a NOT NULL constraint. The code it generates matches your actual database because it has your actual database schema.

How PostgreSQL MCP Servers Work

An MCP server for PostgreSQL connects to your database (usually via a read-only connection string) and exposes tools that agents can call over the Model Context Protocol. The protocol uses JSON-RPC 2.0 over Streamable HTTP transport, so the server can run anywhere — locally, on your VPS, or as a managed service. The agent discovers available tools via the MCP handshake, then calls them as needed during a coding session.

The core tools typically include schema introspection (list tables, describe columns, show constraints and indexes), relationship mapping (foreign keys, junction tables, enum types), and optionally read-only query execution for validation. More advanced servers add migration history, schema diffing between branches, and change tracking so the agent knows not just what the schema is, but how it got there.

// .cursor/mcp.json — PostgreSQL MCP server config
{
  "mcpServers": {
    "postgres": {
      "url": "https://your-mcp-server.com/mcp",
      "headers": {
        "Authorization": "Bearer <your-api-key>"
      }
    }
  }
}

// Agent tool call:
// get_db_schema({ project_id: "abc-123" })
// Returns: tables, columns, types, constraints, foreign keys

What Tools Are Available

A well-built PostgreSQL MCP server exposes several categories of tools. Schema tools let agents list all tables in a schema, describe individual tables with column types and constraints, and enumerate foreign key relationships. These are the most frequently called tools — agents use them at the start of nearly every task that touches the database.

Query tools allow agents to run read-only SQL for validation. An agent might execute a SELECT query to verify that the data shape matches its assumptions before generating application code. The read-only constraint is critical — you never want an AI agent running ALTER TABLE or DROP in production. Connection strings should use a role with SELECT-only permissions.

Migration tools expose the history of schema changes: which migrations have been applied, what each migration changed, and whether there are pending migrations. This context helps agents understand why the schema looks the way it does and avoids generating code that conflicts with in-flight migrations.

# Example tool responses from a PostgreSQL MCP server:

## get_db_schema response (truncated):
{
  "tables": [
    {
      "name": "projects",
      "schema": "public",
      "columns": [
        { "name": "id", "type": "uuid", "nullable": false, "default": "gen_random_uuid()" },
        { "name": "name", "type": "text", "nullable": false },
        { "name": "owner_id", "type": "uuid", "nullable": false },
        { "name": "created_at", "type": "timestamptz", "nullable": false }
      ],
      "foreign_keys": [
        { "column": "owner_id", "references": "auth.users(id)" }
      ]
    }
  ]
}

How AppHandoff Uses PostgreSQL Context

AppHandoff pairs naturally with a PostgreSQL MCP server. The database server gives your agent the live schema; AppHandoff gives it the coordination layer — which tickets touch which interfaces, what contracts other agents have published, and what work is in flight. Together, agents see not just the schema in isolation but how it relates to the agreed API surface.

Published contracts make the pairing concrete. If your API contract says a 'count' field is a number but the database column is a bigint (which PostgreSQL returns as a string in some drivers), an agent with both servers connected can catch the disagreement while implementing the endpoint — the contract states the agreed shape, and the schema shows what the database will actually produce.

PostgreSQL MCP vs. Raw SQL Access

Some teams give agents direct database access via connection strings. This works but has significant drawbacks. First, security: a connection string with write access in an AI agent's context is a disaster waiting to happen. Second, context quality: raw SQL results are untyped text blobs that the agent must parse. Third, scope: an agent with a connection string can only see the database, not how it relates to the rest of your architecture.

An MCP server provides guardrails (read-only access, tool-level permissions), structure (typed JSON responses instead of text tables), and integration (schema data alongside API specs and frontend contracts). The tradeoff is setup complexity — you need to run or connect to an MCP server. For teams using AppHandoff, the setup is already done: connect your project and the schema tools are available immediately via the MCP server at /mcp-server.

Setting Up a PostgreSQL MCP Server

If you want to run a standalone PostgreSQL MCP server, several open-source options exist. The community postgres-mcp-server package connects directly to a PostgreSQL instance and exposes schema and query tools. You provide a read-only connection string, configure which schemas to expose, and point your editor's MCP config at the server URL — the same flow as setting up an MCP server in Cursor. If your database is hosted on Supabase, the Supabase MCP guide for Claude Code covers the hosted option.

# Standalone PostgreSQL MCP server setup:

# 1. Create a read-only database role
CREATE ROLE mcp_reader WITH LOGIN PASSWORD 'secure-password';
GRANT USAGE ON SCHEMA public TO mcp_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mcp_reader;

# 2. Run the MCP server
npx @modelcontextprotocol/server-postgres \
  --connection-string "postgresql://mcp_reader:secure-password@localhost:5432/mydb" \
  --port 3100

# 3. Add to your editor config (.cursor/mcp.json):
# { "mcpServers": { "postgres": { "url": "http://localhost:3100/mcp" } } }

Best Practices

Always use a read-only database role. Never expose write access through an MCP server. Limit schema exposure to the schemas your application uses — exclude pg_catalog, information_schema, and internal schemas. Enable migration tracking so agents understand schema evolution. Cache schema responses (schemas change infrequently, so a 5-minute cache is reasonable) to reduce database load during active agent sessions.

For teams already using AppHandoff, connect both servers side by side: the PostgreSQL server for schema, AppHandoff for tickets, claims, and published contracts. Explore the MCP server documentation at /mcp-server for the complete tool reference.

Frequently asked questions

What is a PostgreSQL MCP server and what does it do?

A PostgreSQL MCP server connects AI coding agents to your database through the Model Context Protocol, exposing schema introspection tools that agents call during coding sessions. Instead of pasting CREATE TABLE statements into a prompt, the agent calls get_db_schema and receives a typed JSON response with every table, column, type, constraint, and foreign key relationship. This gives agents accurate database context before they write a single line of code.

Is it safe to give AI agents database access via MCP?

A properly configured PostgreSQL MCP server is safe because it uses a read-only database role that can only execute SELECT statements. This constraint is enforced at the PostgreSQL level with GRANT SELECT privileges, not just in the MCP server code, because agents can be creative with tool parameters. The MCP server adds additional guardrails by scoping access to specific schemas and logging all queries, giving you an audit trail of what the agent read.

How does database schema context improve AI-generated code quality?

Without schema context, agents guess column names, invent table relationships, and generate queries against tables or fields that do not exist. With a PostgreSQL MCP server, agents call schema introspection tools before writing any database-related code, so they know the exact column names, nullable constraints, foreign key relationships, and index strategies. Code that would otherwise fail at runtime with column-not-found errors succeeds on the first execution.

What is the difference between a standalone PostgreSQL MCP server and AppHandoff?

A standalone PostgreSQL MCP server connects directly to a single database and exposes schema and query tools in isolation. AppHandoff covers the coordination layer around it: handoff tickets, claims, milestones, and API contracts published by the agents that own them. Connected together, agents can check an implementation against both the live schema and the agreed contract — catching disagreements like a bigint column being returned as a string in certain database drivers.

How do I set up read-only database access for an MCP server?

Create a dedicated PostgreSQL role with login permissions but only SELECT privileges on your application schemas. Use GRANT USAGE ON SCHEMA and GRANT SELECT ON ALL TABLES IN SCHEMA to restrict access to only what the agent needs. Set ALTER DEFAULT PRIVILEGES to ensure new tables are automatically readable by the role as they are created. Never use a superuser or application role for MCP access, and store the connection string in a secrets manager rather than in plaintext configuration files.