Skip to main content
Glama
mcp-postgres-readonly

mcp-postgres-readonly

mcp-postgres-readonly

A read-only Model Context Protocol server for any Postgres database. Point it at a connection string and an AI agent (Claude Desktop, Claude Code, or any MCP client) can explore the schema and answer questions with SQL, without being able to change a row.

TypeScript on Bun, the official @modelcontextprotocol/sdk over stdio, Zod-typed inputs, and a test suite that runs against a real Postgres.

The five tools

Tool

Input

What it returns

list_tables

schema?

Tables and views in the allowed schemas, with kind, estimated row count and comment.

describe_table

table, schema?

Columns (type, nullability, default), primary key, foreign keys with what they reference, and indexes.

query

sql, limit? (default 100, max 1000)

The rows of one read-only SELECT, as JSON.

sample_rows

table, schema?, limit? (default 10, max 100)

The first rows of a table, to see what the data looks like.

explain

sql

The execution plan of a SELECT (EXPLAIN, never ANALYZE): planned, not executed.

query and sample_rows answer with the same shape:

{
  "columns": ["status", "n"],
  "rows": [{ "status": "paid", "n": "3" }, { "status": "pending", "n": "2" }],
  "row_count": 2,
  "truncated": false,
  "truncated_by": null
}

bigint and numeric come back as strings (no precision loss), timestamps as ISO 8601, bytea as \x hex. A failure comes back as a tool error the agent can read and act on, with the Postgres error code:

Postgres error 25006: cannot execute nextval() in a read-only transaction

Related MCP server: mcp-data-gateway

Safety model

Each layer below has a test in tests/safety.test.ts that fails if the layer is removed.

  1. Read-only transaction. Every statement, including the server's own catalog queries, runs inside BEGIN TRANSACTION READ ONLY and is always rolled back. This is the real guarantee: Postgres itself rejects INSERT/UPDATE/DELETE/DDL, SELECT ... FOR UPDATE, SELECT ... INTO, sequence changes, and a DELETE hidden inside a CTE.

  2. One statement per call, enforced by the wire protocol. SQL from the agent is sent with Postgres's extended query protocol, which refuses more than one statement per message. A COMMIT; DELETE ... cannot step out of the read-only transaction.

  3. Text filter before the database. Input that is not a single SELECT (or WITH ... SELECT) is rejected without a round trip. The filter understands comments, string literals, quoted identifiers and dollar quoting, so a ; inside a string is fine and one outside is not. It is defense in depth; layers 1 and 2 hold without it.

  4. Statement timeout. statement_timeout is set for the transaction only, so a slow query is cancelled by Postgres and the pooled connection is left as it was.

  5. Schema allowlist. MCP_PG_SCHEMAS (default public) limits what the tools can see. list_tables, describe_table and sample_rows refuse anything else. For free SQL, the server asks Postgres for the plan first and refuses it if it reads a table outside the allowlist; that covers unqualified names, subqueries, CTEs and views. search_path is set to the allowlist.

  6. Safe identifiers. sample_rows looks the table up in the catalog by exact name, passed as a parameter, and builds its SQL from the catalog's answer with quoted identifiers.

  7. Result caps. Rows are read through a cursor and stop at the row limit or at MCP_PG_MAX_BYTES, whichever comes first. A cut result says so: "truncated": true and "truncated_by": "rows" | "bytes".

  8. The connection string stays private. It is read from DATABASE_URL only, never logged, and error messages are redacted before they reach the agent.

What this does not replace

Give the server a database role that can only SELECT what the agent should see. The role is the boundary; the layers above are there for when something else goes wrong. Two things only the role can stop: functions with side effects that Postgres allows in a read-only transaction (for example pg_terminate_backend or advisory locks, when the role may call them), and a function that reads another schema internally, which the plan check cannot see.

CREATE ROLE mcp_readonly LOGIN PASSWORD 'choose-one';
GRANT CONNECT ON DATABASE mydb TO mcp_readonly;
GRANT USAGE ON SCHEMA public TO mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mcp_readonly;

Other limits worth knowing: with the allowlist on, pg_catalog and information_schema are refused in free SQL unless you list them; a view is refused when it reads a table outside the allowlist; and two result columns with the same name collapse into one, so alias them.

Setup

Requires Bun 1.4 or later and a Postgres database (tested on Postgres 18).

git clone https://github.com/MaximilianoAdaro/mcp-postgres-readonly.git
cd mcp-postgres-readonly
bun install

To try it with sample data, load the demo schema (shop: customers, orders, order items) into a scratch database. It drops and recreates the shop schema:

psql "$DATABASE_URL" -f demo/seed.sql

The demo tables live in the shop schema, so set MCP_PG_SCHEMAS=shop in the configuration below when you try it; with the default public, list_tables comes back empty.

Claude Desktop

Add the server to claude_desktop_config.json (Settings, Developer, Edit Config) and restart Claude Desktop:

{
  "mcpServers": {
    "postgres-readonly": {
      "command": "bun",
      "args": ["/absolute/path/to/mcp-postgres-readonly/src/index.ts"],
      "env": {
        "DATABASE_URL": "postgresql://mcp_readonly:choose-one@127.0.0.1:5432/mydb",
        "MCP_PG_SCHEMAS": "public"
      }
    }
  }
}

If Claude Desktop cannot find bun, use its absolute path (which bun) as command.

Claude Code

claude mcp add postgres-readonly \
  -e DATABASE_URL=postgresql://mcp_readonly:choose-one@127.0.0.1:5432/mydb \
  -e MCP_PG_SCHEMAS=public \
  -- bun /absolute/path/to/mcp-postgres-readonly/src/index.ts

Then ask something like "which customers have more than one paid order?" and watch it call list_tables, describe_table and query.

Environment variables

Variable

Default

Meaning

DATABASE_URL

required

postgres:// or postgresql:// connection string. The only source of credentials.

MCP_PG_SCHEMAS

public

Comma-separated schema allowlist. The first one is the default for describe_table and sample_rows.

MCP_PG_STATEMENT_TIMEOUT_MS

5000

Per-statement timeout, in milliseconds.

MCP_PG_MAX_BYTES

262144

Maximum size of the rows one call returns, in bytes of JSON.

All of them are read and validated in one place, src/config.ts; the server refuses to start on an invalid value and names the variable without printing it.

Tests

The suite uses a real Postgres, no database mocks. It includes an end-to-end test that starts the server as a child process and calls every tool over stdio with the SDK's client, the same way Claude Desktop does.

bun run db:test:up    # Postgres 18 in Docker, on 127.0.0.1:54329
bun run verify        # typecheck + lint + tests
bun run db:test:down

To use another database, set DATABASE_URL_TEST. The suite drops and recreates the shop and shop_internal schemas, so it refuses any host that is not local.

CI runs the same verify on every pull request, against a Postgres service container (.github/workflows/ci.yml).

What a paid engagement adds

This repository is the Basic package: a read-only MCP server with up to five tools over one Postgres database or REST API, typed inputs, tests, and a README with setup for Claude Desktop and Claude Code. The same foundation extends to:

  • Standard: more tools shaped around your domain instead of raw SQL, write operations behind an explicit confirmation step, and token authentication over HTTP so a team can share one server.

  • Premium: OAuth, multi-tenant isolation, deployment to your infrastructure with monitoring, and an evaluation suite that measures how well agents actually use the tools.

About

Built by Maxi Adaro, freelance software engineer. This project was built with AI assistance; every line is reviewed and tested.

MIT License. See LICENSE.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      A
      quality
      D
      maintenance
      Enables AI agents to inspect and query PostgreSQL databases safely, with features like listing tables, retrieving schemas, and running read-only SQL queries.
      3
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to query a PostgreSQL database through a small set of controlled, read-only tools for schema inspection, row lookup, and aggregate statistics.
      1
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables LLM agents to explore and query a Postgres database through secure, read-only tools.
      -