Let Claude Code, Codex or any MCP client explore a PostgreSQL database, run SQL, read query plans, test hypothetical indexes, find the slowest queries and check the database's health, without flooding the model's context or escaping read-only mode.
A Model Context Protocol server that gives an AI client compact, bounded access to one PostgreSQL database. It is a drop-in replacement for crystaldba/postgres-mcp 0.3.0, with crystaldba's nine tools and parameters unchanged, plus a tenth, analyze_locks; switching is one line of client configuration, and MIGRATION.md lists what changes.
Why a bounded, read-only Postgres MCP server
- Bounded, announced results. Compact CSV with an explicit footer. Every result is capped in rows, bytes and cell length, and every cut is announced.
- A restricted mode, on by default. Each statement is parsed with PostgreSQL's own parser (libpg_query), every function it names is checked wherever it stands, and it runs inside a read-only transaction.
- One static Go binary that starts in milliseconds.
Measured against crystaldba/postgres-mcp 0.3.0
On a PostgreSQL 17 database, as a read-only role, on 2026-11-01:
- 131 of 131 attack statements refused in restricted mode;
- 9 MB of memory in a Linux container.
Method, every number including where postgres-dba-mcp does worse, and the comparison with crystaldba/postgres-mcp 0.3.0: BENCHMARK.md. To run the harness: bench/README.md.
What the model receives
SELECT * FROM types:
id,txt,empty,num,arr,iv,ts,bin
1,hello,"",532.10,"{1,2}",1 day 02:00:00,2026-03-02 10:14:00+00,\xdeadbeef
2,\N,\N,\N,\N,\N,\N,\N
-- 2 rows, 2 ms
Values keep their PostgreSQL text form, NULL (\N) stays distinct from an empty string, and the footer says how many rows came back and whether anything was cut. The 0.3.0 server returned the same rows as Python repr, with no size limit (MIGRATION.md has the details).
Install
With npm (Node.js 18 or later; macOS, Linux and Windows on amd64, macOS and Linux also on arm64), there is nothing to install: npx downloads the binary of your platform and runs it.
npx -y postgres-dba-mcp --version
In the quick starts below, use npx -y postgres-dba-mcp wherever the command is postgres-dba-mcp.
With Homebrew (macOS and Linux):
brew install a-lafon/tap/postgres-dba-mcp
With the install script (macOS and Linux, amd64 and arm64): it downloads the release archive, checks it against checksums.txt and puts the binary in ~/.local/bin (POSTGRES_DBA_MCP_INSTALL_DIR to change it, POSTGRES_DBA_MCP_VERSION=v0.1.0 for a given release):
curl -fsSL https://raw.githubusercontent.com/a-lafon/postgres-dba-mcp/main/install.sh | sh
With Docker (linux/amd64 and linux/arm64, non-root, no shell):
docker run -i --rm -e DATABASE_URI ghcr.io/a-lafon/postgres-dba-mcp:latest
localhost in the URI then means the container itself: on Docker Desktop use host.docker.internal, on Linux --network=host (see below).
From a release archive, Windows included: download the archive for your system from the releases page (darwin, linux and windows on amd64; darwin and linux also on arm64), check it against checksums.txt (SHA-256), and put the postgres-dba-mcp binary on your PATH.
With the Go toolchain (Go 1.26 or later): go install github.com/a-lafon/postgres-dba-mcp/cmd/postgres-dba-mcp@latest.
The Linux binaries and the image parse SQL with the native PostgreSQL parser (about 20 MB at start). The macOS and Windows binaries, and a plain go install, use a WASM copy of it, which peaks near 300 MB of memory at start and hands it back afterwards. With a C compiler, CGO_ENABLED=1 go install -tags pgquery_cgo,netgo,osusergo github.com/a-lafon/postgres-dba-mcp/cmd/postgres-dba-mcp@latest builds the native one.
Check the install with postgres-dba-mcp --version. When the shell does not find it, ~/.local/bin is not on your PATH: add it, or register the server with the full path.
Quick start with Claude Code
Register the server with the database URI in its environment:
claude mcp add pg --env DATABASE_URI=postgres://pgdba_ro:secret@localhost:5432/pgdba -- postgres-dba-mcp
Without an install, through npm:
claude mcp add pg --env DATABASE_URI=postgres://pgdba_ro:secret@localhost:5432/pgdba -- npx -y postgres-dba-mcp
Or put it in .mcp.json:
{
"mcpServers": {
"pg": {
"command": "postgres-dba-mcp",
"env": { "DATABASE_URI": "${DATABASE_URI}" }
}
}
}
The URI can also be the first argument (postgres-dba-mcp postgres://...). When both are given, DATABASE_URI wins. The server starts without connecting: the first tool call opens the connection.
Connection options in the URI (sslmode, sslrootcert, connect_timeout, …) are honoured, and so is search_path, which is applied to every transaction rather than sent at connection time, because a transaction pooler refuses it there. A server setting such as timezone is reported as ignored for the same reason. A misspelled TLS option is refused at startup instead: left alone it would read as a server setting, and the connection would fall back to an unchecked certificate.
Through Docker, localhost inside the container is the container itself, and the image does not rewrite it. On Docker Desktop use host.docker.internal in the URI; on Linux use --network=host or the address of the host on the bridge network.
{
"mcpServers": {
"pg": {
"command": "docker",
"args": ["run", "-i", "--rm", "-e", "DATABASE_URI", "ghcr.io/a-lafon/postgres-dba-mcp:latest"],
"env": { "DATABASE_URI": "postgres://pgdba_ro:secret@host.docker.internal:5432/pgdba" }
}
}
}
Quick start with Codex
Register the server with the database URI in its environment:
codex mcp add pg --env DATABASE_URI=postgres://pgdba_ro:secret@localhost:5432/pgdba -- postgres-dba-mcp
Or put it in ~/.codex/config.toml:
[mcp_servers.pg]
command = "postgres-dba-mcp"
env = { DATABASE_URI = "postgres://pgdba_ro:secret@localhost:5432/pgdba" }
Codex stops waiting for a tool after tool_timeout_sec (60 s by default). If you raise --statement-timeout above that, raise tool_timeout_sec in the same entry too.
Several databases
One process serves one database. To use several, add one server entry per database. Each entry gets its own tools, so you can write permission rules per server. Use a read-only role everywhere, and --access-mode=unrestricted only where writes are intended.
{
"mcpServers": {
"pg-prod": {
"command": "postgres-dba-mcp",
"env": { "DATABASE_URI": "${PROD_DATABASE_URI}" }
},
"pg-staging": {
"command": "postgres-dba-mcp",
"args": ["--access-mode=unrestricted"],
"env": { "DATABASE_URI": "${STAGING_DATABASE_URI}" }
}
}
}
In Claude Code, permission rules name the server, so the two entries above can be treated differently. For example, in .claude/settings.json, allow every tool of pg-prod and ask before each execute_sql on pg-staging:
{
"permissions": {
"allow": ["mcp__pg-prod"],
"ask": ["mcp__pg-staging__execute_sql"]
}
}
Credentials outside the URI
You do not have to put the password in the URI or in .mcp.json. The driver (pgx) reads the standard libpq sources itself; this server adds no option for them.
A URI without a password, with the password read from ~/.pgpass (or the file named by PGPASSFILE) or from PGPASSWORD:
DATABASE_URI=postgres://pgdba_ro@db.example.com:5432/pgdba
A ~/.pgpass line has the form host:port:database:user:password, and the file must not be readable by others (chmod 600). PGPASSWORD=... postgres-dba-mcp works the same way.
A named service from pg_service.conf (or the file named by PGSERVICEFILE):
DATABASE_URI="service=prod"
[prod]
host=db.example.com
port=5432
dbname=pgdba
user=pgdba_ro
sslmode=verify-full
The password never appears in the server's log: the startup line shows user@host:port/db only.
Read-only role
In restricted mode the server refuses writes, but the Postgres role is the real barrier. Give the server a role that can only read:
CREATE ROLE pgdba_ro LOGIN PASSWORD 'change-me';
GRANT pg_read_all_stats TO pgdba_ro; -- pg_stat_statements text and other sessions' statistics
GRANT USAGE ON SCHEMA public TO pgdba_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO pgdba_ro;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO pgdba_ro; -- tables created later
Without pg_read_all_stats, analyze_locks still reports the pids, the locks and the chains, but the waits, states, transaction ages and query texts of other roles' sessions come back as \N and it says so in a -- session details hidden: grant pg_read_all_stats to <role> … line. From PostgreSQL 15 on, a NOINHERIT member of pg_read_all_stats reads nothing either, and is reported the same way; PostgreSQL 14 grants it on membership alone. Either way the line appears only when the report really hides something.
Repeat the USAGE, SELECT and ALTER DEFAULT PRIVILEGES lines for every other schema the agent should see. After the first connection the server warns on stderr when the role is a superuser, bypasses row-level security, owns tables, or belongs to a powerful built-in role (pg_read_server_files, pg_write_server_files, pg_execute_server_program, pg_signal_backend, rds_superuser, azure_pg_admin). It also warns when PostgreSQL is newer than 18, the newest version whose built-in functions the restricted-mode denylist was checked against.
Sensitive columns
Restricted mode prevents writes, not reads: any column the role can read can end up in the model's context. If some columns must stay out of reach, the role is the barrier. Create a dedicated role and grant it only what it may see, instead of SELECT ON ALL TABLES.
With column-level grants (SELECT * is then refused by Postgres with SQLSTATE 42501, and the agent must name the columns it may read):
CREATE ROLE pgdba_agent LOGIN PASSWORD 'change-me';
GRANT pg_read_all_stats TO pgdba_agent;
GRANT USAGE ON SCHEMA public TO pgdba_agent;
GRANT SELECT (id, name, created_at) ON public.accounts TO pgdba_agent; -- not the email column
Or through a view without the sensitive columns:
CREATE VIEW public.accounts_safe AS SELECT id, name, created_at FROM public.accounts;
GRANT SELECT ON public.accounts_safe TO pgdba_agent;
Keep in mind that pg_read_all_stats shows the text of statements run by other users in pg_stat_statements, which can contain literal values.
Flags
Flags can come before or after the database URI, as --name=value or --name value.
| Flag |
Default |
Meaning |
--access-mode |
restricted |
restricted (read-only, with the SQL checks) or unrestricted (execute_sql can modify the database) |
--transport |
stdio |
stdio, streamable-http, or sse (deprecated) |
--tools |
all |
Comma list of tool groups: schema, query, explain, stats, health, index, locks, or all |
--max-rows |
100 |
Default row limit of a result (at least 1, at most --max-rows-limit) |
--max-rows-limit |
1000 |
Highest max_rows a client may ask for |
--max-bytes |
32768 |
Size cap of one tool result in bytes (at least 1024) |
--max-cell |
200 |
Default longest cell in characters before it is shortened (at least 16, at most --max-cell-limit) |
--max-cell-limit |
10000 |
Highest max_cell a client may ask for |
--statement-timeout |
30s |
Server-side timeout of every statement (a Go duration, above 0) |
--allow-function |
none |
Function name or pattern to allow in restricted mode; repeatable, schema.name and * wildcards accepted |
--deny-function |
none |
Function name or pattern to refuse in restricted mode; repeatable, same syntax |
--host |
127.0.0.1 |
HTTP transports: address to bind |
--port |
8000 |
HTTP transports: port to listen on |
--allow-remote |
false |
HTTP transports: allow binding a non-loopback address |
--allowed-hosts |
none |
HTTP transports: extra Host values to accept (host or host:port, comma list) |
--allowed-origins |
none |
HTTP transports: extra Origin values to accept (scheme://host[:port], comma list) |
--sse-host |
none |
Alias of --host (crystaldba compatibility) |
--sse-port |
none |
Alias of --port (crystaldba compatibility) |
--version |
|
Print postgres-dba-mcp <version> and exit |
Environment: DATABASE_URI (the connection string), plus the libpq variables the driver reads (PGPASSWORD, PGPASSFILE, PGSERVICEFILE, PGSSLMODE, and so on).
Tools
Tools belong to a group, which --tools can switch off.