Nov 23, 20266 min read

Postgres MCP Server: Let Your AI Agent Query the Database Safely

What a Postgres MCP server gives Claude Code or Cursor, why the reference server was deprecated after a read-only bypass, how to make database access read-only at the Postgres level, which database the agent should see, and how Encore's local MCP server connects an agent to the local database with a read-only role.

Illustration for Postgres MCP Server: Let Your AI Agent Query the Database Safely

A coding agent that cannot see the database guesses at it, and writes a migration for a column that already exists. A Postgres MCP server lets Claude Code or Cursor read the schema and run SQL instead.

Many setup guides do it by pasting a connection string with full write access into the agent's config. This guide covers access you can live with.

What does a Postgres MCP server do?

A Postgres MCP server implements the Model Context Protocol and exposes tools such as "list tables", "describe table" and "run query" that an agent calls during a session. What makes one safe is the database role it connects with and which database it points at, much more than the server you pick.

ServerWhat the agent can doHow read-only is enforcedStatus
Encore local MCP serverRead schemas, run SQL, call endpoints, read tracesConnects with a read-only database roleMaintained, part of the Encore CLI
Reference server-postgresRead schemas, run SQLWraps each query in a read-only transaction, which could be bypassedDeprecated and archived
Zed postgres-context-serverRead schemas, run SQLPatched fork of the reference serverMaintained fork
Postgres MCP ProRun SQL, index and health analysisrestricted mode with read-only transactions and a time limitMaintained, open source

Why was the reference Postgres MCP server deprecated?

The reference server ran each query inside BEGIN TRANSACTION READ ONLY, and the Postgres driver it used accepts several statements in one string, so a query that started with COMMIT; ended the read-only transaction and ran whatever came next with the connection's full privileges. Datadog Security Labs published the bypass in 2025, noting that the package had been deprecated in July and was still seeing about 21,000 weekly downloads on npm.

The broader point applies to every MCP server: a read-only promise made by the tool is only as strong as its parsing, and an agent that reads untrusted text, such as a support ticket stored in the database, can be steered into sending SQL you did not intend. Simon Willison calls the combination of private data, untrusted content and a way to send data out the lethal trifecta, and a database tool with write access adds the ability to change data on top.

How do you make a Postgres MCP server read-only?

Enforce it in Postgres with the role the server connects as. On Postgres 14 or later the predefined role pg_read_all_data grants SELECT on every table without any write privileges, and on older versions you grant SELECT on the schemas the agent needs. Setting default_transaction_read_only and a statement_timeout on that role with ALTER ROLE ... SET adds a second layer and stops a runaway query from loading the database.

-- Run as an admin on a local or staging database. CREATE ROLE agent_read LOGIN PASSWORD 'change-me'; GRANT pg_read_all_data TO agent_read; ALTER ROLE agent_read SET default_transaction_read_only = on; ALTER ROLE agent_read SET statement_timeout = '5s';

The role does not bypass row-level security, so tables protected by policies stay protected, and it can still read every row of every table it can see, which is why the choice of database matters as much as the role. The grants are one layer, not a sandbox. A SECURITY DEFINER function that PUBLIC can execute still writes with its owner's privileges, so revoke EXECUTE from PUBLIC on any write-capable function the agent could call.

Which database should the agent query?

Point the agent at the local development database or a staging database with generated data, where the worst outcome of a bad query is a slow laptop. Production holds customer data that ends up in the agent's context, and from there in prompts sent to a model provider and in session logs, so production access deserves the same review you would give a new contractor asking for a database login.

When the agent needs to understand a production issue, traces and logs usually answer the question with far less exposure than raw table access, and a read-only replica with masked columns is the safer route if table access is unavoidable.

How do you add a Postgres MCP server to Claude Code or Cursor?

In Claude Code, a local server is added with claude mcp add, where everything after -- is the command that starts the server, and --scope project writes it to a .mcp.json file the whole team shares. In Cursor the same entry goes in .cursor/mcp.json. Keep connection strings out of those files and pass them through environment variables, since project-scoped config is committed to the repository.

How does Encore's MCP server give an agent the database?

Encore

Encore is the safe way for AI agents to ship backend changes to your cloud, and its local MCP server is how an agent sees the app it is changing: the databases and their schemas, the endpoints, the Pub/Sub topics and the traces of the requests it made. Its query_database tool connects to the local development database, the same one encore run uses, with Encore's read-only encore-read role, whose only table privileges come from pg_read_all_data, as the CLI source shows.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.
Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

Add it to Claude Code from the app's directory, replacing your-app-id with the ID that encore mcp start prints:

claude mcp add --transport stdio --scope project encore -- encore mcp run --app=your-app-id

The agent then works against a service like this one, where the database and its migrations are declared in the code:

// orders/orders.go package orders import ( "context" "encore.dev/storage/sqldb" ) // get_databases returns this database's tables; query_database reads it with a read-only role. var db = sqldb.NewDatabase("orders", sqldb.DatabaseConfig{ Migrations: "./migrations", }) type Summary struct { Status string `json:"status"` Count int `json:"count"` } type SummaryResponse struct { ByStatus []Summary `json:"byStatus"` } //encore:api public method=GET path=/orders/summary func OrderSummary(ctx context.Context) (*SummaryResponse, error) { rows, err := db.Query(ctx, `SELECT status, count(*) FROM orders GROUP BY status ORDER BY status`) if err != nil { return nil, err } defer rows.Close() resp := &SummaryResponse{} for rows.Next() { var s Summary if err := rows.Scan(&s.Status, &s.Count); err != nil { return nil, err } resp.ByStatus = append(resp.ByStatus, s) } return resp, rows.Err() }

A typical loop for a request such as "add a refunded status and include it in the summary" has the agent call get_databases to read the current orders schema, write the migration and code, then use call_endpoint to hit /orders/summary and query_database to confirm the rows match, with get_traces showing how the request ran. The database itself is declared in the service code, so the same agent can add a new database or table in that change and have encore run create it locally. The query tool cannot write, so data changes happen through migrations and endpoints in the code, which the agent can run locally and a reviewer sees in the diff.

For people, encore db shell orders opens psql with read-only permissions by default, as the database docs describe, and --write has to be passed explicitly, so the same default holds for humans and agents. For deployed environments, the Cloud MCP server gives agents production traces, deployment status and infrastructure metadata, so a production question usually starts from a trace instead of the tables.

Best fit: Teams that want Claude Code or Cursor to read the current schema and data of the app it is changing, with writes going through reviewed code.

Frequently asked questions

What is a Postgres MCP server?

A Postgres MCP server is a Model Context Protocol server that gives an AI agent such as Claude Code or Cursor tools to list a database's tables and run SQL against it. The agent can then check the schema before writing a migration or look at the rows an endpoint returned instead of guessing.

Is the official Postgres MCP server safe to use?

No. The reference @modelcontextprotocol/server-postgres was deprecated and archived in 2025, and Datadog Security Labs showed that its read-only mode could be bypassed by stacking a COMMIT before a write. Use a maintained server and enforce read-only access with the database role itself.

How do I make a Postgres MCP server read-only?

Connect it with a dedicated role that can only read, for example one granted pg_read_all_data on Postgres 14 or later, and set default_transaction_read_only and a statement_timeout on that role. A read-only flag in the MCP server is useful, but the role is what Postgres enforces whatever SQL the agent sends.

How do I give Claude Code access to my Encore app's database?

Run claude mcp add --transport stdio encore -- encore mcp run --app=your-app-id in the app's directory. Encore's local MCP server then exposes get_databases and query_database, which run against the local development database with a read-only role, along with tools for calling endpoints and reading traces.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders