pgops

io.github.arzharch由 GitHub 帳號 arzharch 發布v0.1.9更新於 Oct 24, 2026

Safe, audited PostgreSQL operations for AI agents: queries, migrations, EXPLAIN, containers

概覽

AI 產生的概覽

一個本機 MCP 伺服器,讓 AI 助理在受保護、可稽核的前提下檢查、查詢、診斷與遷移 PostgreSQL 資料庫。

可以做什麼
檢查資料庫結構與資料表結構,並讀取結構摘要、健康狀態與近期稽核記錄等資源。執行唯讀查詢、受保護的寫入以及 EXPLAIN 執行計畫,並提供解析後的結論與調校建議。規劃、說明、套用、回復與檢視遷移,附帶鎖定影響與風險分析。透過索引建議與資料庫健康檢查診斷效能。檢視容器環境:拓撲、關聯、日誌與統計,並在啟用核准模式時使用受限的重啟與 exec 工具。
適用情境
適合讓助理回答關於 Postgres 資料庫的問題、診斷慢查詢,或在人工確認與稽核日誌的保護下規劃與執行結構遷移。面向單一工程師與少量資料庫,而非多租戶情境。
執行需求
透過 uvx(Python)或已發佈的容器映像(Docker)作為本機程序執行。需要 PGOPS_DSN 中的 PostgreSQL 連線字串,可選用 PGOPS_READONLY_DSN 中的唯讀角色連線。可選設定包括 PGOPS_READ_ONLY、PGOPS_APPROVAL_MODE、PGOPS_AUDIT_LOG 以及列數與逾時變數。需要能存取資料庫的網路。
安裝前請注意
PGOPS_DSN 與 PGOPS_READONLY_DSN 是授予資料庫存取權的機密,應使用最小權限角色與獨立的唯讀角色。寫入、遷移與回復工具會變更資料與結構,部分刪除操作無法回復。啟用 PGOPS_APPROVAL_MODE 會註冊容器重啟與 exec 工具,而 Docker socket 存取在主機上等同 root 權限。稽核日誌與查詢結果可能包含敏感資料。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 pgops,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

pgops-mcp

Let an AI assistant operate your PostgreSQL database — without letting it wreck anything.

Point Claude, Cursor, or VS Code at a database and ask questions in plain English. Your assistant gets 18 tools for inspecting schemas, running queries, diagnosing slow ones, and planning migrations. What it does not get is a way to quietly destroy your data.

What it actually looks like

Every number below is real output from the demo database in this repo — 1.2M rows, 114 MB.

You: I want to index orders.status

Assistant: (calls migration.plan)

CREATE INDEX "idx_orders_status" ON "orders" (status)  risk=medium   estimate=4000ms   confidence=medium  blocks:  writes yes, reads no  SAFER:   CREATE INDEX CONCURRENTLY "idx_orders_status" ON "orders" (status)

Assistant: A plain index build blocks writes for roughly 4 seconds. CONCURRENTLY is slower overall but keeps writes working. Which do you want?

The tool didn't return a raw plan for the model to interpret — it returned a verdict, a duration estimate with an honest confidence level, and the safer alternative.

query.explain works the same way. Instead of handing back JSON, it says things like:

planner overestimated rows by 5833x (estimated 239,160, actual 40)  -> run ANALYZE; if it persists the columns may be correlated, consider CREATE STATISTICS

And when something is genuinely dangerous

You: clear out the orders table

Assistant: (calls query.write with DELETE FROM orders)

CONFIRMATION_REQUIREDDELETE has no WHERE clause and would affect every row in the table

Where your client supports it, the approval prompt goes to you — not to the assistant. Nothing runs until a human answers, and the refusal is written to the audit log whether or not you approve.

That last part is the point. The assistant cannot approve its own dangerous action, because it is not the one being asked. Where a client can't show a prompt, it degrades to a single-use token bound to that exact statement — never to "allowed".

Why this exists

Most Postgres MCP servers are thin query wrappers: introspect and SELECT. None handle migrations with lock-impact analysis, none diagnose performance from EXPLAIN and pg_stat_statements, and none understand the container the database runs in. Agents operating databases today are doing it blind, and without guardrails.

pgops-mcp is the operations brain: schema intelligence → guarded queries → migration engine → performance diagnosis → environment awareness, with a safety architecture that makes every action classifiable, confirmable, and auditable.

Native AI/ML Extension Support: Because pgops builds on core Postgres catalogs rather than brittle regex parsing, it inherits native support for custom types and extensions like pgvector. Tools like migration.plan and query.explain understand vector types (vector(384)) and hnsw indexes out of the box, with zero configuration.

New here? docs/GETTING_STARTED.md is a 15-minute guided tour that assumes no MCP knowledge.

Tool surface

GroupTools
Schemaschema.inspect
Queriesquery.read, query.write (guarded), query.explain (parsed plan + verdict)
Performanceindex.advise, db.health
Migrationsmigration.plan (dry-run + lock analysis), migration.describe (plain English), migration.apply, migration.rollback, migration.history
Environmentenv.topology, env.correlate, container.logs, container.stats
Gatedcontainer.restart, container.exec

* Not registered at all unless the server runs with --approval-mode, and even then each call needs a confirmation token. container.exec additionally enforces a read-only diagnostic command allowlist — it does not offer a shell. The Docker socket is root-equivalent on the host, so the default is read-only access.

Safety model (the core differentiator)

  • Separate read-only / read-write connection roles; tools bind to the right role
  • Statement classification before execution — unbounded DELETE/UPDATE blocked
  • Destructive actions require explicit confirmation tokens
  • Every executed statement lands in an append-only audit log with timing and verdict
  • Runaway-query cancellation with timeout tiers

MCP surface

PrimitiveWhat's here
Tools17 — schema, query, explain, advise, migrate, environment
Resourcespgops://schema, schema/summary, schema/{table}, health, migrations, audit/recent, config
Promptsdiagnose-slow-query, plan-safe-migration, incident-triage, review-index-health, explain-safety-model
ElicitationDangerous actions ask the user directly, not via the agent; confirmation tokens are the fallback
Samplingmigration.describe turns English into a plan using your model — this server ships no API key
CompletionsTable-name autocomplete for pgops://schema/{table}
Progress / loggingBest-effort notifications during long operations

Remote access & agent tokens

stdio needs no auth — the server is a subprocess your client spawns, with no open port. HTTP does, so it refuses to start without a key:

bash
pgops-mcp keygen                                    # RS256 keypairpgops-mcp issue-token --subject my-agent            # read-only by defaultpgops-mcp issue-token --subject deploy-bot --scope pgops:read --scope pgops:writepgops-mcp scopes                                    # which scope each tool needs
pgops-mcp --transport http --public-key ~/.pgops/keys/pgops_public.pem

The server holds only the public key, so it can verify tokens but never mint them. Scopes (pgops:read / pgops:write / pgops:admin) map to the same danger tiers as the guardrails, and a tool with no scope entry requires admin — deny by default. Binds loopback unless you say otherwise.

Install

pgops-mcp is an MCP server, not a Python library — nothing in it is meant to be imported, and pgops.* carries no API-stability promise. You install it the way you install any MCP server: point your client at it.

Claude Desktop / Cursor / VS Code:

json
{  "mcpServers": {    "pgops": {      "command": "uvx",      "args": ["pgops-mcp"],      "env": { "PGOPS_DSN": "postgresql://user:pass@localhost:5432/mydb" }    }  }}

uvx fetches and runs it in a throwaway environment — nothing to install first, and nothing added to your own project's dependencies.

Or run the container, if you would rather not put a Python toolchain on the machine that talks to your database:

json
{  "mcpServers": {    "pgops": {      "command": "docker",      "args": [        "run", "-i", "--rm",        "-e", "PGOPS_DSN",        "-v", "pgops-audit:/var/lib/pgops",        "ghcr.io/arzharch/pgops-mcp:latest"      ],      "env": { "PGOPS_DSN": "postgresql://user:[email protected]:5432/mydb" }    }  }}

Two things the container changes: mount a volume at /var/lib/pgops or the audit log dies with the container, and localhost inside a container is the container itself — use host.docker.internal or a compose service name.

Check the connection before wiring a client to it:

bash
uvx pgops-mcp --selfcheck --dsn "postgresql://user:pass@localhost:5432/mydb"

Both paths install the same server and are listed together in the MCP Registry entry — they fail for different people. uvx needs nothing preinstalled but assumes the host may run Python; the container assumes only Docker.

See SETUP.md for configuration, HTTP transport, agent tokens and troubleshooting, and CONTRIBUTING.md to run it from a source checkout.

Docs

Links are absolute so they resolve from the PyPI project page as well as from GitHub.

Using it

DocWhat's in it
Getting startedFirst 15 minutes, no MCP knowledge assumed
Tool referenceAll 18 tools: parameters, returns, error codes, scopes
Setup & configurationClients, HTTP auth, observability, troubleshooting
Environment variablesEvery knob, documented
Security modelWhat it can do, what it refuses, known limits
ChangelogWhat changed per release

How it works

DocWhat's in it
ArchitectureSystem design and trade-offs
System designThe safety pipeline, with diagrams
Decision recordsWhy each choice was made, and what it cost
BenchmarksWhat is measured, and against what

Contributing

DocWhat's in it
ContributingSource checkout, gates, release process
Module layoutWhat each module is for

How it's verified

471 tests, and the ones that matter run against a real PostgreSQL 16 in a container — not mocks. That is a deliberate decision (ADR-005): a guardrail proven only against a fake has been proven against the wrong thing. The interesting failures — default_transaction_read_only, lock escalation, transactional DDL, relfilenode changes on rewrite — are behaviours of the real database.

SuiteWhat it proves
Guardrails & classifierEvery refusal rule, against live Postgres
Property-based (Hypothesis)The invariant itself, over inputs nobody thought to write
Red-team15 named attacks a hostile agent would try — each refused and audited
Live serverReal HTTP server, real JWTs, end to end
BenchmarksLatency budgets as regression tripwires, published as CI artifacts

The red-team suite has found real bugs, which is the argument for having it: it caught a confirmation token issued for a refused statement being redeemable against a different one, and a pgops:read token that could call query.write because the scope table was documentation rather than enforcement.

Known limits

Stated here rather than left to be discovered:

  • No per-session database isolation. Auth identifies the caller and scopes limit what they may do, but every caller shares one connection manager and one audit log. Built for one engineer and a few databases, not multi-tenant SaaS.
  • index.advise names the table taking sequential scans, not the column to index — that needs per-statement plan inspection. It says so instead of inventing a CREATE INDEX.
  • DROP INDEX / DROP CONSTRAINT cannot be rolled back, because the object's definition is not captured before the drop. The rollback refuses and explains why rather than reconstructing a guess.

Sample of what migration.plan returns for a type change on the 1.2M-row orders:

ALTER TABLE "orders" ALTER COLUMN "total_cents" TYPE bigint  op=table_rewrite  risk=high  estimate=4800ms  confidence=medium  why:   rewrites every row and rebuilds every index, holding AccessExclusiveLock  SAFER: add a new column of the target type, backfill in batches, sync with a         trigger, swap the names, then drop the old column

Try it without a database of your own

A seeded stack with the 1.2M-row orders table used in every example above. Host port 5435, so it does not collide with a local Postgres on 5432:

bash
git clone https://github.com/arzharch/pgops-mcp && cd pgops-mcpdocker compose up -duvx pgops-mcp --selfcheck --dsn "postgresql://pgops:pgops_dev@localhost:5435/pgops_demo"

MIT licensed. Contributions welcome — see CONTRIBUTING.md.

來源:README.md,提交 aaadd7e

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.1.9最新Sep 16, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分