Skip to main content
Glama
README.md
# governed-lakehouse-mcp

**AI agents are being pointed at clinical and claims data. The easy way to do it is a database
connection and a model that writes SQL, and that gives the agent everything the connection can read.** One
prompt-injected document or one confidently wrong query can pull names, birth dates and SSNs into a chat
window. Afterwards nobody can say exactly what the agent saw, who it was acting for, or why it was allowed.

This project takes the other approach: a governed data layer between the agent and the lakehouse,
built as an [MCP](https://modelcontextprotocol.io) server in Python. The agent asks in words or
through a structured tool. The server decides which defined metric or dataset that means and writes the SQL
itself. It applies the caller's row and column policy, masks identifiers inside the query, and refuses
anything it can't bound. It writes one tamper-evident audit entry for every data request, including refused
ones.

- **Stack:** Apache Iceberg tables (PyIceberg with a SQLite catalog), DuckDB, a small YAML semantic layer
  for metric definitions, sqlglot for static SQL checks, and OpenTelemetry for spans.
- **Data:** synthetic only. 500 patients and about 3,200 encounters with payer and claim-cost fields,
  generated in-process using Synthea's CSV column names. No real data is used, and nothing from any
  employer.

```sh
docker compose up --build -d --wait && docker compose exec govlake python -m govlake.smoke
```

That command builds the image, seeds the synthetic lakehouse on first start, serves MCP on
`127.0.0.1:8000`, and makes real MCP calls against it:

```text
ok: health -> {'status': 'ok', 'version': '0.1.0'}
ok: list_metrics as population_analyst -> ['encounter_count']
ok: ask -> 12 rows, 0 suppressed, cost 3182, audit b15d8288-...
    sql: SELECT CAST(date_trunc('month', "start") AS DATE) AS "month", COUNT(*) AS "encounter_count", ...
ok: ask {'question': 'list patients'} -> denied ROLE_FORBIDDEN, audit e0c1145a-...
ok: query_metric {'name': 'patient_roster', 'columns': ['ssn']} -> denied ROLE_FORBIDDEN, audit 8a10450d-...
ok: forged Host rejected with HTTP 421
```

## See it

- **[Replay a recorded session](docs/demo/index.html).** Eight steps as three roles. For each request it
  shows the question, the SQL the server generated, what was masked or refused, and the audit entry it
  left. The hash chain is drawn as linked slips. It is one self-contained HTML file with no network
  requests: open it in a browser or host it anywhere (GitHub shows its source rather than the page).
  `make demo` re-records it.
- **[Red-team report](docs/redteam-report.md).** 38 attacks: prompt injection, forbidden and masked
  columns, role escalation, malformed calls and runaway queries. Each is blocked or neutralized, logged
  once, and leaks nothing. `make redteam` reruns it.

## Connect an agent

With the container running, add it to Claude Code:

```sh
claude mcp add --transport http govlake http://127.0.0.1:8000/mcp
```

The server acts as the role in `GOVLAKE_ROLE` (default `population_analyst`). To try another role, copy
`.env.example` to `.env`. Set `GOVLAKE_ROLE=care_coordinator` and `GOVLAKE_ORG=org-riverbend`, or set
`GOVLAKE_ROLE=auditor`. Then run `docker compose up -d`. As the coordinator, `list patients` returns rows
like `['p_74b4fb63d26bcfd3', 'S.', 'O.', 1991, 'F', '024**']`.

To run without Docker over stdio, run `make install && make seed`, then register the server:
`claude mcp add govlake -- uv run --directory <repo> govlake serve`.

## Spec: what an agent can and can't do

### Principals and roles
Every request carries a principal: `user_id`, `role`, and `organization` for row-scoped roles. The demo
takes it from server config (`GOVLAKE_ROLE`, `GOVLAKE_ORG`). Production identity is out of scope (see
Limitations).

| Role | Sees | Row scope |
|---|---|---|
| `population_analyst` | Aggregate metrics only. No patient-level rows. | All organizations |
| `care_coordinator` | Aggregates plus the `patient_roster` dataset, identifiers masked | Only rows for their own organization |
| `auditor` | The audit log only. No clinical or claims data. | n/a |

### What an agent can ask
The agent never sends SQL. It has six tools:

- `list_metrics` lists the metrics and datasets this role may query. For datasets, it also shows how each
  column comes back: `none`, `initial`, `year`, `zip3`, `pseudonymize` or `forbidden`.
- `describe_metric(name)` describes one of them.
- `ask(question)` takes a plain-English question. Using synonyms from the YAML semantic layer, the server
  resolves it to **one defined metric or dataset**, plus dimensions or columns, a grain and a year. If
  nothing matches with confidence, it returns the closest candidates and runs nothing.
- `query_metric(name, dimensions, columns, grain, year)` is the structured form of the same request.
- `read_audit(limit)` returns recent audit events and whether the hash chain is intact. Only `auditor` can
  use it.
- `health` reports the server version.

Defined today: the `encounter_count` metric (dimensions `encounter_class` and `payer`; grains `month` and
`year`) and the `patient_roster` dataset. Planned as the semantic layer grows: `member_count`,
`claims_paid_amount`, `pmpm_cost`, `er_visit_rate` and `readmission_rate_30d`, with `age_band`,
`condition_category` and `claim_type` dimensions.

### What an agent can never see
- **Direct identifiers**, modelled on the HIPAA Safe Harbor list: name, SSN, driver's licence, passport,
  street address, city, ZIP beyond the first 3 digits, phone, email, full birth date, and raw MRN or member
  ID.
  - Names come back as initials, birth dates as years, ZIPs as their first 3 digits, and IDs as keyed HMAC
    tokens.
  - SSN, street address and city are never returned. Asking for them is denied with `COLUMN_FORBIDDEN` and
    logged.
- **Small cells.** An aggregate cell drawn from fewer than 11 patients is suppressed. This follows the
  common CMS small-cell rule.
- **Free-form SQL.** Agents can't send SQL at all. The server's own SQL is checked again against an AST
  allow-list before it runs. That rules out `SELECT *`, joins, subqueries, unions, DDL, DML, table functions
  and extra statements. DuckDB runs in memory, with external access, extension loading and configuration
  changes locked.
- **Rows outside the principal's scope.** The server adds row filters as bound parameters. The agent can't
  group or filter on the scoping column, and the static check refuses SQL without the filter.
- **Expensive queries.**
  - A request is rejected before it runs if its estimated rows touched exceed `GOVLAKE_MAX_SCAN_ROWS`
    (default 10 million).
  - A running query is stopped after `GOVLAKE_QUERY_TIMEOUT_S` (default 5 seconds).
  - Results are capped at 1,000 rows.
- **The audit log.** Only `auditor` can read it, through `read_audit`. Every read is itself audited.

### Request pipeline
Every request passes through these stages in order:

1. Principal.
2. Resolve the question to a target.
3. Authorize against role, row and column policy.
4. Compile SQL, with masks applied in the SQL.
5. Static check against the sqlglot AST allow-list.
6. Cost estimate from table size and EXPLAIN.
7. Execute with a time limit.
8. Pseudonymize IDs and suppress small cells.
9. Write the audit event and the OpenTelemetry span.

Every stage can deny the request. A denial returns no data and a stable reason code: `METRIC_NOT_FOUND`,
`INVALID_REQUEST`, `ROLE_FORBIDDEN`, `COLUMN_FORBIDDEN`, `SQL_REJECTED`, `COST_EXCEEDED` or
`QUERY_TIMEOUT`. Calls the MCP layer rejects before governance runs, such as malformed arguments or unknown
tools, are logged as `INVALID_REQUEST` or `UNKNOWN_TOOL`. Failures return `INTERNAL_ERROR` without
revealing internals. If the audit event can't be written, the answer is withheld and the request returns
`AUDIT_UNAVAILABLE`.

### What gets logged
One audit event is written for **every** data request, audit read and refused tool call, whether it was
allowed, denied or errored.
- **The audit log.** Events go to an append-only, hash-chained `audit.jsonl`, which is the record of
  truth.
- **Spans.** Each request is also an OpenTelemetry span carrying the same facts. Spans are written to
  `spans.jsonl`, never to stdout, and optionally sent to an OTLP collector. The span and the event
  reference each other.

| Field | Content |
|---|---|
| `event_id`, `timestamp`, `trace_id`, `span_id` | Identity, and correlation with the span |
| `user_id`, `role`, `organization`, `tool` | Who asked, and through which tool |
| `question` | The question as asked, truncated to 2,000 characters |
| `request`, `resolved_target` | What the server decided was meant: target, dimensions, columns, grain, year |
| `generated_sql`, `sql_params` | The exact SQL that ran or was rejected, and its bound parameters |
| `row_filters_applied`, `masked_columns`, `suppressed_cells` | The governance that was applied |
| `cost_estimate`, `rows_returned`, `duration_ms` | Cost and size |
| `outcome`, `reason_code` | `allowed`, `denied` or `error`, and the reason |
| `policy_version`, `prev_hash` | A fingerprint of the policy and semantic files, and the previous event's hash, which together make the chain tamper-evident |

**Result values are never logged,** in either the audit log or the spans. Neither is the pseudonym key.
Only shapes and counts are logged.

### Non-goals
- This is not a certified HIPAA-compliant system. It demonstrates the controls; it does not replace a
  compliance program.
- Authentication is out of scope. The demo trusts its configured principal.
- There are no writes, no ad-hoc exploration, and no LLM inside the server. Language understanding stays
  with the agent, and the server stays deterministic and testable.

## Architecture

```mermaid
flowchart LR
    A[Agent] -- MCP tool call --> M[Middleware: audit refused calls]
    M --> R[Resolve question to one metric or dataset]
    R --> Z[Authorize: role, row scope, column masks]
    Z --> C[Compile parameterized SQL, masks in SQL]
    C --> G[Static check: sqlglot allow-list]
    G --> E[Cost estimate: table size and EXPLAIN]
    E --> X[Execute in DuckDB with a time limit]
    I[(Iceberg tables)] --> X
    X --> P[Pseudonymize IDs, suppress cells under 11]
    P --> L[(Hash-chained audit.jsonl and OTel span)]
    L --> A
```

| Module | Job |
|---|---|
| `semantic/metrics.yaml`, `semantic/policy.yaml` | The contract: metrics, datasets, synonyms, roles, column masks and row scope |
| `resolver.py` | Maps a question to one target by longest synonym match. No LLM. An ambiguous or unknown question runs nothing |
| `governance.py` | Turns a request and a principal into a plan, or a denial with a reason code |
| `compiler.py` | Writes the only SQL that ever runs, with masks and row filters built in and values as parameters |
| `guard.py` | Checks that SQL independently, estimates its cost, and enforces the timeout |
| `lakehouse.py` | Reads Iceberg tables into a locked-down, in-memory DuckDB with no file, network or extension access |
| `service.py`, `audit.py`, `telemetry.py` | Run the pipeline and write the audit event and the span, failing closed |
| `server.py`, `cli.py` | Serve the MCP tools over stdio or streamable HTTP, with DNS-rebinding protection |
| `redteam.py`, `demo.py`, `smoke.py` | The attack corpus, the recorded demo, and the container check |

Design choices worth knowing:

- **The agent never writes SQL.** Language understanding stays with the agent. The server is
  deterministic, so each control in the spec has tests that try to break it. A hostile question can at worst
  resolve to a metric the caller was already allowed to query.
- **Two independent locks.** Policy decides what to compile. Then a separate AST allow-list checks the
  compiled SQL against the plan and the policy, so a compiler bug has to get past both.
- **Masks run inside the query.** Raw names, birth dates and ZIPs never leave DuckDB. Patient IDs are
  replaced with keyed HMAC tokens after the query runs, so the key never appears in SQL or in logs.
- **Audit first, answer second.** If the audit event can't be written, the caller gets
  `AUDIT_UNAVAILABLE` and no data. The JSONL log is the record of truth. Spans carry the same facts so
  they fit into whatever observability stack is already in place.

## Limitations

- **Authentication is out of scope.** The server trusts the principal it was configured with. A real
  deployment needs identity from the MCP client (OAuth) mapped to roles. Here, one server instance per role
  stands in for that.
- **The semantic layer is small.** It has one metric (`encounter_count`) and one dataset
  (`patient_roster`). Claims metrics such as `claims_paid_amount`, `pmpm_cost` and readmission rates are
  designed for but not built.
- **The resolver uses keyword matching.** It is predictable and safe, not clever. For a paraphrase it
  doesn't know, it returns candidates instead of an answer, and agents are expected to fall back to
  `query_metric`.
- **Differencing defeats small-cell suppression.** Subtracting the visible cells from a total can recover
  a suppressed count, because there is no complementary suppression. A strict xfail test records this.
- **Deleting the newest audit entries is not detected.** The hash chain catches edits and removals in the
  middle of the log, but not truncation at the end. Catching that needs the latest hash stored somewhere
  outside the log. A strict xfail test records this too.
- **One audit writer per log.** Two server processes sharing an audit file would fork the chain.
- **No rate limiting.** Floods of requests are fully audited, and each query is bounded, but nothing
  throttles them.
- **Demo scale.** Tables are copied into memory for each connection. The Iceberg catalog is local SQLite
  with a file warehouse. The cost cap is a guard, not a query planner.
- **Pseudonyms change on restart** unless `GOVLAKE_PSEUDONYM_KEY` is set.
- **Not a compliance certification.** The controls are modelled on HIPAA Safe Harbor and the CMS
  small-cell rule. They demonstrate the approach; they don't replace a compliance program.

## Development

You need [uv](https://docs.astral.sh/uv/), plus Docker for the container targets.

```sh
make install   # .venv from uv.lock, plus git hooks (ruff, mypy, gitleaks, lockfile check)
make check     # ruff, mypy --strict, pytest with coverage (fails under 85%)
make audit     # pip-audit over the locked dependencies
```

Dependencies are pinned to exact versions and locked. On every push, the GitHub Actions workflow runs
lint, type checks, tests, the pre-commit hooks, the dependency audit and the Docker smoke test. Its
actions are pinned to commit SHAs. `make help` lists every target.

Released under the MIT License.

TDQS

A3.7/5.0

Scored across 6 tools

Disambiguation4/5

Most tools target clearly separate concerns (health, discovery via list_metrics/describe_metric, querying, auditing). The only real overlap is between ask and query_metric, but the descriptions explicitly frame query_metric as the 'structured form of ask', which gives an agent a usable decision rule. Minor residual risk that an agent picks the NL path when structured parameters were intended.

Naming Consistency4/5

Four of six tools follow a clean verb_noun snake_case pattern (list_metrics, describe_metric, query_metric, read_audit). Deviations are 'health' (bare noun) and 'ask' (bare verb), which are conventional and readable but break the pattern. No style mixing such as camelCase, so the set stays predictable.

Tool Count5/5

Six tools is well-scoped for a governed metric-query server: exactly one liveness probe, two discovery tools, two query entry points, and one audit tool. Every tool earns its place with no redundant entries. Nothing feels thin given the narrow, governance-focused domain.

Completeness4/5

The surface covers the full lifecycle an agent needs: connectivity check, metric discovery, metric description, two query paths, and audit verification including hash-chain integrity. Gaps are small — no pagination/limit controls on results, and read_audit only exposes the most recent events rather than filtering or time ranges. Agents can work around these, but they are real limitations.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues