mcp-postgres
Provides tools for interacting with PostgreSQL databases: exploring schemas, tables, indexes, and roles; running scoped reads and SELECT queries; explaining query plans; inspecting active queries and database statistics; and, when enabled, performing governed inserts, updates, deletes, index creation, table drops, and other admin operations with safety controls and approval gates.
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., "@mcp-postgres show me the users table schema and its indexes"
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.
mcp-postgres
A Model Context Protocol server for PostgreSQL. It lets an MCP-capable client (Claude Desktop, Claude Code, Cursor, …) explore schemas, query data, read query plans, and diagnose a live database — and, when you allow it, make governed changes — with behaviour controlled entirely by flags.
Safe by default: it starts read-only, runs every read inside a READ ONLY transaction that is always rolled back, refuses superuser connections, can be scoped to an allowlist of schemas, protects system schemas from mutation, caps how many rows any change can touch, and gates destructive operations behind an explicit opt-in plus a human approval bound to the exact action.
Operating PostgreSQL on Kubernetes with the Percona operator (scaling, PgBouncer, backups, PITR)? That is
mcp-percona-pg. This server talks SQL to any PostgreSQL 13+ database.
Features
Explore — schemas, tables/views with sizes and row estimates, full table descriptions (columns, constraints, indexes with scan counts).
Query — structured
select_rows(no SQL needed, schema-scoped) and free-formrun_queryfor oneSELECT/WITH/VALUES/TABLE/SHOWstatement with$1parameters.Tune —
explain_query(JSON plans;EXPLAIN ANALYZEfor reads in a rolled-back transaction), top statements frompg_stat_statements,create_index(CONCURRENTLY),analyze_table.Diagnose — active sessions and waits, connection/cache/deadlock stats, roles and extensions; cancel a runaway query.
Change — parameterized
insert_rows/update_rows, and in admin modedelete_rows,drop_table,terminate_backend, and (opt-in)execute_sql.Access modes —
read-only→read-write→admin, layered so a mode never exposes tools above its level.
Related MCP server: PostgreSQL MCP Server
Security model
Concern | Flag | Default | Effect |
What can the server do? |
|
|
|
Read path | (always on) | — | Reads run in |
Superuser connections |
|
| A superuser bypasses every privilege check, so connecting as one is refused. Use a least-privilege role. |
Which schemas are in scope? |
| (all) | When set, other schemas are refused — and free-form SQL ( |
Protect system schemas |
|
|
|
Protect specific schemas |
| (none) | Additional read-only-forever schemas. |
Blast radius of a change |
|
| An insert/update/delete that would touch more rows rolls back. |
Result size |
|
| Rows returned to the model per call; the database stops early. |
Secrets in results |
|
| Values in |
Can it delete? |
|
|
|
Raw SQL |
|
|
|
Statement timeout |
|
| Applied to every statement the server runs. |
Preview without touching the database |
|
| Write/admin tools validate + log intent, then return. |
Audit trail |
|
| Emits a JSON line to stderr per guarded operation. |
Interactive confirmation | (automatic) | — | Destructive & high-impact actions prompt the human to approve via MCP elicitation. The prompt shows the tool, the exact arguments and a fingerprint; the target's version (table identity, the exact set of matching rows, the backend's current query) is pinned across the prompt and the action is refused if it changed; |
Require a human |
|
| When |
AI risk guard |
|
| Optional laya-guard check on every mutating call ( |
Tools
Read (read-only+): get_server_info, list_schemas, list_tables, describe_table, select_rows, run_query, explain_query, list_active_queries, get_database_stats, get_top_queries, list_roles, list_extensions
Write (read-write+): insert_rows, update_rows, create_index, analyze_table, cancel_query
Admin (admin): delete_rows, drop_table, terminate_backend (need POSTGRES_ALLOW_DELETE), execute_sql (only registered with POSTGRES_ALLOW_RAW_SQL)
Recommended database role
The flags are defence in depth; the database's own privileges are the primary control. Give the server its own login role with only what it needs:
CREATE ROLE mcp_readonly LOGIN PASSWORD '…' CONNECTION LIMIT 5;
GRANT CONNECT ON DATABASE app TO mcp_readonly;
GRANT USAGE ON SCHEMA public TO mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO mcp_readonly;
GRANT pg_read_all_stats TO mcp_readonly; -- optional: full query text in list_active_queries / get_top_queriesGrant INSERT/UPDATE/DELETE only on the tables a write task needs, and only for as long as it needs them.
Quickstart — add to your agent
Published on npm as @dockndevai/mcp-postgres. No clone or build needed — your MCP client runs it on demand with npx. Start in read-only mode; see .env.example for every variable and docs/CLIENTS.md for the full per-client guide.
Claude Code (CLI)
claude mcp add postgres -e POSTGRES_URL="postgresql://mcp_readonly:PASSWORD@localhost:5432/app" -e POSTGRES_MODE="read-only" -- npx -y @dockndevai/mcp-postgresClaude Desktop · Cursor · Windsurf — same block in claude_desktop_config.json, .cursor/mcp.json, or ~/.codeium/windsurf/mcp_config.json:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@dockndevai/mcp-postgres"
],
"env": {
"POSTGRES_URL": "postgresql://mcp_readonly:PASSWORD@localhost:5432/app",
"POSTGRES_MODE": "read-only"
}
}
}
}OpenAI Codex CLI — in ~/.codex/config.toml:
[mcp_servers.postgres]
command = "npx"
args = ["-y", "@dockndevai/mcp-postgres"]
env = { POSTGRES_URL = "postgresql://mcp_readonly:PASSWORD@localhost:5432/app", POSTGRES_MODE = "read-only" }VS Code (GitHub Copilot, Agent mode) — in .vscode/mcp.json:
{
"servers": {
"postgres": {
"type": "stdio",
"command": "npx",
"args": [
"-y",
"@dockndevai/mcp-postgres"
],
"env": {
"POSTGRES_URL": "postgresql://mcp_readonly:PASSWORD@localhost:5432/app",
"POSTGRES_MODE": "read-only"
}
}
}
}Example prompts
"Which tables in
publicare the largest, and which of their indexes are never scanned?""Why is this query slow? Explain it and suggest an index."
"What is running right now, and is anything waiting on a lock?"
"Mark order 1042 as refunded." (needs
read-write)
Run from source (development)
Prefer the published package above. To run from a clone:
npm install
npm run build
node dist/index.js # with the environment variables setDevelop
npm run dev
npm test
npm run typecheckIntegration tests run against a real database when POSTGRES_TEST_ADMIN_URL points at a disposable superuser connection (they create and drop the mcp_it schema and role):
POSTGRES_TEST_ADMIN_URL=postgresql://postgres:pw@127.0.0.1:5432/postgres npm testPublishing
This server ships a server.json for the official MCP registry and an mcpName for npm ownership validation. See PUBLISHING.md for publishing to npm and listing on the MCP registry, Smithery, Glama, Cursor, and PulseMCP.
License
MIT
Available Tools
12 toolsdescribe_tableDescribe tableCRead-onlyIdempotent
Columns (type, nullability, default), constraints, indexes (with scan counts), size, and estimated rows.
Inputs: table (required), schema (required).
explain_queryExplain query planARead-onlyIdempotent
Show the planner's JSON plan for one statement (SELECT/WITH/VALUES/TABLE, or INSERT/UPDATE/DELETE/MERGE — not executed). analyze: true executes read statements inside a rolled-back READ ONLY transaction for real timings. Refused while POSTGRES_SCHEMA_ALLOWLIST is set.
Inputs: sql (required), params, analyze.
get_database_statsDatabase statsBRead-onlyIdempotent
Connections by state, commits/rollbacks, deadlocks, temp usage, cache hit ratio, and key memory settings.
Inputs: no named parameters.
get_server_infoServer infoARead-onlyIdempotent
PostgreSQL version, current database and role, database size, uptime, and whether it is a replica.
Inputs: no named parameters.
get_top_queriesTop queriesARead-onlyIdempotent
Most expensive statements from pg_stat_statements (requires the extension), with inline secrets masked.
Inputs: limit, orderBy.
list_active_queriesActive queriesBRead-onlyIdempotent
Sessions from pg_stat_activity: role, state, wait event, transaction/query age, and query text (inline secrets masked).
Inputs: includeIdle.
list_extensionsList extensionsBRead-onlyIdempotent
Installed extensions with their version, schema, and the newest available version.
Inputs: no named parameters.
list_rolesList rolesARead-onlyIdempotent
Roles with their attributes (superuser, login, replication, bypass RLS …) and memberships. Never returns passwords.
Inputs: no named parameters.
list_schemasList schemasARead-onlyIdempotent
List schemas with owner and relation count (filtered to POSTGRES_SCHEMA_ALLOWLIST when set).
Inputs: no named parameters.
list_tablesList tablesARead-onlyIdempotent
List tables, views, and materialized views with estimated row counts and on-disk size.
Inputs: schema, includeSystem.
run_queryRun read-only queryARead-onlyIdempotent
Run one SELECT / WITH / VALUES / TABLE / SHOW statement inside a READ ONLY transaction that is always rolled back. Use $1, $2 … placeholders with params for values. Results are capped at POSTGRES_MAX_ROWS. Refused while POSTGRES_SCHEMA_ALLOWLIST is set (free-form SQL can reach any schema) — use select_rows then.
Inputs: sql (required), params.
select_rowsSelect rowsARead-onlyIdempotent
Read rows from one table with equality filters — no SQL needed, and held to the schema allowlist. Results are capped at POSTGRES_MAX_ROWS; secret-like columns are redacted.
Inputs: table (required), schema (required), limit, where, +2 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 12 tools
Most tools target clearly distinct subjects (table structure, schemas, sessions, roles, extensions, planner output). The only real overlaps are select_rows vs run_query and get_server_info vs get_database_stats, but the descriptions explicitly spell out the boundary (allowlist-safe row reads vs free-form read-only SQL) well enough that an agent can choose correctly.
Every tool follows a predictable verb_noun snake_case pattern (describe_table, list_schemas, get_server_info, select_rows, run_query, explain_query). Verbs are used consistently by semantic class: list_* for enumerations, get_* for aggregate snapshots, describe_* for structure.
Twelve tools sit in the sweet spot for a database inspection server, with no filler — introspection, data access, planning, and performance/ops views each contribute distinct capability. Nothing obviously redundant or missing at this granularity.
The read-only diagnostic lifecycle is well covered: schema discovery, structural detail, row sampling, ad-hoc querying, plan analysis, live/aggregated query stats, roles, and extensions. Minor gaps remain — no way to enumerate functions, triggers, sequences, or view definitions, and no object-name search — but agents can fall back to run_query/describe_table for most of these.
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.67 npmApache 2.0
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to interact with PostgreSQL databases through schema intelligence, query execution, and DBA tooling including index analysis and health monitoring. Features configurable access levels and audit logging for secure database operations.MIT
- AlicenseAqualityDmaintenanceEnables AI agents to analyze, optimize, and safely interact with PostgreSQL databases, including health checks, index recommendations, query planning, and SQL execution with read-only and production protection modes.15MIT