PostgreSQL MCP Server

v0.14.3
io.github.YawLabs/postgres-mcp Checked 2 hours ago Published 1 day ago

PostgreSQL MCP server - query, schema introspection, explain, and health checks for AI assistants

These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.

pg_readonly Run read-only SQL

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 w…

ParameterTypeDescription
sql *stringThe SQL statement to execute. Hard cap of 1 MB.
paramsarrayPositional parameters referenced as $1, $2, ... in the SQL.

pg_query Run SQL query

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 check…

ParameterTypeDescription
sql *stringThe SQL statement to execute. Hard cap of 1 MB.
paramsarrayPositional parameters referenced as $1, $2, ... in the SQL.

pg_list_schemas List schemas

List non-system schemas in the database. Excludes `pg_catalog`, `information_schema`, and other `pg_*` internals.

pg_list_tables List tables in a schema

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.

ParameterTypeDescription
includeViewsbooleanIf true, include views and materialized views.
limitintegerMax rows to return (default 500, max 10000).
offsetintegerRows to skip for pagination (default 0).
schemastringSchema name (defaults to 'public').

pg_describe_table Describe table

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 (`genera…

ParameterTypeDescription
table *stringTable name.
schemastringSchema name (defaults to 'public').

pg_list_views List views with definitions

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.

ParameterTypeDescription
includeMaterializedbooleanIf true, include materialized views.
schemastringSchema name (defaults to 'public').

pg_list_functions List functions and procedures

List functions, procedures, and aggregates in a schema. Returns name, arguments, return type, kind (function/procedure/aggregate/window), and implementation language.

ParameterTypeDescription
schemastringSchema name (defaults to 'public').

pg_list_extensions List installed extensions

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.

pg_search_columns Search columns by name

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'.

ParameterTypeDescription
pattern *stringLIKE pattern. Use '%' for wildcard: 'user_id', '%email%', 'created_%'.
limitintegerMax rows to return (default 100).
schemastringLimit to this schema. If omitted, searches all user schemas.

pg_explain Explain query plan

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 outs…

ParameterTypeDescription
sql *stringThe SQL statement to explain. Do NOT prefix with EXPLAIN.
analyzebooleanRun EXPLAIN ANALYZE (actually executes the query).
buffersbooleanReport buffer hits/reads/dirtied. Defaults to TRUE when `analyze` is true (PostgreSQL 18 does the same); pass false to suppress. Requesting it without `analyze` requires PostgreSQL 13+.
costsbooleanInclude estimated cost/rows/width. Set false for a terser plan.
formatstringOutput format.
generic_planbooleanPlan the statement with UNKNOWN values for its $1/$2 placeholders - the plan a prepared statement would get. Cannot be combined with `analyze` or `params` (PostgreSQL 16+).
hypothetical_indexesarrayList of indexes the planner should pretend exist for this EXPLAIN. Requires the HypoPG extension. Indexes are session-scoped and reset at the end of the call. Plain EXPLAIN only: rejected together wit…
memorybooleanReport memory used by the planner (PostgreSQL 17+). Works with or without `analyze`, since planning happens either way.
paramsarrayPositional parameters referenced as $1, $2, ... in the SQL.
serializestringCharge the cost of serializing result rows (network-bound queries hide it otherwise). Requires `analyze` (PostgreSQL 17+).
settingsbooleanReport planner GUCs set away from their defaults - explains a weird plan (PostgreSQL 12+).
timingbooleanInclude per-node actual timing. Setting it to false REQUIRES `analyze: true` (it is rejected otherwise, not silently ignored); false lowers measurement overhead.
verbosebooleanInclude output columns, schema-qualified names, and triggers.
walbooleanReport WAL generated by the statement. Requires `analyze` (PostgreSQL 13+).

pg_index_advisor Recommend indexes for a workload

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 tok…

ParameterTypeDescription
limitintegerHow many statements to pull from pg_stat_statements. Ignored when `statements` is given.
max_candidatesintegerCap on candidate indexes considered. Candidates are ranked by table sequential-scan count first.
max_explainsintegerCap on EXPLAIN round trips spent searching (baseline plans are not counted). The search stops when the next candidate would exceed it and reports `budget_exhausted: true`.
max_index_columnsintegerWidest candidate index to consider. Every narrower prefix is considered too.
max_recommendationsintegerStop after this many accepted indexes, even if more would still help.
min_improvementnumberFraction of total weighted workload cost an index must remove to be accepted (0.1 = 10%). Relative rather than absolute so it means the same thing on a small and a large database.
schemastringOnly recommend indexes on tables in this schema. Candidates elsewhere are dropped.
statementsarrayThe workload to optimize. When omitted, the top `limit` statements from pg_stat_statements are used instead (and weighted by their call counts).

pg_health Database health snapshot

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: `total` for the CURRENT database, broken down into `active` / `idle` / `idle_in_transaction` / `idle_in_transaction_aborted` / `other` (starting, fastpath function call, disabled) / `state_unavailable` -- those six sum to `total`. `idle_in_transaction_aborted` is called out separately…

ParameterTypeDescription
activeQueryLimitintegerMax active queries to return (default 10, max 100).

pg_top_queries Top queries by execution time

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 `$1`, `$2`, ...), 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-…

ParameterTypeDescription
limitintegerNumber of rows to return (default 20).
orderBystringRanking: total_time (cumulative impact), mean_time (worst per-call), or calls (hottest).

pg_seq_scan_tables Find tables with heavy sequential scans

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…

ParameterTypeDescription
limitintegerMax rows to return (default 20).
minSizeintegerMinimum live tuple count to include (default 1000, filters out tiny/empty tables).
schemastringLimit to one schema. If omitted, all user schemas are included.

pg_unused_indexes Find unused indexes

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_rese…

ParameterTypeDescription
limitintegerMax rows to return (default 50).
maxScansintegerInclude indexes with scan count <= this (default 10). Use 0 for 'never scanned'.
schemastringLimit to one schema. If omitted, all user schemas are included.

pg_io_stats I/O statistics and in-flight async I/O

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. Counters `reads` / `writes` / `extends` / `writebacks` / `hits` / `evictions` / `reuses` / `fsyncs` are bigints returned as decima…

ParameterTypeDescription
includeZeroRowsbooleanIf true, return every (backend_type, io_object, io_context) row including the ones with no recorded activity. Default false -- the view is mostly zeros on a quiet system.
limitintegerMax rows per section (default 200). pg_stat_io has well under 200 combinations, so this effectively bounds the in-flight list on a busy PG18 server.

pg_inspect_locks Inspect blocking locks

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 d…

ParameterTypeDescription
limitintegerMax blocked/blocker pairs (default 50).

pg_list_roles List roles

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.

ParameterTypeDescription
includeSystembooleanIf true, include built-in `pg_*` roles (pg_read_all_data, pg_monitor, etc.).

pg_table_privileges Show table privileges

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 -- membe…

ParameterTypeDescription
schemastringSchema name (defaults to 'public').
tablestringTable name. Omit to list privileges for all tables in the schema.

pg_kill Cancel or terminate a backend

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 ta…

ParameterTypeDescription
pid *integerBackend PID to signal.
modestring`cancel` aborts the current query; `terminate` closes the connection entirely.

pg_replication_status Replication status

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.

pg_advisor Database advisor (DBA lints)

Rolled-up DBA lint pass. One call returns four categories of findings: - sequence_exhaustion: SERIAL / BIGSERIAL / IDENTITY sequences whose `last_value` is above `seqExhaustionThreshold` of `limit_value`. The classic incident class. `limit_value` is the bound the sequence is heading for -- `max_value` when ascending, `min_value` when descending -- narrowed to the owning column's type when the sequence is OWNED BY a smallint or integer column (a pre-PG10 SERIAL feeds an int4 column from a bigint sequence, which overflows the column long before the sequence); `limited_by` says which one won. Seq…

ParameterTypeDescription
limitintegerMax rows per category (default 50).
rlsSchemasarraySchemas where RLS-missing should be flagged. Defaults to ['public'].
seqExhaustionThresholdnumberMinimum used-fraction (last_value / limit_value) to flag a sequence (default 0.5 = 50%).
wraparoundThresholdnumberMinimum used-fraction to flag a database or table for wraparound risk (default 0.5 = 50%). Applied to BOTH ratios -- age(frozenxid) / autovacuum_freeze_max_age and mxid_age(minmxid) / autovacuum_multi…

pg_table_bloat Estimate table bloat

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…

ParameterTypeDescription
limitintegerMax rows to return (default 50).
methodstringBloat measurement method. 'estimate' (default) uses pg_stat_user_tables (fast, no extensions). 'approx' uses pgstattuple_approx() (fast sampling, more accurate). 'exact' uses pgstattuple() (full scan,…
minDeadRationumberMinimum dead-tuple fraction to include - dead / (live + dead). Default 0.1 = 10%.
schemastringLimit to one schema. If omitted, all user schemas are included.