PostgreSQL Performance (read-only)
概览
作者提供的说明(英文原文)
Read-only PostgreSQL performance diagnostics: slow queries, EXPLAIN, index advice, locks, functions
PopNx MCP 的三大支柱
这三项永远不会合并成一个分数:意见、测量和人气是不同的东西。
- 用户评价i暂无评价评价功能将在后续阶段与账户功能一起开放
- 我们的基础检查i1 项中通过 1 项依据公开信息检查;尚未扫描代码
- 使用情况i非常新★ –
它能帮你做什么
我们还没有为它写通俗的介绍。下面是我们从注册中心读取到的事实。
- 连接方式: 在你的电脑上运行
- 传输方式: Streamable HTTP
- 分类: 数据库与数据集
- 你需要填写:PGPERF_DB_URL, PGPERF_DB_USER, PGPERF_DB_PASSWORD, MCP_API_KEY
安装
选择你使用的 AI 应用,然后复制设置。
安装之前
- 基础检查:1 项中通过 1 项
- 在你的电脑上运行,拥有你的用户账户的权限(文件、网络、应用)。
- 需要你自己填写:
PGPERF_DB_URL,PGPERF_DB_USER,PGPERF_DB_PASSWORD,MCP_API_KEY
标为机密的值是你账户的钥匙。千万不要分享给别人,也不要粘贴到聊天里。
你需要
- Docker已安装 Docker
你用的是哪个应用?
在上方选择你的应用。我们会记住它,下次按钮会显示“安装到 …”。
打开 Claude Desktop → Settings → Developer → Edit Config,把下面的内容粘贴到 claude_desktop_config.json
{
"mcpServers": {
"pg-perf": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"PGPERF_DB_URL",
"-e",
"PGPERF_DB_USER",
"-e",
"PGPERF_DB_PASSWORD",
"-e",
"MCP_API_KEY",
"ghcr.io/gouranshul/pg-perf-mcp:0.1.0"
],
"env": {
"PGPERF_DB_URL": "your-value",
"PGPERF_DB_USER": "your-value",
"PGPERF_DB_PASSWORD": "your-value",
"MCP_API_KEY": "your-value"
}
}
}
}在终端中运行这条命令
claude mcp add pg-perf --env PGPERF_DB_URL=your-value --env PGPERF_DB_USER=your-value --env PGPERF_DB_PASSWORD=your-value --env MCP_API_KEY=your-value -- docker run -i --rm -e PGPERF_DB_URL -e PGPERF_DB_USER -e PGPERF_DB_PASSWORD -e MCP_API_KEY ghcr.io/gouranshul/pg-perf-mcp:0.1.0运行前请先填写空着的值。
或者自己复制设置
粘贴到项目中的 .cursor/mcp.json,或 ~/.cursor/mcp.json
{
"mcpServers": {
"pg-perf": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"PGPERF_DB_URL",
"-e",
"PGPERF_DB_USER",
"-e",
"PGPERF_DB_PASSWORD",
"-e",
"MCP_API_KEY",
"ghcr.io/gouranshul/pg-perf-mcp:0.1.0"
],
"env": {
"PGPERF_DB_URL": "your-value",
"PGPERF_DB_USER": "your-value",
"PGPERF_DB_PASSWORD": "your-value",
"MCP_API_KEY": "your-value"
}
}
}
}浏览器会先询问是否打开应用,然后应用会显示设置并请你确认。密钥的值会留空,由你自己填写。
或者自己复制设置
粘贴到项目中的 .vscode/mcp.json
{
"servers": {
"pg-perf": {
"type": "stdio",
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"PGPERF_DB_URL",
"-e",
"PGPERF_DB_USER",
"-e",
"PGPERF_DB_PASSWORD",
"-e",
"MCP_API_KEY",
"ghcr.io/gouranshul/pg-perf-mcp:0.1.0"
],
"env": {
"PGPERF_DB_URL": "your-value",
"PGPERF_DB_USER": "your-value",
"PGPERF_DB_PASSWORD": "your-value",
"MCP_API_KEY": "your-value"
}
}
}
}浏览器会先询问是否打开应用,然后应用会显示设置并请你确认。密钥的值会留空,由你自己填写。
这个服务器在你的电脑上运行,而 ChatGPT 只能连接互联网上的服务器。请选择其他应用。
你的选择通过 Cookie 保存在这台设备上,无需账户。
需要你填写的值
- JDBC URL of the database to diagnose. From inside the container, use host.docker.internal for a database on your machine, e.g. jdbc:postgresql://host.docker.internal:5432/mydb
- A read-only role with pg_read_all_stats and pg_monitor (see docker/init.sql)
- Password of that role
- Bearer token clients must send, at least 16 characters (32+ random recommended)
这些设置是根据作者在注册中心的条目生成的。如果 README 的写法不同,请以 README 为准。
它能做什么
它在你的电脑上运行;安装后,工具列表会显示在你的 AI 应用中。
基础检查i
我们检查的是任何人都能看到的信息;我们没有阅读代码。不适用的检查项不计入总数。 · 检查于 2026年11月9日
- ✓ 通过
作者与仓库一致
注册名称已通过 GitHub 账户 gouranshul 验证,该账户拥有此仓库
- … 尚未检查
仍在维护
我们还没有从 GitHub 读取这个仓库
- … 尚未检查
有许可证
我们还没有从 GitHub 读取这个仓库
- – 不适用
端点有响应
它在你的电脑上运行,没有互联网端点
- – 不适用
使用 OAuth 登录
在你的电脑上运行,改用本地设置
- … 尚未检查
工具描述中没有隐藏指令
它在你的电脑上运行;我们只能读取互联网端点的工具列表
与“数据库与数据集”中的其他服务器比较i
- 星标数多于此分类中其他 1153 个服务器的 0%
- 发布到注册中心的时间比此分类中其他 1153 个服务器的 61% 更新
- 基础检查结果等于或优于此分类中其他 1153 个服务器的 100%
与注册中心里这个分类中所有活跃的服务器比较。只有当发布者拥有该仓库时,星标数才计入。
常见问题
PostgreSQL Performance (read-only) 安全吗?
它在 1 项适用的基础检查中通过了 1 项。我们没有阅读代码。在添加密钥或令牌之前,请先看看这个服务器要求哪些权限,并使用只具备所需权限的密钥。
它需要哪些密钥或代码?
你需要填写:PGPERF_DB_URL, PGPERF_DB_USER, PGPERF_DB_PASSWORD, MCP_API_KEY
它在我的电脑上运行还是在云端?
它在你的电脑上运行。你的 AI 应用会在需要时启动它,数据不会经过作者的服务器(除非它自己调用在线服务)。
它还在维护吗?
GitHub 仓库最后更新于–,最新版本(0.1.0)于30天前进入注册中心。
哪些应用可以使用它?
支持 MCP 的应用,例如 Claude Desktop、Claude Code、Cursor 和 VS Code。你的电脑上还需要有 Docker。
有什么可以替代它?
同一分类中有:Supabase, MongoDB MCP Server, Elasticsearch MCP Server
替代选择
同一分类中其他作者的服务器,按星标数排序。
如何看卡片:↓ 每周下载量i★ GitHub 星标i三大支柱:评价 · 检查 · 使用情况i更新 = 最新版本发布到注册中心的时间i
作者的 README
打开 README
按原文从作者的仓库复制。PopNx MCP 没有审查或背书其内容。HTML、图片和脚本已被移除。链接会离开本站。
pg-perf-mcp
An MCP server that lets AI assistants diagnose PostgreSQL performance problems safely: slow queries, EXPLAIN plans, index suggestions, table health and lock contention. It is read-only by design.
*A real Claude Code session against the demo shop, sped up. First it finds which database functions are slow and why. Then it explains a slow catalog query and estimates the fix with a hypothetical index. Asked to create the index, it says it can't: every tool is read-only.*
Why
When a page is slow, developers paste a query into a chat and ask "why is this slow?". The assistant then guesses, because it cannot see the plan, the table sizes, the existing indexes or which queries actually dominate the load.
pg-perf-mcp gives the assistant real numbers from `pg_stat_statements`, `EXPLAIN` and the catalogs, through a narrow, audited, read-only interface. It cannot change data, cannot run DDL, and never creates the indexes it recommends.
Demo
A condensed, illustrative session against the demo shop (docker compose up, then ./demo/workload.sh). Exact numbers vary from run to run:
You: The shop database feels slow. What's going on?
Claude: [top_slow_queries orderBy=total_time] The top statement by total time is SELECT id, status, total, created_at FROM shop.orders WHERE customer_id = $1 ORDER BY created_at DESC (thousands of calls, the largest share of total execution time).
[explain_query sql="... WHERE customer_id = 42 ORDER BY created_at DESC"] HIGH SEQ_SCAN_ON_LARGE_TABLE Seq Scan on shop.orders reads all ~1.0M rows of shop.orders to apply filter (customer_id = 42); only a handful match.
[suggest_indexes] CREATE INDEX CONCURRENTLY idx_orders_customer_id ON shop.orders (customer_id); hypopg: the planner would use it; estimated cost drops by well over 90%. Not executed. Review it and run it yourself, ideally off-peak.
[table_health table=shop.orders] Autovacuum is disabled on shop.orders and ~20% of rows are dead. Re-enable autovacuum and VACUUM.
Prioritized actions: 1) add the index above (orders.customer_id is a foreign key with no index),
- re-enable autovacuum on shop.orders, 3) ...
Architecture
flowchart LR
A["AI assistant (Claude Code, Claude Desktop, ...)"] -- "MCP over streamable HTTP Authorization: Bearer key" --> F["API key filter (constant-time)"] F --> M["MCP tools / resources / prompt Spring AI 2.0 annotations"] M --> R["ToolRunner audit log · metrics · safe errors"] R --> G["SqlGuard PG lexer + JSqlParser"] G --> E["ReadOnlyExecutor READ ONLY tx · always rollback statement/lock timeout · row cap"] R --> AN["analysis PlanAnalyzer · IndexAdvisor (pure functions)"] E --> P[("PostgreSQL 18 role mcp_readonly pg_stat_statements · hypopg")]
Tools
| Tool | What it does | Safety notes |
|---|---|---|
top_slow_queries | Most expensive statements from pg_stat_statements: normalized text, calls, total/mean/max ms, rows, cache hit ratio, share of total time. Order by total_time, mean_time, calls or rows. | Fixed SQL; sort column chosen from an enum. Excludes the server's own statements. |
explain_query | Summarized plan: 5 costliest nodes, seq scans on large tables, 10x row misestimates, disk sorts/hash spills, nested loops with many iterations. analyze=true adds real timings. $1 placeholders get a generic plan. | SQL guard first. ANALYZE runs in a read-only transaction that is rolled back and cancelled after the timeout. |
suggest_indexes | CREATE INDEX CONCURRENTLY candidates from filtered seq scans, join keys and ORDER BY ... LIMIT, each with a reason; validated with hypothetical indexes when hypopg is installed. | Never executed. Hypothetical indexes are reset in a savepoint so they cannot leak to other calls. |
unused_indexes | Indexes with idx_scan = 0, largest first, excluding primary key, unique and constraint indexes; includes size, definition and a DROP INDEX CONCURRENTLY to review. | Nothing is dropped. Reports when stats were last reset. |
table_health | Live/dead tuples, dead ratio, last (auto)vacuum/analyze, rows changed since analyze, seq vs index scans, sizes, with plain-language warnings. | Catalog reads only. |
blocking_sessions | Blocked/blocking pairs via pg_blocking_pids, truncated query texts, wait time, lock type/mode/table, blocker state, root blockers. | Never cancels or terminates anything. |
slow_functions | User-defined functions (PL/pgSQL, SQL, ...) ranked by total, self or mean time or calls, from pg_stat_user_functions, with language and volatility. | Catalog reads only. Needs track_functions. |
explain_function | Looks inside the functions a query calls: time per function, every statement executed inside them with calls, time and its own analyzed plan, and findings such as a seq scan inside a function, a function called once per row, or a read-only function left VOLATILE. Includes the function source. | SQL guard first; runs in the same rolled-back read-only transaction as explain_query, so functions that write fail. auto_explain is switched on for that transaction only, with generic plans so no data values appear. |
Resources: pg://schema/overview (tables, row estimates, sizes, indexes) and pg://schema/{table} (columns, indexes with scan counts, foreign keys flagged when unindexed). Prompt: diagnose_slow_database, a guided workflow: slow queries, then explain, suggest indexes, table health, functions, then a prioritized summary.
Why a separate tool for database functions
EXPLAIN shows a function call as one opaque expression, and charges its time to whichever plan node evaluates it. On the demo catalog page (20 products, each calling shop.product_rating), explain_query blames the index scan on products (184 ms self time) and finds nothing else serious. explain_function on the same query, against the full demo data:
shop.product_rating plpgsql 20 calls 99% of execution time
SELECT avg(rating) FROM shop.reviews WHERE product_id = p_product_id 20 calls 175 ms 96% of execution time HIGH FUNCTION_DOMINATES_QUERY shop.product_rating takes 99% of the query's execution time HIGH FUNCTION_CALLED_PER_ROW ran 20 times for one query (9.0 ms per call) HIGH SEQ_SCAN_ON_LARGE_TABLE inside shop.product_rating: Seq Scan on shop.reviews reads all ~250k rows to apply filter (reviews.product_id = $1)
How it works (ADR 0006): the query runs once with auto_explain enabled for that transaction only, so the plan of each nested statement comes back as a notice; per-function time comes from pg_stat_xact_user_functions and per-statement calls from pg_stat_statements, both as before/after differences.
Security model
Five independent layers stand between the assistant and a write (details in ADR 0001):
- SQL guard: exactly one plain
SELECT. It is checked by a PostgreSQL-faithful lexer *and* JSqlParser, and both must agree. Blocks DML/DDL, multiple statements, data-modifying CTEs,SELECT INTO,FOR UPDATE/SHARE,COPY,DO, and dangerous functions (pg_sleep*,*_file,lo_*,dblink*,set_config,pg_terminate_backend,query_to_xml, ...). It fails closed. - Read-only role:
mcp_readonlyhasSELECTpluspg_read_all_stats/pg_monitor, withdefault_transaction_read_only = onandstatement_timeout = 5sset on the role. - Read-only connections: Hikari
readOnly=trueand a read-only session default. - One rolled-back read-only transaction per call:
statement_timeout/lock_timeoutset locally,standard_conforming_stringsforced on, always rolled back. - Row cap: every result is capped (default 200 rows).
Around those layers: a bearer API key (constant-time comparison; only /actuator/health is open), a JSON audit line per call (SQL stored as a SHA-256 hash plus an 80-character preview), error messages with no stack traces or connection details, and metrics mcp.tool.duration and mcp.guard.rejections.
Quickstart
Requirements: Docker. There are two ways to start:
- [Use it on your database](#use-it-on-your-database): pull the published image. No clone or build.
- [Try the demo shop](#try-the-demo-shop): clone the repo and get a seeded database with realistic problems to diagnose.
Either way, finish with connecting your AI client.
Use it on your database
1. Pull the image (public on GHCR, built for amd64 and arm64):
docker pull ghcr.io/gouranshul/pg-perf-mcp:0.1.0
2. Prepare the database (once). Create a read-only role like mcp_readonly (see docker/init.sql) and make sure pg_stat_statements is in shared_preload_libraries. Prefer a replica or staging database: analyze=true and explain_function execute the query. For the function tools, also enable function tracking.
3. Run it. Put the settings in a file so secrets stay out of your shell history:
cat > pg-perf.env <<'EOF'
PGPERF_DB_URL=jdbc:postgresql://host.docker.internal:5432/mydb PGPERF_DB_USER=mcp_readonly PGPERF_DB_PASSWORD= MCP_API_KEY=<32+ random characters> EOF
docker run --rm --env-file pg-perf.env -p 127.0.0.1:8080:8080 ghcr.io/gouranshul/pg-perf-mcp:0.1.0
host.docker.internal reaches a database on your machine (Docker Desktop; on Linux add --add-host=host.docker.internal:host-gateway). The MCP endpoint is now http://localhost:8080/mcp.
4. Connect your AI client: see below.
Try the demo shop
To build and test from source you also need Java 25.
git clone https://github.com/gouranshul/pg-perf-mcp && cd pg-perf-mcp
cp .env.example .env # then replace the placeholder secrets docker compose up --build # Postgres 18 + seeded demo shop (~4.5M rows) + the MCP server on :8080
Generate some slow-query statistics (optional, but makes top_slow_queries interesting):
./demo/workload.sh # 60s of deliberately bad queries via pgbench
./demo/lock-scenario.sh # holds a row lock for 2 minutes so blocking_sessions has something to show ./demo/smoke-test.sh # curl-based end-to-end check of health, auth and two tool calls
Connect from Claude Code
claude mcp add --transport http pg-perf http://localhost:8080/mcp --header "Authorization: Bearer $MCP_API_KEY"
In PowerShell, set the key first, or the header goes out empty and the server answers 401:
$env:MCP_API_KEY = "<your MCP_API_KEY>"
claude mcp add --transport http pg-perf http://localhost:8080/mcp --header "Authorization: Bearer $env:MCP_API_KEY"
Or install it as a Claude Code plugin. Claude Code asks for the endpoint (default http://localhost:8080/mcp) and your MCP_API_KEY, which it keeps in secure storage:
/plugin install pg-perf --marketplace gouranshul/pg-perf-mcp
On Claude Code versions before 2.1.275, add the marketplace first: `/plu
只显示了开头部分;其余内容请在仓库中阅读