Skip to main content
Glama
governed_mcp
by alez0101
README.md
# nexus-governed-mcp

A governed, read-only [MCP](https://modelcontextprotocol.io/) server over [DeepLynx Nexus](https://github.com/idaholab/DeepLynx), Idaho National Laboratory's open-source digital thread platform. It lets an LLM agent trace requirements to components to tests, and read sensor data, without seeing records its role isn't cleared for.

All data here is synthetic: a fictional reactor's component cooling water system. This is a portfolio project, not affiliated with INL.

## What it enforces

```mermaid
flowchart TD
    A[LLM agent] -- "stdio MCP<br/>bearer token" --> S

    subgraph S [governed_mcp]
      P1["1 authenticate<br/>sha256(token) to role"] --> P2["2 authorize<br/>role tool allowlist"]
      P2 --> P3["3 validate<br/>typed, bounded args"]
      P3 --> C["4 fetch<br/>allowlisted read ops only"]
      C --> G["5 gate<br/>record labels within role clearance"]
      G --> E["6 egress scan<br/>no uncleared ID or canary"]
      E --> L["7 audit<br/>append-only JSONL"]
    end

    C -- "HS256 token for the<br/>role's read-only account" --> N["DeepLynx Nexus 0.8.0<br/>sensitivity labels enforced"]
    N --> D[(Postgres)]
```

- **Six typed tools, no query passthrough:** `find_component`, `get_record`, `get_requirement`, `trace_requirement`, `get_relationships`, `get_timeseries`.
- **Record-level classification, checked twice.** Each role maps to a Nexus account with matching sensitivity-label grants, and `policy.py` re-checks every record's labels independently. The second layer exists because one Nexus endpoint doesn't apply labels ([docs/nexus-findings.md](docs/nexus-findings.md)). The server refuses to start if its Nexus account can read labels the role may not.
- **Uniform denials.** A hidden record and a nonexistent one return byte-identical errors. Withheld counts go to the audit log, never to the agent.
- **Bounded everything:** result caps, query length and charset, a 6-hour timeseries window, and a point cap.
- **Audit:** one JSONL line per call with role, redacted args, result, and every record ID returned.

## Results

| | |
|---|---|
| `validate.py` | **81/81** checks, including 35 denial paths, a leak sweep across every record as every role, and a policy-only run with Nexus deliberately misconfigured (55 labeled records withheld by `policy.py` alone, 0 leaks) |
| Evals, deterministic tier | 20/20 correct, 0 leaks |
| Evals, agent via `claude -p` (Claude Opus 5.5) | 20/20 correct, 0 leaks |
| Evals, agent via Anthropic API (Claude Opus 5.5) | 20/20 correct, 0 leaks (about $0.82 for the run) |

Full results, per-question detail, and the one issue the evals surfaced (the model inferring hidden IDs from numbering gaps) are in [reports/RESULTS.md](reports/RESULTS.md). Design decisions and rejected designs are in [docs/design.md](docs/design.md). A short write-up is in [docs/writeup.md](docs/writeup.md).

## Repository layout

| Path | What it is |
|---|---|
| `governed_mcp/` | The MCP server: `policy.py` (chokepoint), `tools.py`, `nexus_client.py` (allowlisted reads), `audit.py`, `server.py` |
| `config/roles.toml` | Roles, label clearances, tool allowlists, limits |
| `nexus/` | Pinned Nexus build (our Dockerfiles, compose, env template) |
| `data/` | Synthetic dataset generator and generated data |
| `scripts/` | Fetch, secrets, bootstrap, seed, label probe, token issuer, report |
| `validate.py` | Validation harness |
| `evals/` | Eval cases and three-tier runner |
| `ci/e2e.sh`, `.gitlab-ci.yml` | End-to-end pipeline |
| `reports/` | Latest validation and eval results |

## Requirements

- Linux or macOS with Docker Engine and Docker Compose v2
- About 6 GB of free RAM for the image builds (the running stack uses about 250 MB)
- `git`, `openssl`, `curl`, `python3`

## 1. Run Nexus locally

Nexus has no published container images, so the stack builds from upstream source at a pinned commit.

| Component | Pin |
|---|---|
| DeepLynx Nexus | tag `0.8.0`, commit `7a3e359421245b4d84d8fc5c5da5fd681fcdd4c9` |
| Postgres + pgvector | `pgvector/pgvector:0.8.3-pg18` (digest-pinned) |
| .NET build / runtime | `dotnet/sdk:10.0.302`, `dotnet/aspnet:10.0.11` (digest-pinned) |
| Node (UI) | `node:22.23.5-alpine` (digest-pinned) |

```bash
# 1. Fetch upstream source into nexus/src and verify the pinned commit
scripts/fetch-nexus.sh

# 2. Generate nexus/.env with fresh random secrets (gitignored, mode 600)
scripts/gen-secrets.sh

# 3. Build and start Postgres + the API (real auth is on by default)
docker compose -f nexus/compose.yaml up -d --build db server

# 4. Optional: the web UI on http://localhost:3000 (see the auth note below)
docker compose -f nexus/compose.yaml --profile ui up -d --build ui
```

The first start applies the database migrations. The API listens on `http://127.0.0.1:5000`, and the interactive API reference is at `http://127.0.0.1:5000/api/scalar`. Ports bind to localhost only. Set `NEXUS_BIND` in `nexus/.env` to change that.

Check it:

```bash
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5000/api/v2/users/current   # 401 = auth is enforced
```

### Why our own Dockerfiles

`nexus/Dockerfile.server` and `nexus/Dockerfile.ui` build from the upstream source but differ from upstream's `Dockerfiles/*.local`:

- Base images are pinned by digest, not by floating tag.
- The `.local` images download INL's internal root CA over plain HTTP and add it to the trust store. That's only needed inside INL's network, so ours skip it (upstream's `.public` variants also skip it).
- The server publishes only `deeplynx.api`, not the whole solution including tests.
- Both run as non-root users.
- Upstream's compose hardcodes development secrets. Ours read every secret from `nexus/.env`.

Not included: the optional Insight LLM services (their submodule lives on INL's internal Git server), the docs site, and upstream's bundled C# MCP server.

## 2. Authentication

Nexus accepts HS256 JWTs it issues itself. An API key plus secret goes to `POST /api/v2/oauth/tokens` and comes back as a short-lived bearer token. No Okta is needed.

Upstream's development flag `DISABLE_BACKEND_AUTHENTICATION=true` **fails open**. A request with no token, or with a token that fails validation, runs as a SysAdmin "Local Developer". This repo keeps it off. It goes on only for the one-time bootstrap that creates the accounts and keys:

```bash
NEXUS_AUTH_BYPASS=true docker compose -f nexus/compose.yaml up -d server   # bootstrap only
python scripts/bootstrap.py                                                # accounts, labels, keys
docker compose -f nexus/compose.yaml up -d server                          # back to real auth
```

Observed behavior with real auth on (Nexus 0.8.0):

| Request | Result |
|---|---|
| No token | 401 |
| Valid token from an API key | 200 |
| Tampered signature | 401 |
| Malformed token (`abc.def.ghi`) | 500. Denied, but the status code is wrong |
| Non-admin calling a SysAdmin endpoint | 403 |

The UI is built with frontend auth disabled, so it only shows data while the API is in bypass mode. Treat it as a bootstrap and screenshot tool, not a governed surface. Two gotchas:

- Open it as `http://localhost:3000`, not `127.0.0.1`. The API's CORS policy only allows the `localhost` origin.
- Auth.js refuses to start without an Okta issuer, even with frontend auth disabled. The compose file gives it `https://okta.invalid`, a reserved name that can never resolve.

![Nexus UI running locally](docs/img/nexus-ui-home.png)

## 3. Seed the synthetic dataset

`data/dataset.py` defines a small digital thread for the Component Cooling Water (CCW) system of a fictional reactor, "Kestrel-1". Every name, number, vendor, and result in it is invented.

| | Count |
|---|---|
| Requirements, components, parts, vendors, test records, sensors | 12, 10, 12, 7, 12, 4 |
| Edges (`derived_from`, `allocated_to`, `contains`, `supplied_by`, `verifies`, `performed_on`, `monitors`) | 95 |
| Timeseries files (24 h at 60 s, with a pump trip at 14:20 UTC) | 4 |
| Records labeled `EXPORT-CONTROLLED` / `VENDOR-PROPRIETARY` / both | 6 / 5 / 1, plus one labeled sensor file |

Classification uses Nexus's own sensitivity labels. Every labeled record also carries a unique `CANARY-<id>` string in its properties, so a leak shows up as a plain text match.

```bash
python3 -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python data/dataset.py      # regenerates data/dataset.json and data/timeseries/*.csv
scripts/reset-and-seed.sh             # wipe, bootstrap (bypass), real auth, load through the REST API
```

`reset-and-seed.sh` creates one Nexus account per access level. Nexus enforces each account's label grants, and the MCP server (Phase 3) maps a caller's role to one of these accounts:

| Account | Project role | Label grants |
|---|---|---|
| `seed-loader` | project admin | both labels, all actions (loads data only) |
| `mcp-engineer` | Reader (read-only) | none |
| `mcp-ec` | Reader | `EXPORT-CONTROLLED`: read record, download file |
| `mcp-supply-chain` | Reader | `VENDOR-PROPRIETARY`: read record, download file |
| `mcp-lead` | Reader | both labels: read record, download file |

API keys land in `secrets/nexus-identities.json` (gitignored, mode 600). Loading uses only Nexus's ingestion endpoints (bulk records with labels, bulk edges, file upload). There are no direct database writes, and the loader reads every record back to verify its labels.

What Nexus enforces on its own, and the one endpoint where it doesn't, is in [docs/nexus-findings.md](docs/nexus-findings.md).

## 4. Run the governed MCP server

```bash
.venv/bin/python scripts/issue_caller_token.py engineer     # prints a token once; stores only its sha256
GOVERNED_MCP_TOKEN=<token> .venv/bin/python -m governed_mcp  # stdio MCP server
```

Roles are defined in [config/roles.toml](config/roles.toml): `engineer`, `ec_authorized`, `supply_chain`, `lead`. Each maps to one Nexus account, a set of allowed labels, and a tool allowlist.

| Tool | What it does |
|---|---|
| `find_component(query, limit)` | Components by name, tag, or ID |
| `get_record(record_id)` | One record of any type, with properties and classification |
| `get_requirement(requirement_id)` | Requirement text, attributes, parent and derived requirements |
| `trace_requirement(requirement_id)` | Requirement → allocated components → verifying tests, with coverage status |
| `get_relationships(record_id, direction, relationship, limit)` | Related records, filtered by relationship type |
| `get_timeseries(sensor_id, start, end, max_points)` | Sensor readings for a window of 6 h or less: stats over the full window plus downsampled points |

Every call is logged to `audit/audit.jsonl`:

```json
{"ts": 1795460523.524, "id": "04411e01...", "tool": "get_relationships", "role": "lead", "result": "ok",
 "args": {"record_id": "CMP-CCW-RM01", "direction": "incoming", "relationship": null, "limit": 25},
 "record_ids": ["CMP-CCW-RM01", "REQ-CCW-006", "REQ-CCW-009", "TST-006", "TST-012"], "withheld": 0, "duration_ms": 97}
```

How the policy layer works, and the designs considered and rejected, are in [docs/design.md](docs/design.md).

To use it from Claude Code or another MCP client, register a stdio server with command `.venv/bin/python -m governed_mcp`, working directory set to this repo, and `GOVERNED_MCP_TOKEN` in its environment.

## 5. Validate and evaluate

```bash
.venv/bin/python scripts/issue_caller_token.py --dev-all    # one token per role for the harness (secrets/dev-callers.json)
.venv/bin/python validate.py                                # 81 checks; exit 0 only if all pass
.venv/bin/python evals/run_evals.py --tier deterministic    # no model, no key
.venv/bin/python evals/run_evals.py --tier claude-cli       # agent via `claude -p` on a Claude subscription
.venv/bin/python evals/run_evals.py --tier api              # agent via the Anthropic API (needs ANTHROPIC_API_KEY)
.venv/bin/python scripts/make_report.py                     # reports/RESULTS.md
```

`validate.py` drives the real server over stdio against the seeded stack:
- **Protocol:** exactly six read-only tools, none taking a free-form query.
- **Denials:** 35 checks covering no token, unknown token, tools outside a role's allowlist, injection-shaped and out-of-bounds arguments, and hidden records. Hidden and nonexistent records must return byte-identical errors.
- **Leak battery:** every record, relationship, and trace, as each role, plus a positive control showing each role does see the labeled records it's cleared for.
- **Policy layer alone:** the engineer role is wired to the lead's Nexus account. The server must refuse to start. With a test override, `policy.py` alone must withhold every labeled record.
- **Also:** token revocation without a restart, egress-scan unit checks, audit log integrity (one line per call, no secrets, no record contents), and non-admin runtime accounts.

The eval set ([evals/cases.json](evals/cases.json)) has 20 questions across the four roles: lookups, traces, supply chain, timeseries, refusals, and one prompt-injection attempt. Leakage is scored two ways, by text and by the server's own audit log, and the scorer checks itself against planted leaks before every run.

## 6. CI

[.gitlab-ci.yml](.gitlab-ci.yml) has three jobs:

| Job | What it does |
|---|---|
| `lint` | `ruff check .` |
| `e2e` | In Docker-in-Docker: builds Nexus from the pinned source, bootstraps and seeds it through the REST API, runs `validate.py` and the deterministic eval tier. Reports are saved as artifacts. |
| `eval-api` | The same stack plus the Anthropic API agent tier. Manual, and only offered when a masked `ANTHROPIC_API_KEY` CI/CD variable exists. |

Both stack jobs call [ci/e2e.sh](ci/e2e.sh), which also runs locally: `BUILD_FLAGS=--no-cache ci/e2e.sh`. Note that it resets the local stack.

## 7. Reset

```bash
docker compose -f nexus/compose.yaml --profile ui down -v   # removes the database and file-storage volumes
```

## License

MIT. See [LICENSE](LICENSE). DeepLynx Nexus is a separate MIT-licensed project by Battelle Energy Alliance; this repo fetches it at build time and does not redistribute it.