Skip to main content
Glama
pg-governance-mcp

pg-governance-mcp

README.md
# governed-data-agents

**An MCP server that gives AI agents least-privilege access to PostgreSQL — every tool call runs
under the calling agent's own database role — and a small multi-agent runtime that uses it.**

Prompts are not access control. A typical database MCP server connects with one service account,
so every agent gets the union of everyone's permissions, and the only thing between a model and the
customer table is its system prompt. Here the database itself decides what each agent may do; the
orchestrator adds a second, independent layer (allow-lists, risk levels, human approval); and the
models never see raw personal data — only aggregates.

The demo is a six-agent **data governance team** reviewing a request to copy a CRM customer base
(50 000 synthetic customers with planted data-quality defects) into a marketing warehouse.

```
make env && make up      # Postgres + the MCP server (Docker)
make probe               # what each agent may do — enforced by Postgres, observed through MCP
make demo                # the whole team, scripted playbooks instead of an LLM: no API key needed
make run                 # the same team driven by your model (set LLM_* in .env)
```

## How a tool call is governed

```
 model ─► govagents (client side)              ─► pg-governance-mcp (server side)  ─► PostgreSQL
          1 allow-list: is the tool in            4 authenticate: shared token +       6 SET ROLE agent_<id>
            this agent's list?                      X-Agent-Id, or the agent's          (the server's login is
          2 risk: read / write / irreversible       own signed JWT                       NOINHERIT: no rights)
          3 human approval when the policy       5 agent -> DB role; unknown         7 GRANTs decide; refusals
            says so (CLI)                           agent -> a role with no rights      come back as tool errors
                                                                                     8 personal data only as
 model ◄─ result wrapped as DATA: size-capped, secrets redacted, forged markers removed   aggregates (SECURITY DEFINER)
```

Two layers that do not trust each other. A call the client policy allows can still be refused by
the database, and a server's own tool annotations ("read-only!") never relax the client's policy.

## The access matrix

Output of `make probe` (here rendered with `govagents probe --markdown`): real MCP calls under each identity. Write probes send a row that
violates a CHECK constraint, so the probe never writes anything — a role *with* the privilege gets
"row rejected", a role *without* it gets "DENIED BY DATABASE".

| action | `steward` | `architect` | `dq` | `access` | `dpo` | `lead` | `(unknown)` |
|---|:-:|:-:|:-:|:-:|:-:|:-:|:-:|
| read the governance registry | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
| read raw CRM rows | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| profile data (aggregates only) | ✅ | ✅ | ✅ | ❌ | ✅ | ❌ | ❌ |
| run a data-quality check | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
| list grants on a table | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ |
| write the column catalog | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| write a DQ result | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
| file a privacy (DPO) verdict | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ |
| record the final decision | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ |

In JWT mode (`make up-jwt && make probe-jwt`) the probe also shows that the steward's token with a
forged `X-Agent-Id: lead` header still runs as `agent_steward`.

## What a run looks like

An excerpt of `make demo` (scripted mode — the numbers are real, parsed from tool results):

```
── dq · Data Quality Engineer ──────────────────────────────────────────────────
  ✓ skills/load                loaded data-quality-rules
  ✓ pg/run_dq_check            check_type=regex total_rows=50000 violations=760 violation_pct=1.520
  ✓ pg/run_dq_check            check_type=duplicate_combo total_rows=50000 violations=120 violation_pct=0.240
  ✓ pg/run_dq_check            check_type=required_if_true total_rows=50000 violations=300 violation_pct=0.600
  ...
  ✓ pg/append_registry         Wrote 10 of 10 rows to governance.dq_results (author recorded by the database: agent_dq)
  ⛔ pg/append_registry         denied by the database: DENIED BY DATABASE: role agent_dq has no privilege
                               for this action (permission denied for table dpo_reviews)

── lead · Head of Data Governance ──────────────────────────────────────────────
  ✓ pg/query_registry          verdict=rejected
  ✓ pg/query_registry          failed=8 total=10

==============================================================================
 APPROVAL NEEDED  agent=lead  tool=pg/append_registry  risk=write
 why: lead needs approval for 'write' actions
------------------------------------------------------------------------------
{ "table": "onboarding_decisions", "records": [ { "request_id": "DG-142",
    "decision": "needs_changes", "summary": "Package reviewed: 9 registries filled. ..." } ] }
==============================================================================
 Approve this call? [y/N] y
  ✓ pg/append_registry         Wrote 1 of 1 rows to governance.onboarding_decisions (author recorded by the database: agent_lead)

── registry after the run ──────────────────────────────────────────────────────
  column_catalog | agent_steward | 16        dq_rules | agent_dq | 10
  datasets | agent_steward | 1              dq_results | agent_dq | 10
  glossary | agent_steward | 2              access_policies | agent_access | 1
  data_contracts | agent_architect | 1      dpo_reviews | agent_dpo | 1
  lineage_edges | agent_architect | 16      onboarding_decisions | agent_lead | 1
```

The registry's `created_by` column defaults to `current_user`, so the author of every row is
recorded by the database — not claimed by the model. Each run also writes `runs/<time>/report.md`
and a metadata-only `audit.jsonl`. The scripted mode includes two labelled guardrail
demonstrations: the architect calls a tool outside its allow-list (stopped by the client policy)
and the DQ engineer tries to file a privacy verdict (refused by the database).

## The MCP server — `pg-governance-mcp`

Streamable HTTP, JSON-RPC 2.0, protocol revisions 2025-03-26 · 2025-06-18 · 2025-11-25. Stateless
(no session state, scales horizontally), stdlib HTTP + psycopg. Verified with the official MCP
Python SDK (2.3): the legacy handshake negotiates 2025-11-25, and its `auto` mode falls back from
the 2026-07-28 probe cleanly.

| tool | what the agent gets | annotation |
|---|---|---|
| `whoami` | its DB role and effective privileges | read-only |
| `list_objects` | tables / views with row counts and descriptions | read-only |
| `describe_object` | columns, types, nullability, comments | read-only |
| `profile_object` | per-column aggregates: nulls, distinct, lengths, share of e-mail / E.164 / passport-like values — never a value | read-only |
| `run_dq_check` | violation count for `not_null`, `unique`, `regex`, `allowed_values`, `min_value`, `not_future`, `age_between`, `required_if_true`, `duplicate_combo`, `max_age_hours` | read-only |
| `list_grants` | who holds which privilege on an object | read-only |
| `query_registry` | one read-only SELECT against the governance registry (≤ 100 rows) | read-only |
| `append_registry` | append rows to the registry tables its role may write | writes |

Hardening: `401` (with `WWW-Authenticate`) before any tool is reached, `403` for a browser
`Origin` that is not allowed (DNS rebinding), `413` over 1 MiB, `405` on `GET /mcp`, an unknown
tool is a JSON-RPC `-32602`, logs carry metadata only (agent, tool, outcome).

Use it from any MCP client, e.g. Claude Code:

```bash
claude mcp add --transport http pg-governance http://localhost:8765/mcp \
  --header "Authorization: Bearer $PGMCP_TOKEN" --header "X-Agent-Id: steward"
```

## The agent runtime — `govagents`

- **Bring your own model** — any OpenAI-compatible Chat Completions API (OpenAI, OpenRouter,
  vLLM, Ollama, LM Studio …) or the Anthropic Messages API. Each adapter keeps the transcript in its
  provider's own format and only appends to it. No provider is configured by default.
- **Policy before the network** — one deterministic decision per call (`deny` > `require_approval`
  > `allow`): server → allow-list → `irreversible` → the agent's `approval_for` → taint (output from
  an `untrusted_output` server makes every later non-read call need a human).
- **Tool output is data** — capped, secrets redacted, forged `<<<TOOL DATA>>>` markers removed,
  wrapped in markers the system prompt says never to obey. Teammates' notes are wrapped the same way.
- **Bounded** — at most `max_tool_calls` per agent, then one last turn without tools for the report.
- **Context management** — agents don't share transcripts. Each starts fresh with its brief and
  short notes from the agents before it; the shared state is the registry in the database.
- **Skills** — `skills/<name>/SKILL.md`. The system prompt lists one line per skill; the agent loads
  the full text with the local `skills__load` tool when it needs it (progressive disclosure).
- **Audit** — `audit.jsonl`: agent, server/tool, policy decision and layer, outcome, timings,
  tokens. Never arguments, results, prompts or keys.
- **Identity** — token mode (shared bearer + `X-Agent-Id` set by the orchestrator from its config,
  never from model output) or JWT mode (a short-lived RS256 token per agent; `make keys` creates a
  dev key pair, in production your IdP issues them).

## Configuration

- `.env` — secrets (`make env` fills them with random values) and your LLM provider:
  `LLM_PROVIDER=openai|anthropic`, `LLM_BASE_URL`, `LLM_API_KEY`, `LLM_MODEL`.
- `team.yaml` — servers, local risk levels, agents, their tool allow-lists, briefs and approvals.
- `db/03_governance.sql` — the registry and the GRANT matrix: the source of truth for permissions.

## Layout

```
src/pgmcp/       MCP server: tools.py (tools + SET ROLE), auth.py (token / JWT), server.py (transport)
src/govagents/   runtime: mcp_client, llm (adapters), policy, loop, runner, skills, approval, audit,
                 identity, probe, scripted (no-LLM playbooks), cli
db/              schema, synthetic data, registry + GRANTs, reset, the human "apply" step
skills/          pii-classification, data-quality-rules, privacy-review
docs/            security-model.md — threats and the control for each
tests/           55 tests; the integration ones run against `make up`
```

## Tests

```
pip install -e ".[dev,anthropic]"
pytest -q                                    # unit tests; integration tests skip without the stack
make up && set -a && . ./.env && set +a && PGMCP_URL=http://127.0.0.1:${MCP_PORT}/mcp pytest -q -m integration
```

CI runs the unit tests, then the whole stack in Docker: the access matrix, a scripted team run, and
JWT mode with the forged-header check.

## Limitations

- A demo domain: one database, one request. The server's tools are specific to it; the pattern
  (per-agent roles, aggregate-only functions, append-only registry) is the reusable part.
- No OAuth authorization server: bearer token or JWTs verified against a JWKS you provide.
- Human approval is a terminal prompt.
- How well the LLM-driven run goes depends on your model; the scripted mode makes the demo
  deterministic and free.

## License

MIT