@yawlabs/postgres-mcp
Summary: Query, inspect, and diagnose a PostgreSQL database through an MCP client, with read-only access by default and writes only when explicitly enabled and permitted by the database role.
Run SQL with
pg_readonlyfor unconditional read-only queries, orpg_queryfor read-only-by-default queries and opt-in writes viaALLOW_WRITES=1plus role privileges; both support parameterized$1queries.Browse schemas, tables, views, functions, extensions, and columns, and get detailed table metadata including columns, primary keys, foreign keys, constraints, indexes, and partitions.
Explain queries with
pg_explain, including optionalANALYZE, text/JSON plans, planner options, and HypoPG hypothetical indexes.Recommend indexes with
pg_index_advisor, costed against a workload using HypoPG without creating real indexes.Diagnose performance and health with top queries, sequential-scan tables, unused indexes, I/O stats, table bloat, locks, replication status, and rolled-up DBA lints.
Inspect roles and table privileges, and cancel or terminate backends with
pg_killwhen writes are enabled and the role has permission.Use safety features such as result truncation, statement/connection timeouts, result-size limits, startup privilege warnings, optional audit logging, sandbox/runtime controls, and managed-Postgres TLS options.
Provides tools for querying PostgreSQL databases, including SQL execution with read-only safety, schema introspection (tables, columns, keys, indexes), performance diagnostics (EXPLAIN, pg_stat_statements, bloat, locks), health checks, and role/privilege awareness.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@@yawlabs/postgres-mcp List all tables in the public schema"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
@yawlabs/postgres-mcp
One click adds this to your local Yaw MCP config so it's available in every Yaw Terminal session. Tested with Yaw MCP 1.1.16 or newer. Or install manually below.
Query a PostgreSQL database from Claude Code, Cursor, and any MCP client. SQL runs in read-only transactions by default, and writes opt in via a single env var. Connect with a least-privilege role: the role, not this server, is the security boundary.
Built and maintained by Yaw Labs.
What's new in 0.12
An index advisor, opt-in audit logging, structured tool output, and support for current-revision MCP clients. Full detail in the CHANGELOG.
pg_index_advisorrecommends indexes for a workload and keeps only the ones that measurably lower estimated cost. Candidates are costed with HypoPG hypothetical indexes, never created on disk, and the search knows that PostgreSQL 18's skip scan changes which multi-column indexes are useful.Opt-in audit logging of the SQL tools send: one JSON line per audited statement, to stderr or a file. Bound parameter values are never recorded. Off by default, and not a complete record -- see Audit logging.
Structured tool output. Every tool declares an
outputSchemaand returnsstructuredContentalongside the unchanged text block, so anything reading the text today keeps working.Both MCP protocol eras. The server used to speak only the legacy (2025) protocol revisions, which a client on the current 2026-07-28 revision fails against. It now serves both.
On 0.12.0? Upgrade. 0.12.1 closes a stacked-query hole in pg_index_advisor: SQL passed in its statements argument ran on a protocol that accepts several commands in one string, so SELECT 1; COMMIT; DROP SCHEMA public CASCADE; escaped the read-only transaction. The tool is annotated read-only, so hosts often auto-allow it. The same release stops pg_inspect_locks attributing a lock held in another database to whichever local table shares its OID, fixes the advisor's greedy search, and makes audit lines carry the tool field they were missing.
Coming from 0.10.x? 0.11.0 has three breaking changes: pg_seq_scan_tables, pg_unused_indexes and pg_top_queries return an envelope (read data.rows where you used to read data), pg_explain with analyze: true emits BUFFERS (pass buffers: false for the old output), and Node 22 is the floor. Details in the 0.11.0 changelog entry.
Related MCP server: pg-mcp
Backstory
Anthropic's reference Postgres MCP server, @modelcontextprotocol/server-postgres, was archived in May 2025 and marked deprecated on npm in July 2025. Anthropic has not shipped a replacement. Despite the deprecation, the last published version (v0.6.2) is still pulled ~20,000 times per week - a lot of agents are pointed at an unmaintained package.
That unmaintained package also has a known, publicly documented stacked-query SQL injection (Datadog Security Labs) that bypasses its BEGIN READ ONLY wrapper with input like COMMIT; DROP SCHEMA public CASCADE;. It has never been patched at npm.
A handful of community forks have appeared, but each fills a narrow slice:
@zeddotdev/postgres-context-server- Zed's fork, primarily a security patch on the original shape.Postgres MCP Pro (Crystal DBA) - focused on index tuning and hypothetical-index / buffer-cache diagnostics.
AWS Labs Postgres MCP - tied to Aurora / RDS Data API + Secrets Manager.
None of them position themselves as a general-purpose daily driver you'd hand to Claude Code or Cursor against an arbitrary Postgres: modern introspection, perf helpers, role/privilege awareness, and a write-safety posture out of the box. That's the gap @yawlabs/postgres-mcp fills.
Why this one?
Read-only transactions by default, with an unconditional read-only tool too -
pg_queryruns user SQL in aBEGIN READ ONLYtransaction, so postgres itself blocks ordinary writes; opt in to writes withALLOW_WRITES=1.pg_readonlystays in that transaction regardless ofALLOW_WRITES. Read-only paths also refuse statements that step around the transaction. None of this contains a privileged role, so hosts that gate tools individually should auto-allowpg_readonlyonly with a least-privilege role (details).Role-based access as the primary control - the recommended posture is to use a least-privileged postgres role in
DATABASE_URL(e.g. one withGRANT pg_read_all_data); postgres itself then enforces the boundary, no env var needed. See Configuring access.Extended query protocol for all user SQL -
pg_querysends user input withqueryMode: 'extended', which restricts each request to a single statement. This closes the stacked-query injection class (COMMIT; DROP SCHEMA x CASCADE;) that defeated the reference server'sBEGIN READ ONLYwrapper. Integration test asserts the rejection.Parameterized queries -
pg_querytakes aparamsarray for$1,$2, etc. No string-interpolated SQL in our code path.Written from scratch, actively maintained - not a fork of the deprecated code. Unit + integration tests (
npm test,npm run test:integration) run against a real Postgres; releases cut viarelease.sh.Schema introspection built in -
pg_list_schemas,pg_list_tables,pg_describe_tablereturn columns, primary keys, foreign keys, and indexes without the agent having to rememberpg_catalogjoins.EXPLAINas a first-class tool - text or JSON format, with optionalANALYZE. ANALYZE for non-SELECT statements requiresALLOW_WRITES=1and always rolls back, so the plan is real but the written rows don't persist. (What Postgres never rolls back still sticks: a sequence the statement advanced stays advanced.)Perf diagnostics the deprecated server never had -
pg_top_queries(frompg_stat_statements),pg_seq_scan_tables,pg_unused_indexes,pg_table_bloat,pg_inspect_locks,pg_replication_status. Answer "why is this slow?" in one tool call.Health snapshot -
pg_healthreturns version, db size, connection counts, and the 10 longest-running active queries in one call.Role and privilege awareness -
pg_list_rolesandpg_table_privilegesfor the common "who can touch what?" questions.Instant startup - ships as a single bundled file with zero runtime dependencies. No multi-minute
node_modulesinstall on everynpxcold start.Result truncation - large result sets are capped at
POSTGRES_MAX_ROWS(default 1000) with atruncated: trueflag, so a straySELECT * FROM eventsdoesn't blow out the model context.
Quick start
1. Create .mcp.json in your project root
macOS / Linux / WSL:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@yawlabs/postgres-mcp@latest"],
"env": {
"DATABASE_URL": "postgres://user:password@host:5432/dbname"
}
}
}
}Windows:
{
"mcpServers": {
"postgres": {
"command": "cmd",
"args": ["/c", "npx", "-y", "@yawlabs/postgres-mcp@latest"],
"env": {
"DATABASE_URL": "postgres://user:password@host:5432/dbname"
}
}
}
}Why the extra step on Windows? Since Node 20,
child_process.spawncannot directly execute.cmdfiles (that's whatnpxis on Windows). Wrapping withcmd /cis the standard workaround.
2. Restart and approve
Restart Claude Code (or your MCP client) and approve the postgres MCP server when prompted.
3. (Optional) Enable writes
Read-only is the default. If you want the agent to be able to INSERT, UPDATE, DELETE, or run DDL, add ALLOW_WRITES=1 to the env block:
"env": {
"DATABASE_URL": "postgres://...",
"ALLOW_WRITES": "1"
}Prefer scoping this to dev/test databases - for production, leave writes off and use migration tools out-of-band.
Configuring access
The role in DATABASE_URL is the primary access control. Postgres has had a battle-tested permission system for 30 years; lean on it instead of relying on ALLOW_WRITES alone. A least-privileged role makes writes server-rejected no matter what tools or env vars are configured.
Read-only agent (recommended default):
CREATE ROLE mcp_reader LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE your_db TO mcp_reader;
GRANT USAGE ON SCHEMA public TO mcp_reader;
GRANT pg_read_all_data TO mcp_reader;Point DATABASE_URL at mcp_reader. Postgres then rejects writes, DDL and privilege changes regardless of ALLOW_WRITES. pg_read_all_data reads every table, so grant SELECT on specific tables instead if some hold data the agent should not see.
Then check what else the role can reach. The server does this at startup and prints a WARNING on stderr for each problem it finds: superuser, CREATEROLE/CREATEDB/REPLICATION/BYPASSRLS, membership of pg_execute_server_program, pg_read_server_files, pg_write_server_files, pg_write_all_data or pg_signal_backend, roles it can SET ROLE to, table write privileges, and EXECUTE on dblink_connect_u or server-file functions (plain dblink functions are not named: postgres grants them to PUBLIC by default, so every role would trip that warning; the statement checks refuse the calls anyway). It warns and keeps running, so local development against a superuser still works. Clear the warnings with:
ALTER ROLE mcp_reader NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;
ALTER ROLE mcp_reader SET default_transaction_read_only = on;
ALTER ROLE mcp_reader SET statement_timeout = '30s';
-- Remove anything the check named, for example:
REVOKE some_owner_role FROM mcp_reader;
REVOKE EXECUTE ON FUNCTION dblink_connect_u(text) FROM PUBLIC; -- if dblink is installed and its warning firedWhat this server cannot enforce. Its checks are guard rails for a well-meaning agent, not a sandbox:
The statement checks read the SQL text. A function that wraps a blocked call, or a
SECURITY DEFINERfunction, gets past them, and a function that opens its own connection is outside the transaction altogether.An agent that also has a shell, or can read the MCP config, can take the credential and connect directly. Then no control in this server applies, and only the role's privileges limit it.
Scoped write agent (dev/test or narrow production use):
CREATE ROLE mcp_writer LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE your_db TO mcp_writer;
GRANT USAGE ON SCHEMA public TO mcp_writer;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO mcp_writer;
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO mcp_writer;
-- DDL not granted -- the agent can change data but not schema.Set ALLOW_WRITES=1 so pg_query will issue writes, and rely on the role to keep the agent away from DDL and other schemas.
Per-tool gating in the host:
Tools split across two classes. Treat the first list as auto-allowable only once DATABASE_URL is a least-privilege role with no warnings from the startup check. Under a superuser or an over-granted role, prompt for these too, pg_readonly above all.
Auto-allow:
pg_readonly(BEGIN READ ONLYplus best-effort statement checks; its safety comes from the role),pg_index_advisor(only ever EXPLAINs the statements it is given, never with ANALYZE, insideBEGIN READ ONLY), plus the introspection and diagnostics tools (pg_list_*,pg_describe_table,pg_search_columns,pg_health,pg_inspect_locks,pg_table_bloat,pg_unused_indexes,pg_seq_scan_tables,pg_top_queries,pg_io_stats,pg_replication_status,pg_advisor,pg_table_privileges).Always prompt:
pg_query(writes whenALLOW_WRITES=1is set and the role allows it),pg_explain(analyze: trueexecutes the statement; withALLOW_WRITES=1that includes writes, which are rolled back, and without it the tool has the same reach aspg_readonly),pg_kill(changes session state; requiresALLOW_WRITES=1).
The split follows each tool's readOnlyHint annotation, and Claude Code's permissions block and mcp.hosting's per-tool toggle both honor it. The hint describes what a tool is meant to do; it cannot promise what the connected role is able to do.
What
READ ONLYdoes and does not cover. ABEGIN READ ONLYtransaction blocks writes through this session -- INSERT/UPDATE/DELETE, DDL,nextval/setval. It does not stop effects outside it. On read-only paths the server therefore refusesSET,RESET,DO,CALL,PREPARE,EXECUTE,DEALLOCATE,LOAD,DISCARD,COPY,LOCK,VACUUM,ANALYZE,CLUSTER,REINDEX,CHECKPOINT,LISTEN,UNLISTEN,NOTIFY, cursor commands and transaction control by leading keyword, plus direct calls todblink*,set_config,pg_terminate_backend,pg_cancel_backend,pg_read_fileand similar server-file functions,lo_import/lo_export,query_to_xmlandts_stat/ts_rewrite. Those checks are cheap and bypassable (what they cannot do), and withALLOW_WRITES=1pg_queryskips them. The role is the control that bounds this tool.
ALLOW_WRITES as defense-in-depth:
ALLOW_WRITES is a secondary belt-and-braces gate. Useful when:
You're on a managed database where creating a second role is awkward (some Supabase/Neon plans).
You want a single role that can write, but want the MCP server to refuse writes anyway during normal operation.
Otherwise, configure the role and stop relying on ALLOW_WRITES.
What can an agent do with this?
Once connected, the agent picks tools automatically based on what you ask. A few single-tool examples:
"Describe the users table" ->
pg_describe_table-> returns kind, columns, PK, FKs, indexes."Which tables have a
user_idcolumn?" ->pg_search_columnswith patternuser_id-> one call instead of iterating every table."This query is slow, why?" ->
pg_explainwithanalyze: true-> returns the plan with actual row counts and timing."What's the slowest query we run?" ->
pg_top_queries-> returns the top N frompg_stat_statementswith mean/total/min/max times."Do we have any unused indexes?" ->
pg_unused_indexes-> returns non-unique, non-primary indexes with zero or low scan counts + their size."Is
pgvectorinstalled?" ->pg_list_extensions-> yes/no with version.
The bigger leverage is multi-tool reasoning. A few real workflows:
Unstick a hung app.
pg_inspect_locksreturns blocked PID + blocking PID + the offending query, thenpg_kill(ALLOW_WRITES=1required) cancels the blocker. The agent can run both in one turn - it's the fastest path from "the app is frozen" to "back up."Chase a slow page.
pg_top_queriesranks the worst queries,pg_explainwithanalyze: trueshows the plan for the top hit,pg_seq_scan_tablesandpg_unused_indexessay whether the answer is "add an index here" or "drop a dead one there."Oncall triage.
pg_healthchecks connectivity + active-query count + database size;pg_inspect_locksandpg_replication_statusconfirm whether contention or replication lag is in play before paging the on-call DBA.
Tools
Tool | Description |
| Run one SQL statement inside |
| Run a SQL query. Writes gated by the role in |
| List non-system schemas. |
| List tables (and optionally views) in a schema with estimated row counts. Paginated via |
| Kind, columns, PK, outgoing FKs, incoming FKs ( |
| List views and materialized views in a schema, including their SQL definitions. |
| List functions, procedures, and aggregates in a schema with signatures and return types. |
| List installed extensions (pgvector, postgis, pg_stat_statements, etc.) with versions. |
| Find columns by name pattern across all user schemas. Case-insensitive, supports SQL LIKE wildcards. |
|
|
| Recommend indexes for a workload and prove each one pays for itself first. Takes |
| Server version, database size, connections against |
| Top N queries by total/mean execution time. Requires the |
| Tables with heavy sequential scans - missing-index candidates. Returns the |
| Non-unique, non-primary indexes with low scan counts - drop candidates. Also returns |
| I/O observability: |
| Who is blocking whom right now (blocked PID, blocker PID, lock type, queries). |
| Database roles with login/superuser/createdb flags and group memberships. |
| Who has SELECT/INSERT/UPDATE/DELETE/etc. on a table or whole schema. |
| Tables with high dead-tuple ratios - VACUUM candidates. |
| Replication slots, connected replicas, and current WAL position. |
| Rolled-up DBA lints in one call: sequence-exhaustion candidates, wraparound risk for both counters (per-database and per-table |
| Cancel a running query or terminate a backend connection. Requires |
Configuration
All env vars are read from the MCP server's environment:
Variable | Default | Purpose |
| (required) | PostgreSQL connection string. |
| unset | Secondary write gate for |
|
| Per-statement timeout. |
|
| TCP connect timeout. Without this, a dead host hangs until the OS gives up (~2 minutes). |
|
| Cap on rows returned by |
|
| Most bytes one statement's result may send to this process. Over it the call fails (it is not truncated), the transaction rolls back and the connection closes. Counted on the socket, so it also bounds |
| statement timeout + | Client-side limit on one SQL call. Backstop for a statement that outlives |
|
| Max pool connections. Set to |
| unset | Set to |
|
| Value reported in |
| unset (off) |
|
| unset | Append the audit lines to this file instead of stderr. Setting it alone turns auditing on. The server refuses to start if the value is empty, if the file cannot be opened, or if |
| unset (off) |
|
|
| Which JS runtime executes the server: |
| unset | Path to an |
| unset (off) |
|
Supported Postgres versions
Tested on PostgreSQL 15, 17 and 18 in the integration matrix.
Works on PG13+, but note where upstream support actually sits: PG13 reached end of life on 2025-11-13 and PG14 does so on 2026-11-12. PG13/14 are not exercised here and are not a compatibility target going forward. PG12 and below are further out of support and some tools rely on columns that landed in PG13 (pg_replication_status reading wal_status, pg_top_queries reading *_exec_time).
Newer server versions unlock extra fields rather than being required. Every version-dependent column is gated on server_version_num and simply omitted on servers that predate it, so nothing errors -- you get a slightly thinner answer. The cut points that matter:
Server | What it adds |
PG16+ |
|
PG17+ |
|
PG18+ | Generated-column form ( |
If the version probe fails, the server assumes the oldest supported shape rather than emitting SQL a server might reject.
Runtime
The published postgres-mcp command is a small launcher that prefers the newest oam runtime it can find and falls back to Node.
If you do not have oam, nothing changes -- unless POSTGRES_MCP_SANDBOX is on, which needs oam and stops the launcher with a message when there is none. The fallback is not a re-exec: npm already started Node to run the launcher, so falling back is a plain import() of the server into that same process. It costs a few existsSync calls and no subprocess, and behaves identically to running dist/index.js under Node directly.
Which oam. Only oam 0.21.1 or newer -- the latest release -- is used. The launcher looks in the installed locations ($OAM_INSTALL_DIR when it is set, then %LOCALAPPDATA%\oam\bin and ~/.oam/bin on Windows, ~/.oam/bin elsewhere) and on PATH, asks every oam it finds for its version, and runs the newest; on a tie the installed copy wins. An older oam is passed over. On Windows only oam.exe counts; an oam.cmd / oam.bat shim is never run. The passed-over binaries and any shim are named on stderr only when no usable oam is found -- when a newer oam runs, nothing is printed about them. The fix printed then fits what was found: oam self-update for an oam that is too old, a check of the binary for one that would not run, and an install from oamjs.org only when there was no oam at all. An OAM_BIN that cannot be used is always named whenever the launcher looks for an oam, even when a newer one then runs. When a host launches the command with oam run on oam 0.21.1 or newer, the server runs inside that oam with no second one -- except when POSTGRES_MCP_SANDBOX is on, which needs a freshly launched oam and exits with an error when none can be launched. A host oam older than 0.21.1 never serves the server itself: it hands off to the newest usable oam, else (without the sandbox) to Node on PATH, else exits with an error.
If you do have a usable oam, the server runs under it. Verified equivalent on both runtimes: all 23 tools register, queries return identical rows and dataTypeName values, and the error paths match. oam supplies every node: builtin the driver needs, including net, tls, crypto, and dns (SCRAM auth and the extended query protocol both work).
Startup cost, measured. windows-arm64, 1.4 MB bundle, postgres-mcp version (full module init), every binary warmed first, mean of 12 runs:
path | startup |
standalone binary ( | 298ms |
| 306ms |
| 358ms |
launcher -> Node (in-process) | 370ms |
launcher -> oam (spawn) | 409ms |
oam starts faster than Node here. What the launcher costs is the spawn: reaching oam means Node has already booted, and that hop (~100ms) is larger than oam's ~52ms advantage. So through the npm bin, the two land within ~40ms of each other, and POSTGRES_MCP_RUNTIME=node is a marginal win rather than a meaningful one. Those figures were taken with one oam on the machine: the launcher now runs --version on every oam binary it finds, so each extra copy adds a probe.
Either way it is a one-time cost per MCP session, not per tool call -- hosts spawn the server once and hold it open. If startup genuinely matters, the standalone binary avoids the launcher entirely and is the fastest option.
Earlier releases of this README reported ~650-900ms for Node and ~980-1290ms for oam, and advised opting out of oam on that basis. Those figures were measured against cold, freshly-built binaries and reflected the Windows on-access virus scanner rather than either runtime. They were wrong in both magnitude and direction. Corrected in 0.9.1.
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@yawlabs/postgres-mcp"],
"env": {
"DATABASE_URL": "postgres://...",
"POSTGRES_MCP_RUNTIME": "node" // opt out of oam
}
}
}
}Connecting to managed Postgres (Supabase, Neon, RDS, etc.)
Most managed databases require TLS but serve certs signed by a private CA that Node's default trust store doesn't recognize. The symptom is one of:
self signed certificate in certificate chainunable to get local issuer certificateunable to verify the first certificate
To allow the connection while keeping traffic encrypted, add POSTGRES_SSL_REJECT_UNAUTHORIZED=false to the env block:
"env": {
"DATABASE_URL": "postgres://user:pass@host:5432/db?sslmode=require",
"POSTGRES_SSL_REJECT_UNAUTHORIZED": "false"
}This disables certificate chain verification only -- the TCP connection is still TLS-encrypted end-to-end. For production setups where you can install the CA, prefer putting the cert in the Node trust store (NODE_EXTRA_CA_CERTS) over disabling verification globally.
Shaving a round trip on PG17+. Postgres 17 added direct TLS negotiation, which skips the plaintext SSLRequest handshake before the TLS one. The bundled driver supports it, so append sslnegotiation=direct to your DATABASE_URL:
postgres://user:pass@host:5432/db?sslmode=require&sslnegotiation=directIt is opt-in rather than a default because a PG16-or-older server will reject the connection outright, and the saving is one round trip per pooled connection -- worth it on a distant managed database, invisible on a local one.
Audit logging
Off by default. Turn it on in the env block with POSTGRES_AUDIT_LOG=stderr, or with POSTGRES_AUDIT_LOG_FILE alone:
"env": {
"DATABASE_URL": "postgres://...",
"POSTGRES_AUDIT_LOG_FILE": "/var/log/postgres-mcp/audit.jsonl"
}The server then writes one JSON line per audited statement. Two captured from PostgreSQL 17 -- a parameterized query, then a failing one:
{"ts":"2026-09-12T19:26:42.587Z","tool":"pg_query","source":"user","sql":"SELECT $1::int AS n","params":1,"ms":2.827,"rows":1,"ok":true}
{"ts":"2026-09-12T19:26:42.591Z","tool":"pg_readonly","source":"user","sql":"SELECT * FROM does_not_exist_xyz","params":0,"ms":2.217,"rows":null,"ok":false,"sqlstate":"42P01"}Field | Meaning |
| ISO 8601 time the line was written, just after the statement finished. |
| The MCP tool that issued the statement. Absent only when the server's query functions are called outside a tool handler, e.g. when embedding it in-process. |
|
|
| The statement text as sent. For |
| Replace |
| How many bound parameters were passed. The count, never the values. |
| Wall-clock milliseconds for the audited step, not server execution time. A |
|
|
| Whether the statement ran and succeeded. |
| Only when |
Never logged, in any mode: bound parameter values (only their count) and error messages (only the code), since postgres quotes offending values back in its messages. Statement text is logged as written, so pass sensitive literals as params to pg_query, pg_readonly or pg_explain. pg_index_advisor takes no params; write $1-style placeholders in its statements instead (planned with GENERIC_PLAN, PostgreSQL 16+).
Values are parsed strictly. A value outside the accepted sets in the Configuration table -- yes, on, hash -- stops the server at startup instead of reading as off, even for POSTGRES_AUDIT_REDACT with auditing off. An audit control that quietly disabled itself would be worse than none. Case and surrounding whitespace are ignored. A variable that is set but empty, or only whitespace, stops the server too: that is usually an env entry such as "POSTGRES_AUDIT_REDACT": "${AUDIT_REDACT}" whose variable is unset where your MCP client runs (on Windows, variables from a bash or WSL profile do not reach a server launched via cmd), and reading it as unset would log full SQL. Only a variable that is not set at all counts as unset, so to leave either flag off, remove it from the env block or set it to 0.
The file sink. POSTGRES_AUDIT_LOG_FILE alone turns auditing on, and it wins over POSTGRES_AUDIT_LOG=stderr without a warning when both are set. As with the other two variables, an empty or whitespace-only value is an error, not unset. The path must name a file in an existing directory: the file is created if missing, opened for append at startup, and held open for the life of the process. Use an absolute path; a relative one resolves against whatever directory your MCP client launches the server from. A write that fails later (full disk) never fails the query: one warning goes to stderr and later lines keep trying.
On stderr, audit lines are mixed with the startup banner and warnings, so skip lines that are not JSON; the file sink holds only audit lines. stdout is never used -- it is the MCP protocol channel.
Redaction hides text, not guesses. Identical statements hash identically, so you can still count and correlate them -- and for the same reason, anyone holding the log can confirm a guessed statement, so a short literal inside a predictable query is recoverable. Bound parameters are the safe place for sensitive values.
Under POSTGRES_MCP_SANDBOX the sandbox denies the filesystem, so the file sink cannot open and the server exits at startup (could not be opened for append: Access to this API has been restricted). Use POSTGRES_AUDIT_LOG=stderr there; all three audit variables pass through the sandbox.
What the trail does not show.
Which backend
pg_killsignalled. Each signal writes one line --tool: "pg_kill",source: "internal",params: 1, andsqleitherSELECT pg_cancel_backend($1) AS signaledorSELECT pg_terminate_backend($1) AS signaled-- but the pid is a bound parameter, so only its count is logged (PostgreSQL's own log can record the value; see the end of this section). If the target was one of this server's own statements and the signal took effect, that statement writes its ownok: falseline (normallysqlstate57014for a cancel and57P01for a terminate), andtsis all that pairs the two. Measured against local servers over loopback TCP, the target's line usually carried the same millisecond as thepg_killline or the next, and terminating a CPU-bound target took up to a few hundred milliseconds; a target that is slow to reach an interrupt check can take longer still. The target's line is normally the later of the two, occasionally the earlier. Treat closeness as evidence, not proof: a statement timeout writes57014too. UnderPOSTGRES_AUDIT_REDACTboth modes readsqlKeywordSELECT, so tell a cancel from a terminate by hashing the two texts above -- the exact text with no trailing newline, single-quoted in a shell so that$1survives.Whether a
pg_killsignal took effect.okdescribespg_kill's own statement, and thesignaledvalue it returned is not logged.ok: truecovers a signal that landed, a pid that is not a backend (postgres answersfalse), and a cancel that changed nothing: postgres answerstrueonce the signal is sent, not once it has taken effect, and a session that is idle in a transaction, for one, ignores it.ok: falsewith42501is a refusal: the role may not signal that backend.ok: falsewith57014or57P01on thepg_killline itself meanspg_kill's own statement was cancelled or terminated, as happens when the pid names the connectionpg_killis running on; after such a terminate that backend is gone, even though the line readsok: false. A call refused for want ofALLOW_WRITES=1sends nothing and writes nothing.The scaffolding around agent SQL (
BEGIN READ ONLY, thepg_backend_pid()lookup, the row-cap savepoint and cursor, the closingCOMMIT/ROLLBACK, theDISCARD ALLsession reset), thepg_typelookup behinddataTypeName, and thehypopg_create_index/hypopg_resetcalls behindpg_explain'shypothetical_indexes. None of these gets a line of its own. ABEGIN, a savepoint or ahypopg_create_indexthat fails does show, on the statement's ownok: falseline (seeokabove), because the statement is never sent; apg_typelookup that fails does not, because the statement already ran and the lookup only decorates its result.pg_index_advisoris the exception: everything it sends is logged, including its transaction control and theEXPLAINof each workload statement. The server-version probe some tools run first,SELECT current_setting('server_version_num') AS v, is an ordinaryinternalline: once per successful reading, which is then cached for the life of the process (calls that race the first reading share it), and on every probing call while the server is unreachable, since a failure is not cached.The statement a call never got as far as composing. Every tool records a refused connection as the
ok: falseline of the first statement it was about to send, under its owntool, withsqlstateholding the Node error code or absent for a connect timeout: the agent's SQL forpg_queryandpg_readonly; forpg_explaintheEXPLAINitself, unless a version-floored option (settings,wal,generic_plan,memory,serialize,bufferswithoutanalyze) orhypothetical_indexeswas passed, when the line is the version probe's or the HypoPG check's and theEXPLAIN, composed only after them, is not on it; the signal statement forpg_kill; and the version probe or the first catalog query for the rest, including the tools that share one connection across several queries (pg_describe_table,pg_health,pg_advisor,pg_replication_status,pg_seq_scan_tables,pg_unused_indexes,pg_io_stats), whose first query is the one that checks the connection out.
PostgreSQL's own logging is the complete server-side record: log_statement = 'all' records every statement that reaches execution, and log_min_error_statement, at its default error, adds statements that fail earlier. It also records exactly what this trail keeps out -- bound parameter values and full error messages.
Troubleshooting
DATABASE_URL is not set - Your MCP client is launching the server without the env var. On Windows especially, env vars set in bash / PowerShell profiles are not inherited by MCP servers launched via cmd. Put DATABASE_URL directly in the env block of .mcp.json.
password authentication failed - Check the username, password, and that the user has CONNECT privilege on the database. URL-encode special characters in the password (@ → %40, # → %23, / → %2F).
SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string - The password in your connection string is empty or became null after URL decoding. Re-check your connection string.
canceling statement due to statement timeout - A single query exceeded POSTGRES_STATEMENT_TIMEOUT_MS (default 30s). Increase it, narrow the query with WHERE, or add an index. This is working as designed -- the timeout exists so a runaway query cannot hang the agent.
Blocked in read-only mode: ... - The statement or function is refused on read-only paths (list). Rewrite it as a plain read; put settings on the role (ALTER ROLE ... SET ...) or in DATABASE_URL, since session state does not carry between calls. On pg_index_advisor, a blocked row read from pg_stat_statements is skipped with a _warnings entry and the call still succeeds -- you cannot rewrite a row the database recorded, so no action is needed.
Result exceeded POSTGRES_MAX_RESULT_BYTES - Select fewer or narrower columns, add a LIMIT, or raise the variable.
Query exceeded the ... client-side deadline - The statement outlived POSTGRES_STATEMENT_TIMEOUT_MS by the grace period. Narrow it, or raise that and POSTGRES_QUERY_DEADLINE_MS.
Write blocked: this server is in read-only mode - You asked the agent to write via pg_query but ALLOW_WRITES is not set. Either add ALLOW_WRITES=1 to the env block of .mcp.json and restart your MCP client (dev/test DBs), or - cleaner for production - use a role with INSERT/UPDATE/DELETE grants in DATABASE_URL and keep ALLOW_WRITES unset. See Configuring access. Note that pg_readonly always rejects writes; if you want writes, the call has to go through pg_query.
Error: [postgres-mcp] POSTGRES_AUDIT_... or Error: [postgres-mcp] audit log file ... could not be opened for append at startup - An audit variable is misconfigured, and the server exits with a stack trace rather than guess. The Error: line says which case you hit: an unrecognized value (it lists the accepted ones), a variable that is set but empty (usually an unexpanded variable in the MCP config -- remove it from the env block, or give it a real value: 0 or 1 for the two flags, a path for the file), a file set while POSTGRES_AUDIT_LOG is off, or the OS error from opening the file -- ENOENT usually means its directory does not exist, and Access to this API has been restricted means POSTGRES_MCP_SANDBOX=1. See Audit logging.
postgres-mcp: POSTGRES_MCP_SANDBOX=... refusing to start without the sandbox - The sandbox was requested but cannot be applied, so the launcher stops rather than run the server without it. The first line names the case and the last line the fix: POSTGRES_MCP_RUNTIME=node (Node has no --permission); no usable oam 0.21.1 or newer (the indented lines list what was found and why each was passed over); an oam that failed to launch; or a database endpoint that cannot be pinned -- a Unix socket (oam can dial one, but the sandbox only grants a TCP host and port; connect over TCP, or unset POSTGRES_MCP_SANDBOX), several hosts, a port outside 1-65535, a host with whitespace or non-ASCII characters (use its xn-- form), or a DATABASE_URL that is not a readable postgres:// URL. DATABASE_URL itself is never printed. postgres-mcp: POSTGRES_MCP_SANDBOX="..." is not a recognized value means the value is wrong: 1 or true turns the sandbox on, 0, false or off turns it off.
Connection pool exhaustion with PgBouncer transaction mode or pglite-socket - These backends don't support concurrent queries on a single connection. Set POSTGRES_POOL_MAX=1 in the env block.
First query is slow, subsequent queries are fast - Expected. The pg driver lazily establishes the first connection; subsequent queries reuse the pool.
Development
Run the full suite (unit + integration) against a real Postgres:
DATABASE_URL='postgres://user:pass@host:5432/db' POSTGRES_MCP_INTEGRATION=1 npm run test:integrationThe integration suite assumes a disposable database -- it creates and drops a test_fixture schema. Don't point it at anything you care about.
To run the POSTGRES_MCP_SANDBOX path against a real oam as well -- a handshake and select 1 through the launcher under --permission, then a dial to the port next to the pinned one, which must be refused with ERR_ACCESS_DENIED -- set OAM_BIN beside DATABASE_URL. That file is skipped unless both are set, and it never writes:
OAM_BIN=/path/to/oam DATABASE_URL='postgres://user:pass@host:5432/db' npm run test:integrationTo also run the destructive tests (REVOKE / restricted-role path), add POSTGRES_MCP_DESTRUCTIVE_TESTS=1. Only safe on a disposable cluster:
DATABASE_URL='postgres://user:pass@host:5432/db' POSTGRES_MCP_INTEGRATION=1 POSTGRES_MCP_DESTRUCTIVE_TESTS=1 npm run test:integrationWindows: integration tests via WSL2
Native Postgres on Windows ARM64 is fragile (UCRT runtime gaps, missing ARM64 builds). The reliable path is a disposable Ubuntu under WSL2 with the integration suite running inside WSL (WSL2's NAT blocks the Windows host from reaching :5432, so don't try to run the tests from PowerShell):
wsl --install -d Ubuntu --no-launch
# reboot, then:
wsl -d Ubuntu -u root bash -c "apt-get update && apt-get install -y nodejs npm rsync"
wsl -d Ubuntu -u root bash /mnt/c/path/to/postgres-mcp/scripts/wsl-pg-setup.sh
wsl -d Ubuntu -u root bash /mnt/c/path/to/postgres-mcp/scripts/wsl-test-matrix.shwsl-pg-setup.sh installs PG15, PG17 and PG18 from the PGDG apt repo (ports are auto-assigned by pg_createcluster -- typically 17 on 5432, 18 on 5433, 15 on 5434), sets the postgres password to postgres, and creates postgres_mcp_test in each. wsl-test-matrix.sh rsyncs the working tree into /root/postgres-mcp, runs npm ci once, and runs the integration suite against every cluster found via pg_lsclusters.
Running these from Git Bash instead of PowerShell? Prefix both script invocations with MSYS_NO_PATHCONV=1. Git Bash rewrites the /mnt/c/... argument before wsl.exe sees it, so the script arrives as C:/Users/<you>/scoop/apps/git/<ver>/mnt/c/... and bash exits with "No such file or directory" having run nothing. Also avoid piping either script into tail/head -- the pipeline's exit status is the last command's, so a failing matrix reports success.
Tear down when finished: wsl --unregister Ubuntu.
License
MIT © 2026 YawLabs
Available Tools
23 toolspg_advisorDatabase advisor (DBA lints)ARead-onlyIdempotent
Rolled-up DBA lint pass. One call returns four categories of findings:
sequence_exhaustion: SERIAL / BIGSERIAL / IDENTITY sequences whose
last_valueis aboveseqExhaustionThresholdofmax_value. The classic incident class.wraparound_risk: transaction-ID AND multixact wraparound pressure, the classic pageable incident.
{autovacuum_freeze_max_age, autovacuum_multixact_freeze_max_age, databases[], tables[]}. Those two cluster GUCs are the divisors both lists are measured against (null if unreadable). Multixact IDs are a SEPARATE 32-bit counter, consumed by row-level locking (SELECT ... FOR SHARE/UPDATE, FK checks), so a lock-heavy workload can exhaust them while relfrozenxid stays perfectly healthy -- both counters are checked here.databasesrows:{database, xid_age (age(datfrozenxid)), mxid_age (mxid_age(datminmxid)), pct_of_freeze_max_age, pct_of_multixact_freeze_max_age, triggered_by}-- template databases included, since template0 ages like any other and the cluster horizon is the minimum across all of them.tablesrows:{schema, table, relkind, xid_age (age(relfrozenxid)), freeze_max_age, pct_of_freeze_max_age, mxid_age (mxid_age(relminmxid)), multixact_freeze_max_age, pct_of_multixact_freeze_max_age, triggered_by}, wherefreeze_max_age/multixact_freeze_max_ageare the EFFECTIVE limits -- a per-tableautovacuum_freeze_max_age/autovacuum_multixact_freeze_max_agestorage parameter wins over the GUC. A row is returned when EITHER ratio is at or abovewraparoundThreshold, andtriggered_by('xid' | 'multixact' | 'both') says which one did it: 'xid' means chase freezing/autovacuum, 'multixact' means chase the lock-heavy workload burning members.mxid_ageandpct_of_multixact_freeze_max_ageare null on rows whose minmxid is InvalidMultiXactId (no multixact ever recorded); such rows can only be xid-triggered. At pct_of_freeze_max_age 1.0 autovacuum forces an anti-wraparound VACUUM, and near 2.1 billion xids (or 4.2 billion multixacts) the server stops accepting writes.tablesdeliberately includes pg_catalog and pg_toast relations -- the culprit is more often a TOAST table or a system catalog than a user table. On PG18+ table rows also carrypages/all_frozen_pages/frozen_page_fractionfrompg_class.relallfrozen(visibility-map freeze coverage); those three keys are ABSENT on older servers rather than null.tables_without_primary_key: user tables (plain and partitioned) with no PK defined. Bloat candidates and a sign of design drift; some replication setups also need PKs. Foreign tables are excluded -- PostgreSQL forbids declaring PKs on foreign tables.
public_tables_without_rls: tables in
public(or any schema inrlsSchemas) with row-level security disabled. Useful as a security baseline check. Any category whose query fails (permission-gated catalogs on managed providers) appends to_warningsand returns empty; the other categories still return. Use this as the 'what should I be looking at?' starting point, then drill intopg_unused_indexes,pg_table_bloat,pg_seq_scan_tablesfor the perf side.
Inputs: limit, rlsSchemas, wraparoundThreshold, seqExhaustionThreshold. Returns: _warnings, wraparound_risk, sequence_exhaustion, public_tables_without_rls, +1…
pg_describe_tableDescribe tableARead-onlyIdempotent
Describe a relation: kind (table / view / materialized_view / partitioned_table / foreign_table), columns (name, type, nullable, default, generated, identity), primary key, foreign keys (outgoing), referenced_by (other tables whose FKs point at this one), constraints (CHECK / UNIQUE non-PK / EXCLUDE), indexes, and partition info (partition_of parent, partitions children). Works on views and materialized views too -- PK/FK/constraint/index lists will simply be empty for a plain view. Use kind to disambiguate before assuming you can write to the relation. Generated columns (generated: 'stored' / 'virtual') and identity: 'always' columns are NOT writable -- omit them from INSERT/UPDATE column lists; a generated column's expression is reported as generation_expression, never as default_value. On PostgreSQL 18+ constraints also report validated / enforced / has_period, and columns report not_null_validated -- a NOT VALID not-null constraint means nullable: false can still hide NULLs.
Inputs: table (required), schema. Returns: kind, table, schema, columns, +8 more
pg_explainExplain query planADestructive
Get the query plan for a SQL statement. By default, this uses plain EXPLAIN (no execution). Set analyze: true to run the query with EXPLAIN ANALYZE - for non-SELECT statements, ALLOW_WRITES=1 is required (since ANALYZE actually executes the statement). Writes executed during EXPLAIN ANALYZE are rolled back, so you can inspect a plan for an INSERT/UPDATE/DELETE without persisting the rows -- but only what Postgres rolls back is undone: a sequence the statement advanced (nextval, a serial or identity column) stays advanced, and any side effect of a function the statement called that lands outside table data (pg_terminate_backend, an advisory lock) persists. Format is text (default) or json. Pass the raw SQL (not an EXPLAIN-prefixed statement). Planner options (all optional): buffers reports shared/local/temp block hits and is the fastest way to tell a bad plan from a cold cache - it defaults to TRUE whenever analyze is true (matching PostgreSQL 18, which turns it on for you), pass buffers: false to suppress it; requesting it WITHOUT analyze needs PostgreSQL 13+. verbose adds output columns and schema-qualified names. settings (PostgreSQL 12+) lists planner GUCs set away from their defaults - the usual explanation for a plan that looks impossible. wal (PostgreSQL 13+) reports WAL generated and serialize (none|text|binary, PostgreSQL 17+) charges the cost of building the result rows; both require analyze. memory (PostgreSQL 17+) reports memory used by the PLANNER, so it works with or without analyze - use it alone to ask why planning a statement is expensive. generic_plan (PostgreSQL 16+) plans a parameterized statement WITHOUT values for its $1/$2 placeholders and cannot be combined with analyze or params. costs and timing default to true (as in postgres); set either to false to drop those columns, and note timing only applies with analyze. Options that need a newer server than the one connected are rejected with an explicit error naming the required version instead of a confusing parse failure. Set hypothetical_indexes to a list of {table, columns, using?} to ask the planner 'what would the plan be if these indexes existed?' -- requires the HypoPG extension (CREATE EXTENSION hypopg). The hypothetical indexes are torn down at the end of the call, never touching real disk.
Inputs: sql (required), wal, costs, format, +10 more. Returns: plan
pg_healthDatabase health snapshotARead-onlyIdempotent
Quick health snapshot: server version, database size, connection counts measured against max_connections, active queries with their wait events, a pg_stat_database rollup, and table count. Useful as a connection sanity check and to spot runaway queries, connection-cap pressure, and lock/IO waits.
connections:
totalfor the CURRENT database, broken down intoactive/idle/idle_in_transaction/idle_in_transaction_aborted/other(starting, fastpath function call, disabled) /state_unavailable-- those six sum tototal.idle_in_transaction_abortedis called out separately because it holds locks and blocks vacuum while doing no work and will never commit.state_unavailablecounts sessions whosestatereads NULL because the role lacks pg_read_all_stats / pg_monitor membership; a non-zero value means every other bucket is under-counted by at least that much, so do NOT readactive: 0next to it as an idle database. Pluscluster_client_backends(client backends across ALL databases -- those are what actually consume connection slots),max_connections,superuser_reserved_connections, andused_fraction(cluster_client_backends / max_connections). A raw connection count means nothing without the cap; readused_fractionfirst.active_queries:
pid,state,query,application_name,backend_type,wait_event_type/wait_event(both NULL when the backend is running rather than waiting -- the single most diagnostic pair in pg_stat_activity). Both are reported verbatim as the server spells them, and that spelling changes between majors: a backend waiting on a buffer pin reportswait_event_type'BufferPin' through PostgreSQL 18 and 'Buffer' from 19 on, with thewait_eventnames beneath it changing to match. Read them against the reportedversionrather than hard-coding a literal.duration_seconds(since query_start) andtransaction_age_seconds(since xact_start). A large transaction_age_seconds next to a small duration_seconds is a long-open transaction, the usual root cause behind lock waits, bloat, and stalled autovacuum.database_stats: pg_stat_database for the current database --
deadlocks,temp_files/temp_bytes(work_mem spills),conflicts(recovery conflicts, only ever non-zero on a replica),blks_hit/blks_read/cache_hit_ratio, andstats_reset. Every counter is CUMULATIVE since stats_reset, not a rate -- interpret them against that timestamp. Sub-queries that fail (several of these are permission-gated on managed providers) append to_warningsand leave their field null; the rest of the snapshot still returns.
Inputs: activeQueryLimit. Returns: version, database, _warnings, connected, +4 more
pg_index_advisorRecommend indexes for a workloadARead-onlyIdempotent
Recommend indexes for a workload, and prove each one pays for itself before recommending it. Give it statements (the SQL you care about) or let it take the top N from pg_stat_statements; it plans each statement, generates candidate indexes, costs them with HypoPG hypothetical indexes, and returns only the ones that measurably cut estimated cost.
How candidates are generated, and the honest limit: this tool has NO SQL parser and does not read your SQL text. It EXPLAINs each statement and harvests the columns the PLANNER reports as filters, join keys, and sort keys, then intersects those tokens with the real column list from pg_attribute -- so a candidate can never name a column that does not exist. The extraction is deliberately loose (a token matching a real column name on a different table can slip through); HypoPG is the arbiter, and anything that does not lower cost is discarded. Column ORDER within each candidate is equality columns first (most selective first, from pg_stats), then at most one range column, then sort columns.
The search is greedy and BOUNDED. Each accepted index stays in place while the rest are re-costed on top of it, so later picks account for what earlier ones already fixed. max_candidates caps how many candidates are considered and max_explains caps total EXPLAIN round trips; when a cap stops the search early, budget_exhausted is true and the result is a truncated search, not a converged one.
PostgreSQL 18 note, and it reverses a rule you have probably internalized: PG18 added B-tree SKIP SCAN, so a multi-column index whose LEADING column the query never constrains CAN now be used. The classic 'leading column never filtered means the index is useless' heuristic is wrong on PG18+. This tool gates that prune on the server version -- on PG18+ such candidates are kept and costed (skip_scan_available: true, and an accepted one carries requires_skip_scan), below PG18 they are pruned as unusable and counted in candidates_pruned_leading_column.
Requires the HypoPG extension (CREATE EXTENSION hypopg;). Hypothetical indexes are session-scoped and are reset before the call returns, on the success and the failure path alike, so they never touch disk and never leak into a later query plan. Statements are only ever EXPLAINed, never executed, inside a BEGIN READ ONLY transaction.
Costs are PLANNER ESTIMATES, not measurements: they are the right way to compare two plans for the same statement and the wrong way to predict wall-clock time. They are weighted by calls when the workload came from pg_stat_statements, so a query run a million times outranks an identical one run twice. Validate a recommendation with pg_explain before creating it, and create it with CONCURRENTLY in production (create_statement_concurrently).
Inputs: limit, schema, statements, max_explains, +4 more. Returns: _warnings, statements, explains_used, explain_budget, +7 more
pg_inspect_locksInspect blocking locksARead-onlyIdempotent
Show current lock contention: which sessions are blocked and who is blocking them. Returns blocked PID, blocking PID, lock types, relation being contested, and the queries involved. Use this first when a tool call hangs or the app feels stuck - it's the fastest way to identify a long-held transaction holding a lock. Row shape: one row per (blocked_pid, blocking_pid) pair. A session waiting on multiple blockers appears on multiple rows -- group/deduplicate by blocked_pid if you want a per-blocked-session count. Scope: CLUSTER-WIDE, unlike pg_health active_queries, which is filtered to the database in DATABASE_URL. Lock waits cross databases (a shared catalog, a long transaction in a sibling database), so the blocker is not always somewhere this connection could see -- but it does mean a row here may name a pid in another database entirely. relation is only resolved for locks in the CURRENT database or on a cluster-shared catalog (pg_authid, pg_database, ...); it is NULL for a lock held in another database, because a pg_class OID is only meaningful within its own database. A NULL relation has TWO unrelated causes, and lock_type is what tells them apart. When the wait is ON a relation (lock_type relation / extend / page / tuple), NULL means the lock is held in another database and cannot be named from here. When the wait is on something else (transactionid / virtualxid / advisory), relation was only ever a best-effort hint -- an alphabetical guess among the blocker's held write-intent locks, not authoritative -- so NULL there means the guess found no candidate, and the blocker is very likely LOCAL. Do not read that second case as 'somewhere else': use blocking_pid and blocking_query, which are populated either way. Note also that pg_cancel_backend / pg_terminate_backend signal by PID across the whole cluster, so even a genuinely cross-database blocker is actionable via pg_kill. Use the blocked/blocking query text to disambiguate which table is actually contested.
Inputs: limit. Returns: rows
pg_io_statsI/O statistics and in-flight async I/OARead-onlyIdempotent
I/O observability: cumulative per-backend-type I/O from pg_stat_io (PostgreSQL 16+), plus in-flight asynchronous I/O handles from pg_aios (PostgreSQL 18+). This is the layer underneath pg_top_queries and pg_health -- it says WHICH subsystem is doing the I/O (client backends vs autovacuum vs checkpointer vs walwriter) and through which path, which a per-query or per-table view cannot.
io: one row per (
backend_type,io_object,io_context) combination. Countersreads/writes/extends/writebacks/hits/evictions/reuses/fsyncsare bigints returned as decimal strings;read_time_ms/write_time_ms/writeback_time_ms/extend_time_ms/fsync_time_msare float8 milliseconds. A timing of 0 next to a non-zero op count meanstrack_io_timingis off, NOT that the I/O was free -- turn it on to get real numbers. A NULL counter means the operation is not possible for that combination, which is different from 0.io[].read_bytes / write_bytes / extend_bytes: a normalized byte figure that means the same thing on every supported server. On PG16-17 it is computed as
op_bytes * <op count>; on PG18op_byteswas removed and the server reports bytes directly. The top-levelbyte_accountingfield says which source produced the numbers.io[].stats_reset: these are CUMULATIVE counters, so a row is only interpretable next to its reset point. Reported per row because that is how the view reports it;
pg_stat_reset_shared('io')resets them together in practice, but this tool does not assert that.Rows whose counters are all zero are omitted by default (
pg_stat_iois mostly zeros on a quiet system, and the noise buries the handful of rows that matter). PassincludeZeroRows: truefor the full matrix.in_flight + io_method: PostgreSQL 18+ ONLY, and both keys are ABSENT on older servers rather than empty/null -- an empty
in_flightarray would read as 'nothing is stalled' when the truth is 'this server cannot tell you'.in_flightis live, currently-outstanding async I/O (pid,io_id,op,state,off,length,target_desc), which is what you want while a stall is happening rather than after it.io_method(worker/io_uring/sync) explains whatin_flightcan contain: withio_method = syncthere is no asynchronous submission, so the array is legitimately empty no matter how much I/O is running. Requires PostgreSQL 16+. Sub-queries that fail (pg_stat_ioandpg_aiosare permission-gated on some managed providers) append to_warningsand set their field to null; the rest of the response still returns.
Inputs: limit, includeZeroRows. Returns: io, _warnings, in_flight, io_method, +3 more
pg_killCancel or terminate a backendADestructive
Cancel a running query (SIGINT-equivalent) or terminate a backend connection (SIGTERM-equivalent) by PID. Find the PID via pg_health active_queries or pg_inspect_locks. Requires ALLOW_WRITES=1 since this changes database session state. The role in DATABASE_URL must have permission - cancelling another user's query needs the pg_signal_backend role or superuser. Note: pg_signal_backend does NOT cover superuser-owned backends - only a superuser can signal another superuser's session. Cancel is graceful; terminate is forceful. signaled=true means postgres SENT the signal, not that the target stopped: a session that is idle (or idle in a transaction) ignores a cancel, so re-check with pg_health and use terminate for an idle session. signaled=false means postgres found no backend with that PID; the note field carries its own warning (e.g. 'PID 123 is not a PostgreSQL backend process'). A permission denial is NOT a false: postgres raises, so the call returns an error with SQLSTATE 42501 that says what the role lacks.
Inputs: pid (required), mode. Returns: pid, mode, note, signaled
pg_list_extensionsList installed extensionsARead-onlyIdempotent
List installed PostgreSQL extensions. Returns name, version, schema, and description. Useful to check for pgvector, postgis, pg_stat_statements, uuid-ossp, etc. before writing queries that rely on them.
Inputs: no named parameters. Returns: rows
pg_list_functionsList functions and proceduresARead-onlyIdempotent
List functions, procedures, and aggregates in a schema. Returns name, arguments, return type, kind (function/procedure/aggregate/window), and implementation language.
Inputs: schema. Returns: rows
pg_list_rolesList rolesARead-onlyIdempotent
List database roles (users and groups) with their login/superuser/createdb/createrole attributes and inherited role memberships. Use this to answer 'who has access to this database?' without needing to read pg_authid directly.
Inputs: includeSystem. Returns: rows
pg_list_schemasList schemasARead-onlyIdempotent
List non-system schemas in the database. Excludes pg_catalog, information_schema, and other pg_* internals.
Inputs: no named parameters. Returns: rows
pg_list_tablesList tables in a schemaARead-onlyIdempotent
List tables (and optionally views) in a schema. Returns name, type (table/view/materialized view/foreign), and estimated row count (from reltuples; null = no ANALYZE yet on PG 14+; 0 may mean empty or unanalyzed on PG <= 13). Paginate via limit/offset on very large schemas.
Inputs: limit, offset, schema, includeViews. Returns: rows
pg_list_viewsList views with definitionsARead-onlyIdempotent
List views and materialized views in a schema with their SQL definitions. Use this over pg_list_tables with includeViews: true when you want the view body, not just names.
Inputs: schema, includeMaterialized. Returns: rows
pg_queryRun SQL queryADestructive
Run a SQL query against the configured PostgreSQL database. Postgres itself is the primary safety gate: the role in DATABASE_URL enforces what queries can succeed. The recommended posture is a least-privileged role (e.g. one granted pg_read_all_data), which makes writes server-rejected regardless of any env var. ALLOW_WRITES=1 is a secondary belt-and-braces gate - it lifts the in-server BEGIN READ ONLY wrapper, but it cannot grant privileges the role lacks. Useful for managed databases where creating a second role is awkward. Without ALLOW_WRITES this applies the same statement checks as pg_readonly, which stays read-only whatever the flag says. Use params for parameterized queries to avoid SQL injection. Params can be strings, numbers, booleans, null, arrays (for postgres arrays / ANY), or objects (for json/jsonb columns). Dates and UUIDs can be passed as ISO strings. Large result sets are truncated to POSTGRES_MAX_ROWS (default 1000) with a truncated: true flag; a result over POSTGRES_MAX_RESULT_BYTES fails instead. Session state does not carry over between calls.
Inputs: sql (required), params. Returns: rows, fields, command, rowCount, +1 more
pg_readonlyRun read-only SQLARead-onlyIdempotent
Run one SQL statement inside a BEGIN READ ONLY transaction that is always rolled back, regardless of ALLOW_WRITES. Postgres rejects INSERT/UPDATE/DELETE/DDL there. Use this to read: SELECT, WITH ... SELECT, VALUES, TABLE, SHOW, EXPLAIN. Statements that escape or reshape the transaction are refused (SET, RESET, DO, CALL, PREPARE, EXECUTE, COPY, LOCK, transaction control and similar), as are calls to known out-of-transaction functions (dblink*, set_config, pg_read_file, lo_export, pg_terminate_backend, ...). These checks are best-effort and are NOT a security boundary: a function wrapper gets past them, and a function can write through its own connection. The DATABASE_URL role is the boundary, so do not auto-allow this tool unless that role is least-privilege. Use params for parameterized queries to avoid SQL injection. Params can be strings, numbers, booleans, null, arrays (for postgres arrays / ANY), or objects (for json/jsonb columns). Large result sets are truncated to POSTGRES_MAX_ROWS (default 1000) with a truncated: true flag; a result over POSTGRES_MAX_RESULT_BYTES fails instead, and a call past POSTGRES_QUERY_DEADLINE_MS has its backend terminated.
Inputs: sql (required), params. Returns: rows, fields, command, rowCount, +1 more
pg_replication_statusReplication statusARead-onlyIdempotent
Replication overview: configured replication slots, connected replicas (from pg_stat_replication), and current WAL position. Use on primary to spot lagging or disconnected replicas, on replicas to see upstream status. Returns empty arrays on a standalone (non-replicated) database rather than erroring.
Inputs: no named parameters. Returns: slots, replicas, _warnings, is_replica, +1 more
pg_search_columnsSearch columns by nameARead-onlyIdempotent
Search for columns by name across all user schemas. Supports SQL LIKE patterns (% matches any substring, _ matches one character). Case-insensitive. Use this instead of iterating pg_describe_table when the user asks 'which tables have X'.
Inputs: pattern (required), limit, schema. Returns: rows
pg_seq_scan_tablesFind tables with heavy sequential scansARead-onlyIdempotent
Tables with high sequential-scan counts relative to index scans - the first place to look for missing-index candidates. Returns {rows, stats_reset, stats_reset_age_seconds}: each row has seq_scans, idx_scans, live tuples, and the ratio. A high ratio on a large table usually means a query is reading the whole table where an index would suffice. Pair with pg_top_queries to find which query is doing it.
These counters are cumulative since the last statistics reset, so every ratio here is only meaningful relative to the top-level stats_reset (and stats_reset_age_seconds). A ratio measured over a window that was reset minutes ago describes that window, not the workload; stats_reset: null means the start of the window is unknown.
On PostgreSQL 16+ each row also carries last_seq_scan and last_idx_scan timestamps (null = no such scan since the reset), which separate 'scanned hard months ago' from 'being scanned right now' in a way the raw counts cannot.
Inputs: limit, schema, minSize. Returns: rows, _warnings, stats_reset, stats_reset_age_seconds
pg_table_bloatEstimate table bloatARead-onlyIdempotent
Estimate table bloat (dead tuples + free space) for tables in a schema. Returns live tuples, dead tuples, dead-tuple ratio, last_vacuum / last_autovacuum timestamps, and total relation size. A high dead_ratio with a stale last_autovacuum is a sign a table needs VACUUM.
On PostgreSQL 19+ every row also carries stats_reset: the last time THAT relation's counters were reset via pg_stat_reset_single_table_counters(). Read it before trusting anything else in the row -- a reset zeroes live_tuples and dead_tuples AND clears last_vacuum / last_autovacuum / last_analyze together, so a table reset a minute ago is indistinguishable from a pristine one without it. The key is ABSENT on older servers rather than null; null on PG19+ means this relation's counters have never been reset.
Three methods are available via the method parameter:
estimate(default): reads pg_stat_user_tables -- fast, no extensions, ANALYZE-driven approximations. Use this first.approx: uses pgstattuple_approx() -- fast sampling pass, more accurate than estimates, requires the pgstattuple extension.exact: uses pgstattuple() -- full table scan, exact counts, slow on large tables, requires the pgstattuple extension. Always passschemawith method='exact' -- scanning all user tables in one statement will hit statement_timeout on non-trivial databases. Install pgstattuple withCREATE EXTENSION pgstattuple(requires superuser).
Inputs: limit, method, schema, minDeadRatio. Returns: rows
pg_table_privilegesShow table privilegesARead-onlyIdempotent
Show which roles have which privileges (SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER) on a table or on every table in a schema. If table is omitted, the result spans every table in schema, ordered by table then grantee. Use this to answer 'who can write to this table?' or to audit schema-wide access before a migration. Visibility caveat: backed by information_schema.table_privileges, which postgres filters by what the calling role can see. A least-privileged role may not see grants involving unrelated third-party roles. For a complete picture, run as a superuser or a member of pg_read_all_data.
Inputs: table, schema. Returns: rows
pg_top_queriesTop queries by execution timeARead-onlyIdempotent
Top N queries by total or mean execution time. Requires the pg_stat_statements extension to be installed and enabled (most managed Postgres providers have it on by default). Returns {rows, stats_reset, stats_reset_age_seconds, dealloc}: each row has normalized query text (constants replaced with ?), call count, total/mean/min/max time in ms, rows returned, and cache hit ratio. Use this to find slow queries worth optimizing.
calls and total_time_ms are cumulative since the last pg_stat_statements_reset(), so this ranking only describes the window that started at the top-level stats_reset (with stats_reset_age_seconds beside it). This is pg_stat_statements' OWN reset clock, read from pg_stat_statements_info -- it is independent of the stats_reset reported by pg_seq_scan_tables / pg_unused_indexes, which comes from pg_stat_database, so do not compare the two timestamps or assume one implies the other. stats_reset: null means the start of the window is unknown, not that it covers all time.
READ dealloc BEFORE TRUSTING THE RANKING: it counts how many times entries for the LEAST-EXECUTED statements were evicted because more distinct statements were seen than pg_stat_statements.max allows. A non-zero dealloc means this ranking is drawn from an INCOMPLETE population -- queries may be missing from these results entirely, and an evicted query's counters restart from zero if it runs again, understating it. The larger dealloc is, the more churn, so 'not in the top N' stops being evidence that a query is cheap. Raise pg_stat_statements.max to get a complete picture.
On pg_stat_statements < 1.9 (before Postgres 14) pg_stat_statements_info does not exist, so stats_reset, stats_reset_age_seconds and dealloc are omitted entirely rather than returned as nulls, and a _warnings entry says so.
On pg_stat_statements >= 1.10 (Postgres 15+), also returns io_read_time_ms and io_write_time_ms to separate IO-bound from CPU-bound queries (null when track_io_timing = off or the query did no measurable IO -- enable track_io_timing in postgresql.conf to get non-null values). Scoped to the database in DATABASE_URL: pg_stat_statements is cluster-wide, so results are filtered by dbid to match every other tool here rather than leaking query text from unrelated databases sharing the cluster.
Inputs: limit, orderBy. Returns: rows, dealloc, _warnings, stats_reset, +1 more
pg_unused_indexesFind unused indexesARead-onlyIdempotent
Indexes that have never been scanned or have very low usage, largest first. Each unused index costs write amplification (every INSERT/UPDATE maintains it) and disk space, so before adding a new index, check whether the fix is to drop a dead one. Returns {rows, stats_reset, stats_reset_age_seconds}.
READ THIS BEFORE RECOMMENDING A DROP: scans is a counter, not a verdict. It only counts since the last statistics reset, which is why the top-level stats_reset and stats_reset_age_seconds are part of the answer. If the counters were reset an hour ago, EVERY index looks unused; if stats_reset is null, the start of the window is unknown and the counts prove nothing. This list is only trustworthy once the reset age comfortably exceeds the slowest cycle that could use the index - a monthly report, a quarterly close, a yearly job, a failover-only query path.
PRIMARY KEY and UNIQUE indexes are already excluded from these results: they enforce a constraint and stay load-bearing at zero scans, so they never appear here and their absence is not evidence of anything.
On PostgreSQL 16+ each row also carries last_idx_scan, the timestamp of the most recent scan (null = never scanned since the reset). 'Not scanned since 2026-02-14' is a far better basis for a decision than a bare count.
On PostgreSQL 18+, do not fall back on the old 'the leading column is never filtered, so this index is dead weight' reasoning. Skip scan lets the planner use a multi-column btree whose leading column is unconstrained, so such an index can now be doing real work.
Inputs: limit, schema, maxScans. Returns: rows, _warnings, stats_reset, stats_reset_age_seconds
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 23 tools
Most tools target clearly distinct diagnostic surfaces (locks, replication, bloat, indexes, privileges), but there are a few genuinely overlapping clusters: pg_query vs pg_readonly are near-identical in shape, and pg_health vs connections vs active_queries vs database_stats carve one snapshot into four separate calls. The descriptions do a good job asserting the boundaries (pg_readonly is explicitly 'read-only regardless of ALLOW_WRITES'), and pg_list_views vs pg_list_tables includeViews is disambiguated in text, so the overlaps are documented rather than hidden.
A strong `pg_` + verb_noun pattern dominates (pg_list_tables, pg_describe_table, pg_inspect_locks, pg_search_columns), but four tools break it entirely: connections, active_queries, database_stats, and io — and those unprefixed names are exactly the ones most likely to collide with other servers or be taken for generic resources. Noun-only names (pg_health, pg_readonly, io, connections) sit alongside verb-first names, so the convention is readable but not uniform.
23 tools is on the heavy side, but this is a full DBA observability surface and nearly every tool occupies a distinct diagnostic niche (I/O stats, sequence exhaustion, privilege audit, bloat estimation), so few feel redundant. It would be tighter if the four connection/activity counters were folded into pg_health, but nothing is clearly padding.
Coverage is unusually deep for the diagnostic domain: ad-hoc querying, plans, health, locks, replication, bloat, index and workload analysis, roles and privileges, plus a rolled-up advisor pass — there are no obvious dead ends for an investigation workflow. Gaps are mostly write-side/maintenance operations (no VACUUM/ANALYZE trigger, no settings/GUC inspection, no database listing), which are reachable through pg_query with ALLOW_WRITES but not offered as first-class tools.
Maintenance
Related MCP Connectors
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceProvides authenticated access to PostgreSQL databases for Claude AI, enabling users to browse database tables, discover schemas, and execute custom SQL queries through natural language interaction.MIT
- FlicenseNot gradedqualityDmaintenanceEnables natural language querying of PostgreSQL databases through the Model Context Protocol. It translates user questions into validated SQL, executes read-only queries safely, and returns results to MCP-compatible clients like Claude Desktop.-
- AlicenseAqualityDmaintenanceConnects Claude to any PostgreSQL database, enabling schema exploration, query execution, and performance analysis through natural conversation.76 npm1MIT
- AlicenseAqualityCmaintenanceExposes PostgreSQL query execution, EXPLAIN, and schema inspection tools to MCP-compatible clients like Claude Desktop.31MIT