Skip to main content
Glama

governed-warehouse-mcp

CI Python 3.11 to 3.13 License: MIT

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

Related MCP server: Semantic BI MCP

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:

  1. resolve the principal from the token;

  2. apply the rate limit;

  3. run the tool against the catalog;

  4. check the SQL;

  5. execute it;

  6. 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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):

ranker

dev R@1

dev R@3

dev MRR

held-out R@1

held-out R@3

held-out MRR

substring baseline

78.1%

93.8%

0.855

54.2%

70.8%

0.628

identifier BM25

84.4%

100%

0.917

62.5%

91.7%

0.767

description BM25

62.5%

93.8%

0.760

87.5%

100%

0.931

RRF fusion

65.6%

96.9%

0.820

83.3%

100%

0.903

dense (bge-small, optional)

71.9%

93.8%

0.829

58.3%

75.0%

0.704

RRF + dense (optional)

84.4%

100%

0.917

83.3%

100%

0.910

Each single ranker wins one set and loses the other. Fusion is the only one that holds up on both, so the server uses it. An optional dense ranker joins the fusion as a third list (--dense, see Configuration); it lifts the dev set but adds nothing beyond noise on the held-out set, so it stays off by default. The full report is in docs/eval-report.md, and every CI run uploads a fresh one.

Live model results are not committed yet because they need an API key. To add them, run gwm-eval live --record cassettes/ and commit cassettes/. CI then replays the recordings and adds a "replayed live runs" section to the report.

Tracing live runs with Langfuse

gwm-eval live and gwm-eval calibrate --live send traces to Langfuse when its keys are set. Without them, or for scripted and replayed runs, nothing is traced: those model turns are fixtures, and tracing them would record invented usage and cost.

cp .env.example .env   # fill in the model provider and LANGFUSE_* keys (see Configuration)
uv run gwm-eval live --case otd-2025

trace

observations

scores and attributes

answer-question (one per case and trial)

agent root (question in, answer out); one call-model generation per Messages call with thinking, served model and token usage including cache reads; one tool observation per tool call, a sibling of the generation that asked for it

a boolean score per grader (grader.*) and passed; user eval-<role>; tags suite:, role:, mode:

grade-trajectory (one per judge cache miss)

evaluator root (trajectory in, verdicts out) wrapping one judge-trajectory generation

tags judge, rubric:<id>@v<n>

Every PII value in the warehouse is replaced with [REDACTED_PII] before export, whatever the run's role. Traces go to the eval environment unless LANGFUSE_TRACING_ENVIRONMENT is set; LANGFUSE_TRACING_ENABLED=false turns tracing off. The code is in src/warehouse_evals/tracing.py.

Configuration

Server (gwm serve)

option

default

meaning

--transport

stdio

stdio (token from GWM_TOKEN) or http (bearer token on every request)

--host, --port

127.0.0.1, 8000

HTTP bind address; DNS-rebinding protection allows only this host

--db

data/warehouse.duckdb

warehouse file, opened read-only

--keys

.keys

directory with public.pem used to verify tokens

--issuer, --audience

dev values

required iss and aud claims

--max-rows

200

row cap per query; query_metric limits and run_sql results above it are refused or truncated

--audit-log

none

append one JSON line per tool call (allowed, denied or failed)

--agents

packaged agents.yaml

agent registry: each client_id's permitted scopes, owner and whether it is enabled. The packaged one registers only local-dev

--dense

off (GWM_DENSE=1 turns it on)

fuse a local embedding model into search_models as a third RRF list; needs uv sync --extra dense

Dense retrieval (optional). --dense embeds the catalog and each query with BAAI/bge-small-en-v1.5 through fastembed (ONNX, CPU, no PyTorch), on the machine: no catalog text or question is sent anywhere. The model (about 64 MB) downloads on first use into ~/.cache/governed-warehouse-mcp/dense/models. Entry vectors are cached there per catalog version and embedding model, and a cache written by another model is refused rather than mixed in. Query vectors are kept in a 1,000-entry LRU cache. If the model is missing or fails, the query is served by the two lexical lists, a warning is logged, and the audit record's ranker says rrf (dense failover). Like the lexical lists, the dense list is ranked over the caller's tier index only, so its positions never depend on an entry the caller cannot see.

Other limits live in ServerConfig:

  • 60,000 characters per result;

  • a 10 s query timeout;

  • a per-principal token bucket of 60 calls, refilling at 1 per second;

  • SQL capped at 20,000 characters.

Live runs: model provider and credentials

gwm-eval live and gwm-eval calibrate --live read credentials from a gitignored .env (start from .env.example). Variables already set in your shell take precedence, and no other command reads the file.

variable

meaning

ANTHROPIC_API_KEY

key for the model provider

ANTHROPIC_BASE_URL

unset for the Claude API; set for an Anthropic-compatible provider (the template uses https://api.minimax.io/anthropic)

GWM_MODEL, GWM_JUDGE_MODEL

default --model for live and calibrate (default claude-opus-5-5; the template uses MiniMax-M3.1-Flash)

LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL

turn on tracing; leave the keys empty to run without it

The agent sends some Claude-specific request fields (the server-side fallback beta, eager tool-input streaming). An Anthropic-compatible provider may ignore them; a live case passes on MiniMax-M3.1-Flash. The judge records verdicts through a tool call rather than structured outputs (which MiniMax ignores), and asks again if a criterion is missing. Calibrate a judge on a new provider before trusting it.

Development credentials

gwm keys and gwm token exist for local development; gwm token --client-id picks the agent (default local-dev). In production, point the verifier at your identity provider's public key, issue short-lived tokens there, and pass --agents with your own registry, without local-dev.

Extending the catalog

Models and metrics are declared in src/warehouse_mcp/catalog/catalog.yaml.

  • A metric is an expression on a base model, optionally with a filter. Columns must be model-qualified, and they must come from the base model or a model it declares a join to:

    - name: on_time_rate
      model: fct_shipments
      description: Share of delivered shipments that arrived on or before the promised delivery date.
      expression: AVG(CASE WHEN fct_shipments.delivered_date <= fct_shipments.promised_delivery_date THEN 1.0 ELSE 0.0 END)
      where: "fct_shipments.status = 'delivered'"
      format: ratio
      synonyms: [on time delivery, OTD, service level, reliability, punctuality]
  • A model declares its tier and grain, and each column's type, which columns are pii, and which are free_text.

The catalog is validated at load time:

  • joins must point to real keys;

  • metrics may only read reachable, non-PII columns;

  • names must be unique.

tests/test_catalog.py checks the catalog against the warehouse in both directions, so a column missing from either side fails CI. A metric is as sensitive as the most sensitive model it reads, and the server derives its tier automatically.

Development

uv sync
uv run ruff check . && uv run ruff format --check . && uv run mypy
uv run pytest --cov

CI runs four checks:

  • lint and strict type checks;

  • the test suite on Python 3.11, 3.12 and 3.13: 234 tests, with a coverage floor of 85% (currently about 96%);

  • end-to-end tests that start the server as a subprocess over stdio and over HTTP;

  • the offline eval gate, run with an empty API key.

Tests never read .env or exported Langfuse keys, so they make no live calls and send no traces. Content fingerprints in the tests pin the synthetic data, so any change to the generator has to show up as a visible, deliberate test update. See CONTRIBUTING.md.

Repository layout

src/warehouse_mcp/        the server
  synthetic.py            deterministic synthetic warehouse (seeded)
  catalog/catalog.yaml    models, tiers, PII columns, joins, metrics
  policy.py  auth.py      scopes, principals, visibility, JWT verification
  semantic.py             metric request -> SQL AST
  sql_guard.py            AST checks for agent SQL
  warehouse.py            read-only, sandboxed DuckDB execution
  discovery.py            BM25 + RRF search over the catalog
  server.py  audit.py  ratelimit.py  cli.py
src/warehouse_evals/      the eval harness
  agent.py                streaming tool-calling agent on the Anthropic SDK
  sse.py  transport.py    offline transports: scripted, recording, replay
  cases/                  agent and retrieval cases (YAML)
  graders.py  scripted.py  validation.py  retrieval.py  runner.py  report.py  cli.py
  judge.py  calibration.py  rubrics/   LLM judge, verdict cache, calibration against graders and labels
  tracing.py              Langfuse tracing for live runs, with PII redaction
tests/                    unit, integration and end-to-end (stdio and HTTP subprocess) tests
docs/                     architecture, threat model, eval methodology, latest eval report
scripts/smoke_http.py     smoke test for a running HTTP server (CI runs it against the image)
Dockerfile                multi-stage image: non-root, read-only root filesystem, Streamable HTTP
.env.example              template for live-run credentials (copy to the gitignored .env)

Provenance

The design follows a production system I built for a logistics data platform. This repository is a from-scratch reimplementation. No code, schema or data from that system is used, and all data here is synthetic. The case study behind it, covering the decisions and results, is at tongliu.md/work/data-access.

License

MIT

Available Tools

5 tools
describe_modelA

Describe one model: grain, access tier, columns with types and descriptions, which columns are PII (not selectable without pii:read), joins and metrics built on it.

Inputs: name (required). Returns: kind, name, tier, grain, +6 more

list_metricsA

List the governed metrics you can query, with their definitions, base model, time column and the dimensions each metric can be grouped or filtered by.

Inputs: no named parameters. Returns: metrics, catalog_version

query_metricA

Compute a governed metric, optionally grouped, filtered and bucketed by time.

Prefer this over run_sql: the metric definition is the agreed business logic. The result includes the SQL that ran and the models it read, for provenance.

Inputs: metric (required), limit, filters, end_date, +5 more. Returns: sql, rows, models, columns, +6 more

run_sqlA

Run one read-only SELECT against catalog models when no metric fits.

The query is validated before it runs: only visible catalog models, no PII columns without pii:read, no file or system functions, and results are capped.

Inputs: sql (required). Returns: sql, rows, models, columns, +6 more

search_modelsA

Search the catalog for models (tables) and metrics relevant to a question.

Returns the best matches you are allowed to see, ranked. Start here when you do not know which metric or model answers the question.

Inputs: query (required), limit. Returns: hits, catalog_version

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 5 tools

    Disambiguation4/5

    The tools have mostly distinct roles: discovery, schema description, metric listing, governed metric querying, and raw SQL fallback. The only mild overlap is search_models versus list_metrics for finding metrics, but their descriptions clarify ranked search versus full enumeration.

    Naming Consistency5/5

    All names use a consistent snake_case verb_noun pattern: search_models, describe_model, list_metrics, query_metric, run_sql. The convention is predictable and readable throughout.

    Tool Count5/5

    Five tools is well-scoped for a governed warehouse interface: discover models, inspect schemas, list metrics, query metrics, and fall back to SQL. Each tool has a clear place in the workflow.

    Completeness4/5

    The surface covers the core read-only governed analytics lifecycle from discovery through querying, including metric definitions and provenance. A minor gap is the lack of an explicit browse/list-all-models operation separate from search, though search_models likely covers most discovery needs.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • F
      license
      Not graded
      quality
      C
      maintenance
      Model Context Protocol (MCP) server that gives AI assistants a safe, correct data-analyst capability over business metrics - without raw SQL improvisation.
      -
    • A
      license
      Not graded
      quality
      C
      maintenance
      A governed MCP server enabling LLM agents to query BigQuery, inspect GCS, trigger Airflow DAGs, and run data-quality checks with built-in security guardrails like allow-lists, cost ceilings, and audit trails.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A governed analytics MCP server that provides LLM agents with safe, read-only access to data warehouses through a layered safety pipeline including AST validation, column/row governance, PII masking, cost limits, and audit.
      MIT