pgmcp
Provides read-only PostgreSQL operations and DBA diagnostics, including tools for analyzing slow queries, explaining plans, index health, table bloat, lock waits, connections, replication lag, and configuration checks.
Click on "Install 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., "@pgmcpShow me the current lock wait graph"
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.
pgmcp
pgmcp is a read-only PostgreSQL ops/DBA server for the Model Context Protocol, built on the official modelcontextprotocol/go-sdk. It answers the questions a DBA asks during an incident — which statements are slow, why this plan is slow, which indexes are dead weight, which tables autovacuum has fallen behind on, who is blocking whom, how far the standby is lagging — and it is read-only by construction rather than by convention: a dedicated database role that holds no write privilege, a BEGIN READ ONLY transaction with a statement timeout around every single statement, and a SQL parser guard that rejects anything that is not one SELECT/EXPLAIN/SHOW and every function that could mutate state from inside a read-only transaction. Tested against PostgreSQL 16; requires 13 or later.
Installation
Claude Desktop, one click: download pgmcp_<version>.mcpb from Releases and open it. Claude Desktop asks for a Postgres connection string, keeps it in the OS keychain, and launches the bundled binary itself — nothing on PATH, no config file to edit. One bundle covers macOS (universal) and Windows (x64).
Otherwise download a binary for your platform from Releases — darwin, linux and windows, amd64 and arm64, with checksums.
Or build from source with the Go CLI tool go:
go install github.com/pascalallen/pgmcp/cmd/pgmcp@latestOr run the released image, which is distroless, non-root and multi-arch:
docker run --rm -i -e PGMCP_DATABASE_URL='postgres://…' ghcr.io/pascalallen/pgmcppgmcp is listed in the MCP Registry as io.github.pascalallen/pgmcp.
Before you point it at anything, create the read-only role — see Database role. It is the layer that still holds if the other two have a bug.
Related MCP server: PostgreSQL MCP Server
Usage
One MCP surface, two transports. Which one you run is configuration, not a different build.
Claude Code, stdio — the client launches the binary and talks over stdin/stdout:
claude mcp add pgmcp --transport stdio \
--env PGMCP_DATABASE_URL='postgres://pgmcp:…@db.internal:5432/app?sslmode=require' \
-- pgmcpClaude Desktop, stdio — install the .mcpb bundle from Releases (see Installation), or write the same thing into claude_desktop_config.json by hand:
{
"mcpServers": {
"pgmcp": {
"command": "pgmcp",
"env": {
"PGMCP_DATABASE_URL": "postgres://pgmcp:…@db.internal:5432/app?sslmode=require"
}
}
}
}HTTP — Streamable HTTP behind a static bearer key, for a shared deployment. pgmcp speaks plain HTTP and never terminates TLS itself; run it on loopback behind a reverse proxy.
PGMCP_DATABASE_URL='postgres://pgmcp:…@db.internal:5432/app?sslmode=require' \
PGMCP_AUTH_MODE=static \
PGMCP_API_KEYS="$(openssl rand -hex 32)" \
pgmcp --transport http --listen 127.0.0.1:8080claude mcp add pgmcp --transport http https://pgmcp.example.com/mcp \
--header "Authorization: Bearer <key>"TLS termination, the proxy settings the streaming transport needs, JWT auth against an identity provider, and wiring pgmcp up as a claude.ai custom connector are all in docs/DEPLOYING.md.
Tools
Tool | The question it answers |
| Which statements are slow or expensive server-wide? Ranks |
| Why is this statement slow? Plan tree, the nodes burning the most self time, plan warnings, and a stable |
| Which indexes can I drop, and which are missing their job? Never-scanned, duplicate, invalid and bloated indexes. |
| Where is autovacuum falling behind? Dead-tuple ratio, last vacuum/analyze, sequential versus index scans and estimated bloat, per table. |
| Why is this query hanging? The current lock wait graph — who is blocked, who blocks them, and any cycle that amounts to a deadlock. |
| What is the server doing right now, and how close is it to |
| How far behind is the standby, and which slot is retaining WAL? Primary/standby role, per-standby lag in bytes and milliseconds, slots and the current WAL rate. |
| Is this server tuned sanely? |
| Everything the other eight do not cover. One read-only |
Every tool is annotated readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false, and returns a typed output schema.
query is the only tool that carries free-form SQL, and it is optional. --disable-query drops it from the catalogue entirely — a deployment that only needs the eight diagnostics tools can run without any ad hoc SQL surface at all. --query-schemas=public,app restricts it to named schemas instead — and bounds explain with it, since analyze=true executes the statement; read what that does and does not stop in docs/SECURITY.md.
Resources & prompt
Resource | Contents |
| The server snapshot to start from: version, uptime, recovery state, installed extensions, per-database sizes, cache hit ratio, and connections against |
| The raw |
Prompt | Arguments | Purpose |
|
| A four-step investigation: |
Configuration
Every setting has a --flag and a PGMCP_<KEY> environment variable. Flags win over the environment, which wins over the default. Configuration errors exit 2 with every offending key named in one message; runtime failures exit 1.
Flag | Env | Default | Meaning |
|
| — (required) | Postgres connection string |
|
|
|
|
|
|
| HTTP listen address |
|
| — | Public origin this server is reachable at, for OAuth resource metadata |
|
|
|
|
|
| — | Comma-separated static API keys, required for |
|
| — | JWK set URL, required for |
|
| — | Required |
|
| — | Required |
|
| — | Comma-separated OAuth authorization servers to advertise via RFC 9728 |
|
|
| Drop the ad hoc |
|
| — | Comma-separated schemas the |
|
|
| Maximum Postgres connections |
|
|
| Per-tool-call timeout |
|
|
| Tool calls per principal per minute (HTTP only) |
|
|
| Cap on a tool call's structured content |
|
|
|
|
|
|
|
|
|
|
| Allow |
| — | — | Print the version and exit |
The auth block applies to the HTTP transport only. Over stdio the operating system decides who the caller is: the parent process that launched the binary, and nobody else.
Security model
Read-only three independent ways. A dedicated role with no write privilege (
pg_monitorplusSELECT, and deliberately notpg_signal_backend);BEGIN READ ONLYwithSET LOCAL statement_timeoutandlock_timeout = '2s'around every statement the adapter runs, always rolled back; and a parser-level guard, because a read-only transaction alone does not stoppg_terminate_backend,pg_read_file,pg_sleeporsetval.The SQL guard is allow-list first. One top-level statement, and it must be a
SELECT,EXPLAINorSHOW; no nested write statement anywhere in the tree; noFOR UPDATE/FOR SHARElocking clause; noSELECT INTO; and no call to a denied function — file access, backup and WAL control, replication slots, advisory locks,dblink, sequence mutation, stats resets.The schema allowlist is a guardrail, not a boundary.
--query-schemasmatches the schemas qualifying table references in the parsed statement, case-insensitively, and it bounds both tools that carry caller-supplied SQL —queryandexplain, soexplainwithanalyze=truecannot execute against a schema you excluded. A view, a set-returning function, or aSECURITY DEFINERfunction inside an allowed schema can still read outside it. Database privileges are the boundary; the allowlist just narrows the obvious path.Authenticated, fail-closed, over HTTP. Static keys are compared in constant time against every stored hash without an early exit; JWTs are validated against a JWK set with asymmetric algorithms only (no
alg=none, no HMAC confusion) and a requirediss,audandexp, and the verifier holds no keys until the JWKS arrives, so it starts closed rather than open. RFC 9728 protected resource metadata advertises where to get a token. The server refuses to start on a non-loopback address with auth off.Bounded. Per-principal rate limiting, a per-call timeout, a statement timeout and lock timeout inside the transaction, a row cap on the
querytool, a cap on a result's structured content, and a 1 MiB request body limit.Nothing sensitive is logged. A tool call logs its name, duration, outcome and the caller's user id — never arguments, SQL text, result rows or error text. Parse failures come back as a fixed phrase rather than echoing the statement, and the DSN is redacted from connection errors.
The threat model, the full enumeration of the layers, and the limitations each one does not cover are in docs/SECURITY.md.
Testing
Run the test suite with the race detector and coverage:
go test -race -cover ./...Integration tests need a Postgres database and are skipped when PGMCP_TEST_DSN is unset. To run them against a scratch Postgres with pg_stat_statements preloaded:
docker run -d --rm --name pg -e POSTGRES_PASSWORD=postgres -p 5544:5432 postgres:16 \
-c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all
docker exec pg psql -U postgres -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements"
PGMCP_TEST_DSN="postgres://postgres:postgres@localhost:5544/postgres?sslmode=disable" go test -race -cover ./...Create and view a coverage profile:
go test -covermode=count -coverprofile=coverage.out ./...
go tool cover -html=coverage.outDrive a running server through the official MCP conformance suite, or smoke it with the Inspector:
npx -y @modelcontextprotocol/conformance server --url http://127.0.0.1:8080/mcp \
--expected-failures .github/conformance-expected-failures.yaml
npx @modelcontextprotocol/inspector --cli http://127.0.0.1:8080/mcp --transport http --method tools/listContributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
License
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- -licenseNot gradedqualityAmaintenanceA Model Context Protocol server that provides read-only access to PostgreSQL databases. This server enables LLMs to inspect database schemas and execute read-only queries.66,13689,405MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server providing LLMs read-only access to PostgreSQL databases for inspecting schemas and executing queries.66,13627MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that provides AI assistants with secure, read-only access to PostgreSQL databases while offering comprehensive tools for schema exploration, query validation, and performance optimization.MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server providing read-only access to PostgreSQL databases, enabling LLMs to inspect database schemas and execute read-only SQL queries.66,136MIT
Related MCP Connectors
Comprehensive PostgreSQL documentation and best practices, including ecosystem tools
MCP server for managing Prisma Postgres.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/pascalallen/pgmcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server