pgmcp

io.github.pascalallen由 GitHub 账号 pascalallen 发布v1.1.0更新于 Oct 24, 2026

Read-only Postgres ops/DBA diagnostics: slow queries, EXPLAIN, locks, index and table health.

已验证STDIO仅桌面数据库安全与监控

概览

AI 生成的概览

只读的 PostgreSQL 运维/DBA MCP 服务器,让助手诊断慢查询、执行计划、锁、索引与表健康、连接和复制状态。

可以做什么
  • 按耗时、调用次数等排序慢语句,并解释某条语句为何慢,给出计划树与 plan_hash
  • 检查索引与表健康:从未使用、重复、无效或膨胀的索引,死元组比例、vacuum 与 analyze 记录
  • 诊断实时问题:锁等待图与死锁、按状态和等待事件分组的后端、备库延迟与占用 WAL 的复制槽
  • 对照内存、autovacuum、WAL 与连接数经验值检查服务器配置,给出 ok/review/warn 结论
  • 执行一条受限的只读 SELECT、EXPLAIN 或 SHOW(支持绑定参数),可整体禁用或限定到指定 schema
  • 读取 overview 与 settings 资源,并使用引导式慢查询诊断提示词
适用场景
适合让助手协助排查 PostgreSQL 故障或做日常调优:定位慢语句、阅读执行计划、发现阻塞会话、检查 autovacuum 或索引膨胀、查看复制延迟,同时不授予写权限。
运行要求
以本地进程运行(二进制、Claude Desktop 的 .mcpb 包、Go 安装或容器镜像),或部署为 HTTP 服务。需要 PostgreSQL 13 及以上版本的连接串,放在 PGMCP_DATABASE_URL 中,最好使用专用只读角色。HTTP 模式可选静态 API 密钥或 JWT 配置,并应置于负责 TLS 的反向代理之后。
安装前请注意
连接串是机密,其权限取决于所用角色;应创建专用只读角色,而不要复用高权限账号。自由 SQL 的 query 工具接受调用方提供的语句,explain 在 analyze=true 时会实际执行语句;不需要时应禁用或限制 schema。schema 允许列表只是护栏而非边界,视图和函数仍可能读取列表之外的数据。HTTP 模式在非回环地址上未启用认证时会拒绝启动。

安装

在 SourceWeft 中

  1. 打开 控制台中的 pgmcp,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

pgmcp

[Go Reference] [GitHub go.mod Go version] [Go Report Card] [GitHub Workflow Status (with branch)] [GitHub] [GitHub code size in bytes]

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:

bash
go install github.com/pascalallen/pgmcp/cmd/pgmcp@latest

Or run the released image, which is distroless, non-root and multi-arch:

bash
docker run --rm -i -e PGMCP_DATABASE_URL='postgres://…' ghcr.io/pascalallen/pgmcp

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

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:

bash
claude mcp add pgmcp --transport stdio \  --env PGMCP_DATABASE_URL='postgres://pgmcp:…@db.internal:5432/app?sslmode=require' \  -- pgmcp

Claude Desktop, stdio — install the .mcpb bundle from Releases (see Installation), or write the same thing into claude_desktop_config.json by hand:

json
{  "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.

bash
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:8080
bash
claude 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

ToolThe question it answers
top_queriesWhich statements are slow or expensive server-wide? Ranks pg_stat_statements by total time, mean time, calls, rows or blocks read.
explainWhy is this statement slow? Plan tree, the nodes burning the most self time, plan warnings, and a stable plan_hash to diff against a later run.
index_healthWhich indexes can I drop, and which are missing their job? Never-scanned, duplicate, invalid and bloated indexes.
table_healthWhere is autovacuum falling behind? Dead-tuple ratio, last vacuum/analyze, sequential versus index scans and estimated bloat, per table.
lock_waitsWhy is this query hanging? The current lock wait graph — who is blocked, who blocks them, and any cycle that amounts to a deadlock.
connectionsWhat is the server doing right now, and how close is it to max_connections? Backends grouped by state, wait event, application, user or database, including idle-in-transaction sessions.
replicationHow 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.
config_checkIs this server tuned sanely? pg_settings against memory, autovacuum, WAL and connection heuristics, with an ok/review/warn verdict and a note per setting.
queryEverything the other eight do not cover. One read-only SELECT/EXPLAIN/SHOW in a READ ONLY transaction, bounded by a row cap and a statement timeout, with $1..$n bind parameters.

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

ResourceContents
pgmcp://overviewThe server snapshot to start from: version, uptime, recovery state, installed extensions, per-database sizes, cache hit ratio, and connections against max_connections. Cacheable for 30s.
pgmcp://settingsThe raw pg_settings rows. Cacheable for 5m.
PromptArgumentsPurpose
diagnose_slow_querysql (required)A four-step investigation: explain the statement, check index_health/table_health on every schema in the plan's hot nodes, look for it in top_queries, then summarize root cause, evidence and a recommended index or rewrite — written out as text only, never run.

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.

FlagEnvDefaultMeaning
--database-urlPGMCP_DATABASE_URL— (required)Postgres connection string
--transportPGMCP_TRANSPORTstdiostdio or http
--listenPGMCP_LISTEN127.0.0.1:8080HTTP listen address
--resource-urlPGMCP_RESOURCE_URL—Public origin this server is reachable at, for OAuth resource metadata
--auth-modePGMCP_AUTH_MODEnonenone, static or jwt (HTTP only)
--api-keysPGMCP_API_KEYS—Comma-separated static API keys, required for static
--jwks-urlPGMCP_JWKS_URL—JWK set URL, required for jwt
--jwt-issuerPGMCP_JWT_ISSUER—Required iss claim, required for jwt
--jwt-audiencePGMCP_JWT_AUDIENCE—Required aud claim, required for jwt
--auth-serversPGMCP_AUTH_SERVERS—Comma-separated OAuth authorization servers to advertise via RFC 9728
--disable-queryPGMCP_DISABLE_QUERYfalseDrop the ad hoc query tool entirely
--query-schemasPGMCP_QUERY_SCHEMAS—Comma-separated schemas the query and explain tools may read; unset disables the allowlist
--max-connsPGMCP_MAX_CONNS4Maximum Postgres connections
--call-timeoutPGMCP_CALL_TIMEOUT60sPer-tool-call timeout
--rate-limitPGMCP_RATE_LIMIT60Tool calls per principal per minute (HTTP only)
--max-output-bytesPGMCP_MAX_OUTPUT_BYTES1048576Cap on a tool call's structured content
--log-levelPGMCP_LOG_LEVELinfodebug, info, warn or error
--log-formatPGMCP_LOG_FORMATtexttext or json
--insecure-no-authPGMCP_INSECURE_NO_AUTHfalseAllow auth-mode=none on a non-loopback listen address
--version——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_monitor plus SELECT, and deliberately not pg_signal_backend); BEGIN READ ONLY with SET LOCAL statement_timeout and lock_timeout = '2s' around every statement the adapter runs, always rolled back; and a parser-level guard, because a read-only transaction alone does not stop pg_terminate_backend, pg_read_file, pg_sleep or setval.
  • The SQL guard is allow-list first. One top-level statement, and it must be a SELECT, EXPLAIN or SHOW; no nested write statement anywhere in the tree; no FOR UPDATE/FOR SHARE locking clause; no SELECT 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-schemas matches the schemas qualifying table references in the parsed statement, case-insensitively, and it bounds both tools that carry caller-supplied SQL — query and explain, so explain with analyze=true cannot execute against a schema you excluded. A view, a set-returning function, or a SECURITY DEFINER function 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 required iss, aud and exp, 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 query tool, 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:

bash
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:

bash
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=alldocker 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:

bash
go test -covermode=count -coverprofile=coverage.out ./...go tool cover -html=coverage.out

Drive a running server through the official MCP conformance suite, or smoke it with the Inspector:

bash
npx -y @modelcontextprotocol/conformance server --url http://127.0.0.1:8080/mcp \  --expected-failures .github/conformance-expected-failures.yamlnpx @modelcontextprotocol/inspector --cli http://127.0.0.1:8080/mcp --transport http --method tools/list

Contributing

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

MIT

来源:README.md,提交 09953f9

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v1.1.0最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分