mcp-postgres-readonly
Provides read-only tools for exploring and querying a PostgreSQL database: list tables and views, describe columns, primary/foreign keys and indexes, run single SELECT queries with row/byte limits, sample rows, and explain query plans, all within read-only transactions and schema allowlists.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
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 |
|
| Tables and views in the allowed schemas, with kind, estimated row count and comment. |
|
| Columns (type, nullability, default), primary key, foreign keys with what they reference, and indexes. |
|
| The rows of one read-only |
|
| The first rows of a table, to see what the data looks like. |
|
| The execution plan of a |
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 transactionRelated 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.
Read-only transaction. Every statement, including the server's own catalog queries, runs inside
BEGIN TRANSACTION READ ONLYand is always rolled back. This is the real guarantee: Postgres itself rejectsINSERT/UPDATE/DELETE/DDL,SELECT ... FOR UPDATE,SELECT ... INTO, sequence changes, and aDELETEhidden inside a CTE.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.Text filter before the database. Input that is not a single
SELECT(orWITH ... 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.Statement timeout.
statement_timeoutis set for the transaction only, so a slow query is cancelled by Postgres and the pooled connection is left as it was.Schema allowlist.
MCP_PG_SCHEMAS(defaultpublic) limits what the tools can see.list_tables,describe_tableandsample_rowsrefuse 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_pathis set to the allowlist.Safe identifiers.
sample_rowslooks 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.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": trueand"truncated_by": "rows" | "bytes".The connection string stays private. It is read from
DATABASE_URLonly, 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 installTo 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.sqlThe 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.tsThen 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 |
| required |
|
|
| Comma-separated schema allowlist. The first one is the default for |
|
| Per-statement timeout, in milliseconds. |
|
| 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:downTo 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…
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Related MCP Servers
- FlicenseAqualityDmaintenanceEnables AI agents to inspect and query PostgreSQL databases safely, with features like listing tables, retrieving schemas, and running read-only SQL queries.3-
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to query a PostgreSQL database through a small set of controlled, read-only tools for schema inspection, row lookup, and aggregate statistics.1MIT
- FlicenseNot gradedqualityDmaintenanceEnables LLM agents to explore and query a Postgres database through secure, read-only tools.-
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to securely discover database schemas and execute read-only SQL queries through guardrailed tools that block mutations and clamp result sizes.1MIT