An MCP server that lets an AI agent (Claude Code, Codex, Cursor, or your own loop) diagnose a CloudNativePG cluster, without being able to change it.
Every tool is read-only, and the server's Kubernetes identity has no write verbs at all. The agent finds the problem and says what to do; a human does it.
- Copy
.mcp.json.exampleto.mcp.jsonand setPG_OPS_KUBECONFIGandPG_OPS_PASSWORD_FILEin your shell (eval "$(hack/agent-env.sh)"does it for the e2e cluster). No credential goes in the file. - The
postgres-triageskill loads when you ask about the database. It tells the agent to start fromcluster_status, follow the evidence instead of calling every tool, not to trust the operator'sphasealone, and to answer asDiagnosis / Evidence / Impact / Action for a human. - Ask: "orders is slow, check the database".
The same server works with any MCP client; the skill is plain Markdown that other agents can take as a system prompt (the evals do exactly that).
| Tool | What it returns |
|---|---|
cluster_status |
phase, primary, timeline, Ready / ContinuousArchiving conditions, each instance pod's role, readiness, restarts, node |
recent_backups |
last base backups with phase, age, error |
warning_events |
Kubernetes Warning events in the namespace |
replication |
standbys streaming from the primary, sync state, bytes and seconds behind |
wal_archiving |
last archived / failed WAL segment and how long ago |
connections |
backends by user and state, against max_connections |
long_transactions |
transactions open longer than N seconds, with redacted SQL |
blocking_locks |
who is waiting on whom (pg_blocking_pids) |
top_queries |
pg_stat_statements by total time, normalised and redacted |
The agent never sends SQL. Each tool runs one fixed query from
sql.py, and three independent layers keep it
harmless:
- The database role has only
pg_monitor. Postgres itself refuses writes and reads of table data. - Every query runs in a
READ ONLYtransaction withstatement_timeout = 3sandlock_timeout = 1s, rolled back at the end, so a slow catalog query cannot pile up during an incident. - Query text is redacted before it leaves the server: string and
numeric literals, dollar-quoted bodies, emails and anything shaped like
password=...are replaced. The agent sees the shape ofupdate users set email='?' where id=?, not the customer's address.
The server is bound to one namespace and one cluster by its environment
(PG_OPS_NAMESPACE, PG_OPS_CLUSTER); no tool takes a namespace or cluster
argument, so the agent cannot point it somewhere else.
There is one tool that is not read-only: propose_action. It writes a
proposal file and returns its ID; nothing else happens.
agent: propose_action(action="switchover", target_instance="orders-db-2",
reason="orders-db-1 restarted 4 times in 10m, OOMKilled")
-> {"accepted": true, "proposal_id": "9f3c21ab", "approve_with": "pg-ops-agent approve 9f3c21ab"}
human: pg-ops-agent proposals
9f3c21ab pending switchover -> orders-db-2 orders-db 2026-11-09T14:02:11+00:00
reason: orders-db-1 restarted 4 times in 10m, OOMKilled
pg-ops-agent approve 9f3c21ab # runs kubectl cnpg promote as *you*
- Two identities. The server runs as a service account with no write
verbs.
approveruns with the human's own kubeconfig, so every change in the Kubernetes audit log has a person's name on it. - Allowlisted actions (
switchover,backup), each with preconditions: a switchover needs a ready replica as target and no failover in progress. - Checked twice. Preconditions are checked when the agent proposes and again when the human approves, because the cluster may have moved on.
- Audit log. Every tool call is appended to
.state/audit.jsonlwith its arguments, outcome, duration and result size.
| Layer | The agent can | The agent cannot |
|---|---|---|
Kubernetes (deploy/rbac.yaml) |
get/list CNPG clusters, backups, poolers, pods, events in one namespace | read Secrets, exec into pods, read pod logs, change anything, see other namespaces |
Postgres (deploy/postgres-role.yaml) |
read statistics views (pg_monitor) |
read table data, write, create objects |
| MCP server | call fixed tools bound to one cluster | send SQL, choose a namespace or cluster, run an action |
e2e/rbac.sh checks the Kubernetes column on a real cluster
with kubectl auth can-i --as for every allowed and denied verb, including
the subresources (pods/exec, pods/log, clusters/status).
The e2e environment (hack/e2e-up.sh) is a kind cluster
with CloudNativePG, the Barman Cloud plugin, local S3 and a three-instance
cluster. Every credential in it is generated at setup time; nothing secret
is in the repository. hack/agent-env.sh writes a
kubeconfig with a short-lived token for the agent's service account, so
the server is tested as the agent, not as an admin.
e2e/test_tools.py starts the real server over stdio,
the way Claude Code or any MCP client does, with the agent's own kubeconfig
and database role, and calls every tool against the kind cluster:
- the cluster shows three ready instances, two
quorumstandbys streaming, andContinuousArchivingtrue; - a query run with a card-number-like literal shows up in
top_querieswithout the number; - every call lands in the audit log;
- logged in as the agent's role directly,
selectfrom a table,insertandcreate tableare all refused by Postgres.
The pooler is published on 127.0.0.1:15432 through a kind port mapping
rather than kubectl port-forward: PgBouncer resets connections when a
client disconnects, and port-forward exits on the first reset.
e2e/scenarios.py breaks the real cluster in four ways
and undoes it; e2e/test_faults.py checks that each
fault is visible through the tools:
| Scenario | Injected | Visible in |
|---|---|---|
| long transaction | a session writes a row and sleeps inside its transaction | long_transactions (the row's value is redacted) |
| lock contention | ACCESS EXCLUSIVE lock held, three readers waiting |
blocking_locks: one blocker, three waiters |
| replica down | one standby fenced (cnpg.io/fencedInstances) |
cluster_status (2 of 3 ready), replication (one standby) |
| WAL archiving failure | object store endpoint pointed at a host that does not exist | wal_archiving (failed_count, last failed segment) |
These are the oracle for the LLM evals below: when they pass, a wrong diagnosis is the model's, not the tooling's.
One thing the replica scenario surfaced: with a standby stopped, the
operator's phase still reads "Cluster in healthy state", and
readyInstances only drops 30-40 s later. An agent (or a dashboard) that
trusts phase misses it. The triage skill says so.
evals/run.py injects each fault into the kind cluster,
starts the server as the agent, and runs a small tool-calling loop
(evals/agent.py) with the triage skill as the system
prompt and the page "orders service is slow and some requests fail". The
Diagnosis: line is graded against the injected fault; proposing an action
on a healthy cluster also fails. Any OpenAI-compatible endpoint works; the
run below used qwen3:8b on a laptop through Ollama, so no API key and no
data leaves the machine.
Results, two runs per scenario, temperature 0:
| Scenario | Result | Tools the model chose |
|---|---|---|
| healthy | 2/2 | cluster_status, connections, long_transactions, blocking_locks |
| long transaction | 2/2 | cluster_status, connections, long_transactions |
| lock contention | 0/2 | cluster_status, connections, long_transactions |
| replica down | 2/2 | cluster_status, replication, warning_events |
| WAL archiving failure | 2/2 | cluster_status |
| total | 8/10 | 1 to 4 calls, 70-100 s per run |
What the misses show: on lock contention the model never called
blocking_locks. long_transactions already showed the sleeping session
and the waiting select count(*) from stock queries, and the model
described the contention correctly in its evidence, but filed it as
long_transaction. The tools carried the evidence (the oracle test passes);
the gap is in the categories, where a lock held by a long transaction fits
both. Fixing it means teaching "a lock holder with waiters is
lock_contention" in the skill, then re-running the eval, not editing the
grader.
Two other lessons from building it:
- The first run graded a healthy cluster as
other: the page said "slow", and the skill never said that "the database is fine" is a valid answer. One sentence in the skill fixed it. - On WAL archiving the model stopped after
cluster_status, because theContinuousArchivingcondition was already false. Fewer calls when the first tool is conclusive is the behaviour the skill asks for.
The evals are not in CI: they need a model. The e2e and fault tests are.
python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
make check # ruff + unit tests
make e2e-up # kind + CNPG + test cluster
make rbac # the agent's service account can read and cannot write
make e2e # RBAC + every tool over MCP against the cluster
.venv/bin/pip install -e ".[eval]"
.venv/bin/python evals/run.py --model qwen3:8b --runs 2 # Ollama on localhost