Skip to main content
Glama
Stateless MCP Server with Registry and Governance

Stateless MCP Server with Registry and Governance

by peda-cos
README.md
# Stateless MCP Server with Registry and Governance

A stateless MCP `2026-07-28` implementation of the capstone
[Stateless MCP Server with Registry and Governance](https://aiengineeringfromscratch.com/learn/capstone-projects/mcp-server-with-registry).
It treats production MCP as a chain of contracts: publishable `server.json`,
live `server/discover`, per-request protocol metadata, resource-bound
authorization, action-bound approvals, policy, redacted audit, and deployment
evidence.

## What is implemented

- **Publication layer:** a schema-shaped `server.json` with a reverse-DNS name,
  concrete version, repository metadata, two Streamable HTTP remotes, and a
  bounded publisher-provided `_meta` extension.
- **Live layer:** `server/discover` advertises the supported revision,
  capabilities, identity, instructions, TTL, and cache scope.
- **Stateless envelope:** every request carries protocol version and client
  capabilities in `params._meta`; every result carries `resultType` and
  `io.modelcontextprotocol/serverInfo`. There is no `initialize`, session,
  `Mcp-Session-Id`, GET stream, DELETE, or `Last-Event-ID` replay.
- **Tool surface:** two read-only tools and one approval-gated state-changing
  tool with bounded input/output schemas, honest annotations, deterministic
  results, and `x-mcp-header` mirroring.
- **Discovery caching:** deterministic sorted `tools/list`, `ttlMs`,
  `cacheScope: "private"`, TTL expiry, and `subscriptions/listen` list-change
  notifications.
- **Authorization:** RS256/JWKS validation on every call, per-role audience,
  issuer, expiry, and scope checks, protected-resource metadata, and
  `WWW-Authenticate` challenges.
- **Policy and approvals:** a second decision over role, tool, scopes, and
  arguments; one-time approvals bound to actor, tool, canonical argument digest,
  resource, environment, and expiry.
- **Shared durable state:** SQLite holds incidents, approvals, idempotency keys,
  and mutation records. Two read replicas and two admin replicas share it.
- **Audit:** append-only redacted JSONL with actor, issuer, audience, resource,
  tool, policy decision, request id, trace id, outcome, and latency. Raw
  arguments and results are never persisted; digests and redacted field names
  are.
- **Deployment proof:** a loopback load balancer, two replicas per role, 100
  concurrent requests, cancellation/timeout/idempotency proof, registry
  admission and drift, and a rollback restoration window.

## Architecture

```mermaid
flowchart LR
  C[Client / evidence harness] --> LB[Loopback load balancer]
  LB -->|/readonly/mcp| RO1[read-only replica 1]
  LB -->|/readonly/mcp| RO2[read-only replica 2]
  LB -->|/admin/mcp| RW1[admin replica 1]
  LB -->|/admin/mcp| RW2[admin replica 2]
  RO1 --> DB[(Shared SQLite)]
  RO2 --> DB
  RW1 --> DB
  RW2 --> DB
  RO1 --> A[Redacted audit JSONL]
  RO2 --> A
  RW1 --> A
  RW2 --> A
  I[Local issuer fixture: metadata, JWKS, token mint] --> RO1
  I --> RW1
  P[server.json] --> R[Private registry adapter]
  R -->|discover + tools probe| LB
  R --> L[Admission ledger]
```

The publication schema is `2025-12-11`; the protocol revision is
`2026-07-28`. They are intentionally different contracts and are validated
separately.

## Quickstart

Prerequisites: Python 3.14 and `uv`. The first sync uses the network; everything
after that runs offline over loopback.

```bash
./verify.sh
uv run mcp-governance evidence --out var/evidence
```

`verify.sh` installs pinned dependencies into `.venv`, runs the 90-test suite,
runs strict `mypy`, regenerates the evidence pack in `var/evidence`, and checks
its digest against the committed `evidence/pack.sha256`.

The committed evidence is in:

- `evidence/evidence-pack.json` — redacted wire, proxy, admission, retry, and
  rollback evidence;
- `evidence/pack.sha256` — digest of the canonical pack;
- `evidence/measurements.json` — the measured concurrency run from this
  workstation.

## Repository layout

- `src/mcp_registry_governance/` — protocol, tools, authorization, policy,
  approvals, SQLite store, audit, HTTP server, proxy, client, admission, and
  evidence harness;
- `fixtures/` — small deterministic incidents, metrics, policy, publisher, and
  candidate publication records;
- `tests/` — 90 unit/integration tests plus the committed-pack check;
- `evidence/` — redacted pack, digest, and measured results;
- `server.json` — publication metadata for both remotes;
- `verify.sh` — install, test, typecheck, regenerate evidence, verify digest.

## Tool surface

| Tool | Kind | Scope | Behavior |
|---|---|---|---|
| `incidents.get` | read-only | `incidents:read` | Reads one seeded incident by `INC-####`; unknown ids are tool errors. |
| `metrics.query` | read-only | `metrics:read` | Returns deterministic fixture metrics for `api`, `worker`, or `scheduler`; mirrors `service` into `Mcp-Param-Service`. |
| `incidents.set_status` | state-changing | `incidents:write` | Acknowledges or resolves an incident. Requires a one-time approval in `params._meta["io.example.mcp/approvalId"]`; `status=resolved` additionally requires `incidents:resolve`; mirrors `ticket` into `Mcp-Param-Ticket`. |

Invalid arguments for a known tool return a complete result with
`isError: true` and `error_code: "invalid_arguments"`; the handler is not
invoked. Unknown tools and malformed call envelopes are JSON-RPC errors.
`tools/list` is sorted, returns `ttlMs: 200` in evidence mode, and always uses
`cacheScope: "private"` because visibility depends on the caller's scopes.

## Wire contract

- `POST /mcp` (or `/readonly/mcp` and `/admin/mcp` behind the proxy).
- Required headers: `MCP-Protocol-Version`, `Mcp-Method`, and `Mcp-Name` for
  `tools/call`. `Mcp-Param-*` values must match the body after Base64-sentinel
  decoding.
- Mismatched mirrored headers return HTTP 400 with `-32020`.
- Missing or non-string protocol metadata returns `-32602`.
- A supplied unsupported version returns HTTP 400 with `-32022` and exactly
  `{"supported": ["2026-07-28"], "requested": "..."}`.
- `Origin`, when present, must name a loopback host; otherwise HTTP 403.
- Accepted notifications return HTTP 202 with no body.
- `GET`/`DELETE` on the MCP endpoint return 405; `Mcp-Session-Id` and
  `Last-Event-ID` are ignored.
- Long-lived list changes use request-scoped SSE; normal calls return one JSON
  object. SSE responses set `X-Accel-Buffering: no`, and the proxy streams
  chunks without buffering.

## Authorization, policy, and approvals

The server validates a Bearer JWT against an issuer-specific JWKS endpoint on
every protected call. Tokens must carry the exact role resource as `aud`, the expected
`iss`, `exp`, `iat`, `sub`, and a space-delimited `scope`. The read-only
resource is `https://readonly.mcp.internal.example/mcp`; the admin resource is
`https://admin.mcp.internal.example/mcp`. A read-only token presented to the
admin surface fails audience validation before any handler runs.

Policy is a second gate:

- `incidents.get` and `metrics.query` require their read scopes.
- `incidents.set_status` requires `incidents:write` plus a valid approval.
- `resolved` additionally requires `incidents:resolve`.
- Disabled tools are hidden from listing and denied on call.
- Policy is evaluated even for idempotent replays; annotations are never used
  for authorization.

Approval records are signed with HMAC-SHA256 over canonical JSON and stored in
SQLite. They bind the actor, tool, canonical argument digest, resource,
environment, expiry, one-time policy, and nonce. Changing even one argument
changes the digest and fails verification before the handler. Approval
consumption, incident mutation, and idempotency recording occur in one
`BEGIN IMMEDIATE` transaction, so concurrent admin replicas cannot consume the
same approval twice or commit duplicate mutations.

## Registry admission and drift

`server.json` publishes both remotes. The admission adapter maps each published
URL to a live loopback URL, then probes `server/discover` and `tools/list`
through the load balancer. It records:

- publisher namespace proof (`example.com` → `com.example`);
- canonical record digest;
- remote/artifact provenance digest;
- live identity and capability observation;
- descriptor pin;
- private Registry status (`active` or `held`);
- an admission-ledger event.

Changing the published remote URL without changing the live server produces an
exact `unmapped_remote` drift and holds the release. The rollback scenario
deploys a partial `1.1.0` candidate, observes a failed admin health window and a
held admission, restores the `1.0.0` routes, verifies a green health window and
live version, and records previous/candidate record and artifact digests plus
the previous descriptor pin.

## Audit

The audit sink is an append-only JSONL file outside tool-visible results. Each
event includes role, replica, request id, trace id, actor, issuer, audience,
resource, tool, policy decision/rule/version, approval id, idempotency key,
idempotent-replay flag, argument digest/keys, redacted field names, result
digest, handler-invocation flag, outcome, error code, and latency. Raw argument
values and results are never written. The evidence pack replaces measured
latency with `<measured>` so its digest remains reproducible.

## Offline boundary and real-provider mode

Everything in `verify.sh` runs offline after the first `uv sync`:

- MCP origins bind `127.0.0.1` and use real loopback HTTP;
- the issuer fixture serves OAuth metadata, a public JWKS, and a local token
  mint;
- the load balancer proxies real HTTP requests;
- Registry probes hit the live loopback deployment;
- SQLite, the audit sink, the ledger, and all fixtures are local.

There is no GPU path: this project trains nothing and runs no model inference.

The production swap points are intentionally narrow:

- point `--issuer` and `--jwks-url` at a real RS256 OIDC provider;
- replace the private registry adapter with an official Registry API client and
  validate the full `server.json` against the pinned official JSON Schema or
  `mcp-publisher`;
- terminate TLS at the ingress and publish real `https://` remotes;
- replace the local append-only audit file with the organization's collector;
- replace the local issuer/token-mint fixture with the real authorization-code
  and client-registration flow. That flow is client-side and is not simulated
  as if it were server evidence.

## Measured results

Measured by `evidence/measurements.json` on the implementation workstation
(Python 3.14.10, loopback only). These are local harness numbers, not a
production capacity claim.

| Measurement | Result |
|---|---:|
| Concurrent requests through the load balancer | 100 |
| Successful requests | 100 / 100 |
| Replica distribution | 50 `readonly-1`, 50 `readonly-2` |
| p50 latency | 26.642 ms |
| p95 latency | 34.365 ms |
| Max latency | 38.322 ms |
| Wall time for 100 requests | 146.72 ms |
| Stable result digests | 2 (one read result, one discovery result) |

The committed pack digest is
`sha256:c06c0d327f0e31d0a14f18d023d6e8c74c9255f74de5b697e71977e96cd98be3`.
`./verify.sh` regenerates the pack and fails if the digest differs, so the
evidence is checked, not just asserted.

## Design decisions

- **RS256/JWKS, not a shared JWT secret.** The resource server fetches public
  keys per issuer. The local fixture exists only to make the JWKS path testable
  offline.
- **No protocol session.** Cross-call state is explicit: approvals and
  idempotency keys are opaque application handles stored in shared SQLite.
- **Private tool-list cache.** The list is filtered by token scopes; sharing it
  behind a public cache would leak tool visibility.
- **Sorted JSON and sorted tools.** Canonical serialization makes byte stability
  and pack reproducibility testable.
- **One transaction for approval + mutation + idempotency.** This is the
  correctness core for horizontal replicas.
- **Application-defined auth codes.** `-31001` and `-31003` sit outside the
  JSON-RPC/MCP reserved sub-ranges; protocol-standard codes are used only for
  their specified meanings.
- **Bounded schema validator.** The repository validates only the JSON Schema
  keywords it uses and fails on unknown validation keywords instead of silently
  ignoring them.
- **Redaction by digest.** Audit never stores raw arguments or results; evidence
  adds a separate explicit redaction probe.

## Limitations

- Loopback plain HTTP; TLS and network ingress policy are deployment concerns.
- The local issuer fixture is not a full OAuth authorization server and does not
  implement client registration or the authorization-code browser flow.
- `validate_registry_document` is the capstone's partial remote-profile
  validator, not full official-schema validation. Use the pinned official schema
  or `mcp-publisher` before real publication.
- The private registry adapter is local; it is not an official Registry
  publication.
- Policy is an in-process JSON engine, not OPA/Rego.
- The audit sink is a local append-only file, not WORM storage or a remote
  collector.
- Rate limiting is per replica, not a global shared quota.
- Read-only and admin roles have separate audiences, replicas, policies, and
  credentials, but share the SQLite deployment and audit sink rather than fully
  independent blast-radius domains.
- No MCP SDK differential test is included; the evidence is raw HTTP against the
  shipped `mcp-governance serve` entry point.

## Tests

`python -m unittest discover -s tests -v` runs 90 tests covering canonical
serialization, bounded schema validation, publication namespace and drift,
envelope precedence, header mirroring, JWT/JWKS failure modes, policy,
approvals, SQLite atomicity, audit redaction, cache expiry/list change, HTTP
negatives, cancellation, 100-request concurrency, concurrent replay, admission,
and the committed evidence pack.

## References

1. MCP `2026-07-28` key changes — https://modelcontextprotocol.io/specification/2026-07-28/changelog
2. MCP Streamable HTTP — https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http
3. MCP server discovery — https://modelcontextprotocol.io/specification/2026-07-28/server/discover
4. MCP authorization — https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization
5. Official Registry `server.json` requirements — https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/server-json/official-registry-requirements.md
6. AI Engineering From Scratch, [Stateless MCP Server with Registry and Governance capstone](https://aiengineeringfromscratch.com/learn/capstone-projects/mcp-server-with-registry) — spec, architecture, and evaluation rubric.