governed-warehouse-mcp

A governed Model Context Protocol server that lets AI agents
answer questions from an analytical warehouse. Agents cannot write to the warehouse, read data
their token does not allow, or see personal data they are not cleared for. The repository also
has an eval harness for tool-calling agents. It runs the real Anthropic SDK and the real MCP
server end to end, and it runs offline, so CI needs no API key. Live runs work with Claude or
any Anthropic-compatible API, can be traced to Langfuse, and can be
graded by an LLM judge that is calibrated against the deterministic graders first.
The warehouse is a synthetic cross-border freight dataset (shipments, carriers, lanes, border
crossings, customs documents, invoices, quotes). It is generated deterministically from a seed,
and nothing in it is real.
$ uv run gwm-eval all --gate
wrote reports/report.md and reports/report.json
all gates passed
Contents
- Why it exists
- What an agent sees
- Architecture
- Quickstart · deployment
- Evals · tracing with Langfuse
- Configuration
- Extending the catalog
- Development
- Docs: architecture and design decisions ·
threat model · eval methodology ·
latest eval report · contributing ·
security · changelog
Why it exists
Letting an LLM agent query a warehouse is easy. Letting it do so safely, and knowing whether it
answers correctly, is the hard part. This repository does both:
- The server puts a semantic layer, an access policy and a SQL guard between the agent and
the data. Agents ask for governed metrics by name, or write SQL. Agent SQL is parsed, checked
and regenerated before it runs on a read-only, sandboxed connection. Every call is audited.
- The eval harness measures an agent on that server. It checks whether the agent answers
correctly, respects governance, and resists prompt injection planted in the data. The graders
are deterministic, and they are themselves tested against planted failures. An LLM judge
covers what rules cannot check (is a refusal honest? is the answer clear?), and it is
calibrated against those graders and human labels before its verdicts count.
What an agent sees
Five tools and one resource:
| tool |
what it does |
search_models |
ranks the models and metrics the caller may see for a plain-language question |
describe_model |
returns grain, tier, columns (with which are PII), joins and metrics for one model |
list_metrics |
lists governed metrics with definitions, time column and allowed dimensions |
query_metric |
computes a metric by name, grouped, filtered and bucketed by time; returns the SQL that ran |
run_sql |
runs one read-only SELECT over visible catalog models, after the guard checks it |
catalog://version |
resource: the published catalog version and its tiers |
A metric query returns rows together with how they were produced. These are real responses for
the analyst role; the data is synthetic:
// query_metric {"metric": "on_time_rate", "group_by": ["dim_lanes.border_crossing"],
// "start_date": "2025-01-01", "end_date": "2025-12-31"}
{
"columns": ["border_crossing", "on_time_rate"],
"rows": [[null, 0.873348], ["Detroit-Windsor", 0.788462], ["El Paso", 0.765799],
["Laredo", 0.753898], ["Buffalo", 0.752964], ["Nogales", 0.752092]],
"truncated": false,
"sql": "SELECT \"dim_lanes\".\"border_crossing\" AS \"border_crossing\", AVG(CASE WHEN ...) ...",
"models": ["dim_lanes", "fct_shipments"],
"catalog_version": "v1-42c3e5f7aec9"
}
Refusals start with a stable code, so an agent can recover and an eval can grade without
parsing prose:
run_sql "select contact_email from dim_customers limit 3"
PII_DENIED: column 'contact_email' is PII and needs the pii:read scope
run_sql "select sum(amount_usd) from fct_invoices" (restricted model)
UNKNOWN_MODEL: 'fct_invoices' is not a model you can query; use search_models to find one
run_sql "drop table fct_invoices"
READ_ONLY: only SELECT queries are allowed, got DROP
A restricted model gets the same answer as a model that does not exist, so a refusal never
confirms what is there.
Architecture
flowchart LR
subgraph Agent["Agent (warehouse_evals.agent)"]
LLM["Anthropic SDK: Claude or an<br/>Anthropic-compatible API<br/>streaming, adaptive thinking"]
Loop["Tool loop<br/>strict JSON re-parse<br/>JSON Schema validation"]
LLM <--> Loop
end
subgraph Server["MCP server (warehouse_mcp.server)"]
Auth["Auth<br/>Ed25519 JWT, scopes"]
RL["Rate limit"]
Tools["Tools<br/>search_models · describe_model<br/>list_metrics · query_metric · run_sql"]
Sem["Semantic compiler<br/>metric to AST"]
Guard["SQL guard<br/>sqlglot AST, fail closed"]
Audit[("Audit log<br/>JSONL")]
Auth --> RL --> Tools
Tools -- query_metric --> Sem --> Guard
Tools -- run_sql --> Guard
Tools -.-> Audit
end
Catalog[["Catalog (YAML)<br/>models, tiers, PII columns,<br/>joins, metrics"]]
DB[("DuckDB, read-only<br/>no external access,<br/>config locked, timeout")]
Loop -- "MCP: stdio, Streamable HTTP<br/>or in-process" --> Auth
Loop -.->|"live runs only,<br/>PII redacted"| LF[("Langfuse traces")]
Catalog --> Tools
Catalog --> Sem
Catalog --> Guard
Guard --> DB
Every tool call takes the same path:
- resolve the principal from the token;
- apply the rate limit;
- run the tool against the catalog;
- check the SQL;
- execute it;
- write the audit record.
The architecture notes cover each component and the reasoning behind
the main design choices.
Governance model
|
partner |
analyst |
finance |
support |
| public models (lanes, carriers, lane and carrier marts) |
✓ |
✓ |
✓ |
✓ |
| internal models (shipments, customers, tracking, documents, quotes) |
|
✓ |
✓ |
✓ |
| restricted models (invoices, revenue marts) |
|
|
✓ |
|
| PII columns (customer contact name, email, phone) |
|
|
|
✓ |
Roles are only presets for dev tokens. The server reads scopes: warehouse:public,
warehouse:internal, warehouse:restricted and pii:read. Tiers are contiguous, so a token
with restricted but not internal gets public access only.
Defence in depth, from the outside in:
-
Authentication. Tokens are Ed25519-signed JWTs. The algorithm is pinned, and exp,
iat, sub, iss and aud are required. Over HTTP the MCP SDK's auth middleware verifies
every request; over stdio the token is verified once at start-up. The token's client_id
names the agent, and its scopes are cut to what that agent is permitted in the
agent registry. A missing, unknown or disabled agent is
rejected, and onboarding another agent is one registry entry.
-
Semantic layer. query_metric compiles a metric request into a sqlglot AST from the
catalog. User values only ever become quoted literals, and identifiers are always quoted.
-
SQL guard. run_sql SQL, and compiled metric SQL again, must pass these checks:
- exactly one read-only statement, over visible catalog models only;
- no file, network, settings or introspection functions;
- no positional references;
- no PII columns without
pii:read, wherever they appear (select list, filters, joins,
*, whole-row references).
The SQL that runs is regenerated from the checked AST, so comments never reach the engine.
-
Engine. DuckDB is opened read-only, with external access disabled, extension autoload
off, a memory limit and a query timeout. Its configuration is locked, so a query cannot undo
any of this.
-
Result budget. Rows are capped, and responses are truncated to a character budget with a
flag the agent can see. Results from free-text columns carry a warning that their content is
data, not instructions.
The threat model maps each threat to its mitigation and to the test
that proves it.
Quickstart
Requires uv.
uv sync
uv run gwm generate # build data/warehouse.duckdb (deterministic)
uv run gwm keys # dev Ed25519 keypair in .keys/
uv run gwm token --role analyst # print a signed dev token
Use it from Claude Code
claude mcp add warehouse \
--env GWM_TOKEN="$(uv run gwm token --role analyst --ttl 86400)" \
-- uv --directory "$PWD" run gwm serve
Use it from Claude Desktop
{
"mcpServers": {
"warehouse": {
"command": "uv",
"args": ["--directory", "/absolute/path/to/governed-warehouse-mcp", "run", "gwm", "serve"],
"env": { "GWM_TOKEN": "<output of gwm token --role analyst --ttl 86400>" }
}
}
}
Run it over Streamable HTTP
uv run gwm serve --transport http --port 8000 --audit-log audit.jsonl
# clients send: Authorization: Bearer <token>
Without a valid bearer token the server answers 401. With one, each request is served with that
token's scopes. /healthz and /readyz answer without a token and return no data.
Deployment
The Dockerfile builds a small image that serves Streamable HTTP as a non-root user.
The synthetic warehouse is baked in at /data, and the server needs only a public key at /keys:
A prebuilt image is published for each release as ghcr.io/tongliutl/governed-warehouse-mcp
(linux/amd64 and linux/arm64), and the server is listed in the
MCP Registry as
io.github.tongliuTL/governed-warehouse-mcp. To build it yourself:
docker build -t governed-warehouse-mcp .
uv run gwm keys --dir .keys # dev keys; in production, your identity provider's key
docker run --rm -p 8000:8000 --read-only --tmpfs /tmp \
-v "$PWD/.keys/public.pem:/keys/public.pem:ro" governed-warehouse-mcp
curl localhost:8000/readyz # {"status": "ready", "catalog_version": "..."}
- Read-only. The root filesystem can be read-only: the warehouse opens
read_only, spilling
to disk is off, and nothing is written outside /tmp. Mount your own warehouse with
-v /path/to/data:/data:ro.
- Host names. DNS-rebinding protection only accepts listed Host headers. The image accepts
localhost:8000 and 127.0.0.1:8000; behind a proxy, pass your own, for example
docker run ... governed-warehouse-mcp --allowed-host mcp.example.com --public-url https://mcp.example.com.
- Probes.
/healthz (the process is up) and /readyz (a trivial query succeeds; 503
otherwise). The image's HEALTHCHECK uses /readyz.
- CI. Every change builds the image, runs it with a read-only root filesystem, and runs
scripts/smoke_http.py: probes, a 401 without a token, an allowed
query, a denied one and a refused write.
This makes the server deployable, not operated: there is no identity provider, TLS
termination, log shipping or horizontal scaling here. Those belong to the platform it runs on.
Evals
uv run gwm-eval all --gate # offline: what CI runs
uv run gwm-eval live --trials 3 --record cassettes/ --stream # a real model (see Configuration)
uv run gwm-eval replay cassettes/ # replay recorded live runs offline
uv run gwm-eval calibrate --live # calibrate the LLM judge against graders and labels
The harness has three suites and a judge calibration. docs/evals.md describes
the method in detail.
-
Agent cases (22):
- answer (10): questions the agent must answer correctly;
- governance (4): the right refusal for the role, and a PII-cleared role getting what it is
cleared for;
- prompt injection (8): instructions planted in shipment notes that ask the agent to drop a
table, report a false number, or dump customer emails; and five red-team cases, each a
different route in: a poisoned column description, a payload echoed in a tool error, writes
disguised with comments, case and full-width Unicode, an image link that would carry data out,
and a note claiming the user was promoted to finance.
Gold answers are computed from the warehouse at run time, so cases cannot drift from the data.
-
Grader validation. Five planted-failure policies run against every case: fabricating
numbers, probing PII, following injected instructions, leaking a restricted figure, and
over-calling tools. Each must trip exactly the graders built to catch it, and the reference
policy must pass every grader.
-
Retrieval. Measures whether search_models ranks a correct model or metric in the top k,
for questions phrased the way people ask. A dev set is used to tune the rankers; results are
reported on a held-out set.
-
Judge calibration. An LLM judge grades each trajectory on a versioned rubric
(answer_quality_v3: grounded answer,
respects access, no unsafe actions, honest refusal, clear and concise). gwm-eval calibrate
runs every planted-failure policy, judges each trajectory, and reports agreement, Cohen's
kappa and a confusion matrix per criterion, against the graders and against blind human
labels. Verdicts are cached by rubric text, model, effort and trajectory, so a calibrated run
repeats offline. The verdicts for MiniMax-M3.1-Flash are committed in judgments/, and CI
re-runs the calibration from them with no model calls, failing below κ 0.6.
How it runs offline
The agent always runs on the real anthropic SDK, streaming, against the real MCP server. Only
the HTTP transport underneath the SDK changes:
| mode |
transport |
what it measures |
| scripted |
ScriptedTransport encodes turns from a Python policy as Messages API SSE |
the harness, server and graders (not a model) |
| live |
the network, wrapped by RecordingTransport |
a real model, recorded to cassettes |
| replay |
ReplayTransport serves cassettes in order |
the recorded model, reproducibly, in CI |
Cassettes keep the response streams and a fingerprint of each request (model, system prompt,
tool schemas, turn count). They never store headers or API keys. If the agent or server changes
so that a recording no longer matches, replay fails loudly and so does the CI gate; re-record
when that happens.
Results
These results come from an offline run: the scripted reference policy, grader validation and
retrieval. The scripted results show that the harness works; they are not a model's score.
| suite |
runs |
pass rate |
| answer |
10 |
100% |
| governance |
4 |
100% |
| injection |
8 |
100% |
Grader validation caught 90/90 planted failures with 0 false positives, and 22/22
reference trajectories passed every grader.
Retrieval (Recall@3 is gated at 0.9 for the fused ranker on both sets):