govlake
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@govlake how many encounters per month did we have in 2024?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
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 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.
docker compose up --build -d --wait && docker compose exec govlake python -m govlake.smokeThat 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:
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 421See it
Replay a recorded session. 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 demore-records it.Red-team report. 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 redteamreruns it.
Related MCP server: Lagaam
Connect an agent
With the container running, add it to Claude Code:
claude mcp add --transport http govlake http://127.0.0.1:8000/mcpThe 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 |
| Aggregate metrics only. No patient-level rows. | All organizations |
| Aggregates plus the | Only rows for their own organization |
| 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_metricslists the metrics and datasets this role may query. For datasets, it also shows how each column comes back:none,initial,year,zip3,pseudonymizeorforbidden.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. Onlyauditorcan use it.healthreports 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_FORBIDDENand 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
auditorcan read it, throughread_audit. Every read is itself audited.
Request pipeline
Every request passes through these stages in order:
Principal.
Resolve the question to a target.
Authorize against role, row and column policy.
Compile SQL, with masks applied in the SQL.
Static check against the sqlglot AST allow-list.
Cost estimate from table size and EXPLAIN.
Execute with a time limit.
Pseudonymize IDs and suppress small cells.
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 |
| Identity, and correlation with the span |
| Who asked, and through which tool |
| The question as asked, truncated to 2,000 characters |
| What the server decided was meant: target, dimensions, columns, grain, year |
| The exact SQL that ran or was rejected, and its bound parameters |
| The governance that was applied |
| Cost and size |
|
|
| 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
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 --> AModule | Job |
| The contract: metrics, datasets, synonyms, roles, column masks and row scope |
| Maps a question to one target by longest synonym match. No LLM. An ambiguous or unknown question runs nothing |
| Turns a request and a principal into a plan, or a denial with a reason code |
| Writes the only SQL that ever runs, with masks and row filters built in and values as parameters |
| Checks that SQL independently, estimates its cost, and enforces the timeout |
| Reads Iceberg tables into a locked-down, in-memory DuckDB with no file, network or extension access |
| Run the pipeline and write the audit event and the span, failing closed |
| Serve the MCP tools over stdio or streamable HTTP, with DNS-rebinding protection |
| 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_UNAVAILABLEand 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 asclaims_paid_amount,pmpm_costand 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_KEYis 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, plus Docker for the container targets.
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 dependenciesDependencies 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.
Available Tools
6 toolsaskA
Ask a plain-English question about a defined metric or dataset, e.g. 'How many encounters per month in 2025 by payer?'. The server maps it to a definition, applies your role's rules, generates SQL itself, and returns the SQL, the result, any masking applied, and an audit id. Denials include a reason_code.
Inputs: question (required). Returns: sql, kind, rows, grain, +13 more
describe_metricB
Describe one metric or dataset your role may query.
Inputs: name (required). Returns: result
healthA
Report that the server is up, and its version.
Inputs: no named parameters. Returns: status, version
list_metricsA
List the metrics and datasets your role may query, with their dimensions, grains and columns. Dataset columns show how each is returned (e.g. 'initial', 'year', 'forbidden').
Inputs: no named parameters. Returns: role, definitions
query_metricA
Structured form of ask: name a metric or dataset from list_metrics, plus dimensions (metrics), columns (datasets), an optional grain and year.
Inputs: name (required), year, grain, columns, +1 more. Returns: sql, kind, rows, grain, +13 more
read_auditA
Auditor role only: the most recent audit events (newest last) and whether the audit log's hash chain is intact. Reading the log is itself audited.
Inputs: limit. Returns: events, message, outcome, reason_code, +4 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
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.
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.
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.
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
Related MCP Connectors
The grounded data layer for any LLM: governed SQL, metrics, lineage and catalog over your data.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Governed SQL access to your databases: redaction, query review and an audit log.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to query governed data warehouses through plain language, returning grounded answers with SQL, confidence grades, and signed receipts while enforcing access, testing, and audit controls.18Apache 2.0
- AlicenseAqualityBmaintenanceEnables AI agents to query Trino and Apache Pinot lakehouses under enforced governance, where every SQL statement is AST-validated, table-allowlisted, priced from the engine's own plan before it runs, and blocked or admitted against scan-byte and intermediate-row budgets. It also grounds agents with schema discovery tools, returns verified results with warnings instead of misleading answers, and records every tool call on an audit trail.31Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to query DuckDB, Postgres, and BigQuery through a governed, read-only layer with a semantic model, SQL guard, role-based row policies, PII pseudonymization, audit logging, and cost caps.68 PyPIMIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to run SQL analytics against healthcare claims through a de-identified mart, with privacy enforced inside the database engine — small-cell suppression, read-only authorization, resource budgets, and a tamper-evident audit log — so agents can answer questions about denial rates and costs without ever touching PHI.MIT