MCP Healthcare Reference
Modules · FunctionalModules · TechnicalOverall · FunctionalOverall · Technical
Verified module guide · Technical view

Source-level module walkthrough

Implementation details for every active code/configuration area: entry points, data structures, endpoints, validation boundaries, persistence, concurrency, deployment behavior, tests, and known accuracy limitations.

Five upstream identity sources normalizing through the Keycloak hub into one canonical JWT

Five upstream identities normalize to one canonical JWT.

This page documents what the source does now. It does not silently promote target architecture statements into implemented behavior. File paths cite the project's public source repository — they are provenance, not links. Generated data, local secrets, certificates, caches, lockfiles, and compiled output are runtime artifacts rather than functional modules.

Implementation baseline

MCP runtime

Both servers use @modelcontextprotocol/server 2.x with /express and /node, Express 5, Zod 4, and JOSE 6. createMcpHandler builds a fresh McpServer per request and serves MCP 2026-07-28 natively (server/discover, per-request _meta, Mcp-Method/Mcp-Name headers, no initialize, no sessions).

Clients that still speak 2025-11-25 are served by the SDK’s stateless legacy fallback from the same factory (updated 2026-09-30).

OAuth runtime

Keycloak 26.7 is the hub. Resource servers validate JWTs using remote JWKS, pin algorithms to PS256/ES256, check issuer and resource audience, and publish RFC 9728-shaped metadata.

The lab uses HTTP and mcp:// resource identifiers; those are not production RFC 9728 identifiers.

Data services

HAPI FHIR 8.12 serves R4 data; PostgreSQL 18 stores Keycloak, HAPI, and scheduling state; OpenBao 2.7 stores vendor credentials; Kong Gateway 3.16 runs hybrid data planes.

Observability

OpenTelemetry Collector 0.161 forwards traces to Tempo 3.1 and logs to Loki 3.7. Alloy 1.20 tails container logs. Grafana 13.2 provisions data sources and a tuple dashboard.

Identity configuration: realm/

realm/mcp-plane.jsonKeycloak import

Defines the hub realm, clients, scopes, claim mappers, groups, users, and upstream IdPs. Realm defaults include PS256, a 300-second access-token lifespan, and sslRequired: none for the lab.

ClientFlowPurposeNotable configuration
phase0-smokeclient credentialsbaseline token gatesecret client; internal tier
claude-codeauthorization codeworkforce clientpublic; PKCE S256; internal audiences; optional step-up scopes
workforce-dpopauthorization codeDPoP-bound workforce clientpublic; PKCE S256; dpop.bound.access.tokens=true → tokens carry cnf.jkt
patient-agentauthorization codecustomer/patient clientpublic; PKCE S256; external tier; patient scopes and patient mapper
legacy-exchangetoken exchangelegacy migrationconfidential exchange requester
mcp-agents.loop-agentclient credentials over mTLSworkloadclient-x509; certificate-bound tokens; scheduling scopes

The realm is HTTP-first — lab-only.

Public clients register exact /callback redirect URIs (RFC 9700 exact match; the earlier wildcard registrations were closed as issue #15).

realm/fake-ping.jsontest IdP

Creates a separate OIDC issuer and workforce user with raw upstream group names. The hub brokers it and maps the identity into the canonical mcp-* group vocabulary.

compose/phase1/homegrown-issuer/main.pylegacy issuer

Creates an in-memory RSA key at startup, publishes OIDC-shaped discovery/JWKS, issues five-minute RS256 client-credentials tokens (client secret compared in constant time), and exposes userinfo. MCP components never accept these tokens directly; Keycloak exchanges them.

compose/phase1/setup-phase1.shidempotent setup

Adds external-to-internal token-exchange permission, allows the patient linkage attribute through the Keycloak user profile, and restores account-console client scopes omitted by the explicit import.

FHIR clinical MCP server

Patient-compartment enforcement in the FHIR server and stateless scheduling holds across replicas

Patient-compartment FHIR reads and stateless scheduling holds.

src/index.tsentry point

Loads and validates configuration (exiting with every problem listed if invalid), then starts the Express listener. Docker executes compiled dist/index.js.

src/config.tsconfiguration

Every environment setting with its default in one loadConfig: bind/public URLs, resource and issuer, required and MFA-gated scopes, upstream URL and optional server-owned UPSTREAM_API_KEY, and the upstream guardrails.

src/tools.ts + src/mcp-server.tscore server

Five embedded tool descriptors (generated from openapi.json), JSON-Schema-to-Zod conversion, group-filtered tool registration, and the tool handler: policy re-check → compartment hook → upstream call → final audit.

src/upstream.tsFHIR client

Builds the FHIR URL from declared parameters only, clamps _count, enforces the timeout and the buffered-size cap, and never forwards the caller’s token.

src/authz-hook.tscompartment

If auth.extra.fhir_patient exists, by-ID tools must match it and search tools have their patient argument overwritten. Without that claim, arguments pass unchanged.

servers/shared/shared core

One workspace package used by both servers: token-verifier.ts (JWKS signature, issuer, expiry, audience, PS256/ES256 only, contract-mandatory sub/azp/exp/iat/jti, mcp_contract 1.0, exactly one tier audience, fhir_patient in both directions); dpop.ts (authoritative DPoP re-check with JOSE EmbeddedJWK); tool-policy.ts (step-up scope, per-resource patient scope, mfa for MFA-gated scopes — 403 insufficient_scope or 401 insufficient_user_authentication); app.ts (Host/Origin guard, per-client rate limit ahead of token checks, PRM routes, batch refusal, MCP handler); audit.ts.

openapi.jsonsource description

Describes the curated FHIR endpoints. Runtime does not dynamically load it; descriptors are embedded in the TypeScript source.

Registered tools

ToolFHIR operationAuthorizationInput behavior
getPatientGET /Patient/{id}patient token needs patient/Patient.readpatient ID equality when compartmented
patientEverythingGET /Patient/{id}/$everythingclinical group + broad read scopeby-ID compartment applies
searchObservationGET /Observationpatient observation scopepatient forced; count clamped
searchConditionGET /Conditionpatient condition scopepatient forced; count clamped
searchMedicationRequestGET /MedicationRequestpatient medication scopepatient forced; count clamped
Upstream resource controls
  • MAX_FHIR_COUNT defaults to 100.
  • Timeout defaults to 10 seconds with AbortController.
  • Buffered response size defaults to 2,000,000 bytes.
  • Only declared path/query/body parameters are forwarded.
  • The caller’s token is never forwarded; an optional server-owned UPSTREAM_API_KEY covers backends that need a credential (the lab’s HAPI does not).
Express route order
express.json(1 MB)
securityGuard
public protected-resource metadata
POST /mcp: per-client rate limit (MCP_RATE_LIMIT_PER_MIN, default 600; 429 before any token work)
dpop scheme shim
bearer verification
requireDpop re-check (when cnf.jkt present)
JSON-RPC batch refused (-32600)
per-tool policy challenge (scope / patient scope / mfa)
createMcpHandler: fresh McpServer per request
tool handler → policy re-check → compartment → FHIR fetch → final audit
GET/DELETE /mcp: authenticated 405

Scheduling MCP server

src/index.tsentry point

Validates configuration (authorization server, JWKS and DATABASE_URL are required), awaits schema initialization, then listens — the table and index exist before requests are accepted.

src/server.ts + src/holds.tstools + SQL

holds.ts: synthetic slot catalog, Postgres migration, and hold/confirm/release against an injected database handle. server.ts: tool registration, scope map, and a shared guard (policy re-check, subject check, audit). Bearer, DPoP, Host/Origin guard, PRM and batch refusal come from servers/shared/.

src/config.tsconfiguration

Settings and defaults in one validated loadConfig; the OAuth logic is no longer a per-server copy.

test/offline tests

Hold lifecycle against in-process Postgres (PGlite) and the full HTTP flow with the v2 client pinned to 2026-07-28.

Persistence and concurrency

Startup
PostgreSQL advisory lock; create/alter table; expire duplicate held rows; recreate partial unique index on held slot IDs.
Hold
Expire elapsed hold, insert with conflict-do-nothing, return existing handle to same subject or deny another subject.
Confirm
Read, verify owner/status/expiry, then update held → confirmed only if still held and unexpired; a lost race reports expired.
Release
Read, verify owner, then update to released.
Model limitations: find-slots never queries holds; confirmed rows do not reserve slots; release can change confirmed rows. This proves externalized handles and active-hold contention, not complete booking semantics.

Scheduling validates Host/Origin and answers GET/DELETE with 405 through the shared host (updated 2026-09-30).

Kong gateway configuration and plugins

deck/internal.yamldeclarative state

Global OpenTelemetry, certificate-binding, DPoP sender-constraint, and tier-wall plugins. Routes HAPI, FHIR MCP, scheduling MCP, GitHub egress, and mockhub egress. Applies rate limits and route-specific OIDC/ACL/DLP/vendor-token plugins. The tier-wall pre-function accepts both Bearer and DPoP authorization schemes.

deck/external.yamldeclarative state

Independent external tier wall, OTel, a placeholder FHIR ACL route, and patient-facing FHIR MCP route.

cnf-check/handler.luacertificate binding

Requests a client certificate, parses unverified JWT payload only to locate the thumbprint, hashes leaf DER, and returns 401 on missing/unreadable/mismatch. Later components validate signature.

dpop-check/handler.luasender-constraint

When the token carries cnf.jkt, validates the DPoP proof structure, matches the proof key’s RFC 7638 thumbprint to the claim, checks htm/htu/iat/ath, and enforces single-use jti via a dpop_jti shared dict. It reads every DPoP header value, so a request carrying more than one proof is rejected. The replay cache fails closed: a missing dict or a failed insert returns 503, and forcible LRU evictions are logged as a degraded-mode audit event. It does not verify the proof’s ECDSA signature (the DP does no crypto on first-party routes); the MCP server re-checks authoritatively.

dlp-egress/handler.luainspection

Reads the body and fails closed for unreadable non-GET/HEAD input. Runs the configured PCRE patterns over the raw bytes, then — for a JSON body — over every decoded string and key, so JSON escapes cannot hide a match; a declared-JSON body that does not decode, or nests too deep, is denied. Blocks on error/match and logs only the pattern name.

vendor-token/handler.luacredential swap

Refuses a DPoP-scheme token with 401 (the broker validates bearer hub JWTs and does not check proofs). Posts vendor/sub/JTI/TTL/scopes to the broker, replaces upstream Authorization on 200, maps consent/re-consent responses, and fails closed — 502 when the broker is unreachable or its reply is malformed.

plugins/*/schema.luaschemas

Declare valid configuration fields. Because deck/internal.yaml is shared by every phase, every phase 2–5 setup registers all four schemas with Konnect before decK sync (compose/lib/konnect.sh) and every internal DP loads all four plugins; each is claim- or route-driven and inert where unused.

Vendor token broker

Governed egress: DLP screening at the gateway, broker resolve from vault custody, vendor token swap

OpenBao custody, single-flight refresh, DLP verdicts, and vendor-token isolation.

app/main.pyFastAPI service

Implements lifespan sweeper, problem responses (4xx for bad input; exception text stays in the audit log, never in the client problem detail), in-process cache/locks/transactions/state, OAuth consent, resolve/refresh, grants, admin view, and audit.

app/config.pyconfiguration

Reads and validates every environment input once at startup, so a bad value fails the container with a readable message instead of on the first request. Vault and vendor clients are injectable for the offline tests.

app/hub.pyinbound auth

PyJWKClient + PyJWT pin PS256/ES256, issuer, internal tier audience, 30-second leeway, and exp/iat/sub/jti. Additional contract/tier checks run after decode.

app/vendors.pyvendor adapters

Loads and caches registry/metadata; exchanges and refreshes with 10-second HTTPX clients; classifies invalid grants; resolves vendor identity; revokes via RFC 7009 or GitHub deletion.

app/vault_store.pyOpenBao KV v2

Separates token and client mounts, supports versioned CAS, translates missing entries to None, and wraps failures as VaultUnavailable.

app/audit.pyaudit

Emits structured events as JSON lines.

registry.jsonallowlist

Defines GitHub/mockhub enablement, endpoints or metadata URL, scope ceilings, user lookup, and revocation strategy.

HTTP API

EndpointAuthPurpose
GET /healthznoneliveness
POST /v1/tokens/resolvehub JWTusable token, consent, refresh, or closed failure
GET /v1/authorize/{vendor}transaction handlePKCE/state and AS redirect
GET /v1/callback/{vendor}state/responseissuer/state validation, code redemption, custody write
DELETE /v1/grants/{vendor}/{sub}matching hub subjectvendor-first revocation
GET /v1/grantshub JWTnon-secret grant metadata
GET /v1/admin/vendors/{vendor}platform-admin hub JWTnon-secret registry record
Resolve/refresh algorithm
  1. Validate hub JWT and use its subject.
  2. Validate vendor and requested scopes against ceiling.
  3. Read cache/Vault; absent or stale means consent.
  4. Missing scopes means re-consent for a capped union.
  5. Return token when remaining TTL is sufficient.
  6. Acquire per-vendor/subject asyncio lock and reread.
  7. Refresh once and persist with Vault CAS plus generation increment.
  8. Invalid grant marks STALE; vendor/Vault failure fails closed.

The lock is single-process. CAS prevents stale writes but does not stop duplicate vendor refresh calls across broker replicas.

Consent state

In-memory transactions carry subject/vendor/scopes/time. State records carry transaction, subject, vendor, PKCE verifier, nonce, issuer, issuer-required flag, consumed flag, and time. Both expire after ten minutes; restart abandons them.

Runtime, workload identity, and observability

agents/loop-agent/agent.pyworkload

Rereads the current SVID, calculates x5t#S256, gets an mTLS client-credentials token, checks token binding locally, then calls find/hold/release over the same certificate.

k8s/loop-agent.yamlKubernetes

Namespace, service account, helper sidecar, shared SVID volume, agent, CA, URLs, scopes, and collision-free provider. No client secret.

k8s/spire.yamlSPIRE

SPIRE server/agent chained to the generated lab CA. Setup scripts create workload registration entries and deliberately short SVID TTLs for rotation tests.

compose/phase5/mock-vendor/main.pytest vendor

In-memory OAuth AS/MCP endpoint with real PKCE, 60-second access tokens, rotating refresh families, replay burn, issuer parameter, redirects only to the registered callback, revocation, user endpoint, tools, and test controls.

PhaseRuntime additionSetup action
0Postgres, Keycloak, HAPI, OTel/Loki/Tempo/Grafanarealm import, Synthea seed
1brokered identity and legacy issuerexchange permission/profile setup
2Konnect internal/external DPs + uplink proxyCPs, certs, endpoint aliases, all four custom plugin schemas, decK sync
3FHIR and two scheduling replicasbuild and route sync
4lab PKI, TLS, cnf plugin, k3d/SPIREcerts, schema registration, workload deployment
5OpenBao, broker, mockhub, DLP/vendor plugins, AlloyVault mounts/policy/credentials, egress routes

Audit path

Kong OTel → Collector → Loki/Tempo. Service stdout → Alloy Docker discovery → Loki. Grafana provisions both sources and the audit tuple dashboard.

Containers

Node 24 servers use multi-stage builds (npm workspace context servers/) and run as node. The Python 3.14 services — broker, loop agent, homegrown issuer, mockhub — run as UID 65534. Server health checks query protected-resource metadata.

Local artifacts

Environment files, generated DP settings, cert/private keys, Synthea output, caches, lockfiles, compiled output, and dependencies are operational artifacts—not separately documented modules.

CP resiliency mechanism

Nginx carries aliases for Konnect cluster/telemetry endpoints. Stopping it severs DP uplink while leaving cached gateway configuration serving.

Tests, CI, and presentation

Phase tests

Phase 0–7 suites cover claims, normalization, tier isolation, CP loss, decK drift, tools, step-up, compartments, MFA step-up marks, 2026-07-28 negotiation and legacy fallback, batch refusal, stateless handles, mTLS/cnf, consent, DLP, refresh race, revocation, audit joins, and red-team probes including the DPoP proof suite.

tests/phase3/mcp_http.py

Minimal MCP 2026-07-28 client: every POST carries the per-request _meta envelope and the mirrored MCP-Protocol-Version / Mcp-Method / Mcp-Name headers, with no initialize and no session. Phase 3 also probes discovery, the 2025-era fallback, and batch smuggling.

Offline suite (make test)

248 tests, no accounts: servers (vitest) 89, broker (pytest) 97, the DB-less Kong plugin suite 47, and the kit’s offline claim vectors 15 (plus 4 skipped).

GitHub Actions

Lint, format, and type checks; offline tests with coverage; image builds; lychee, shellcheck, actionlint; decK and compose validation; blocking npm/pip audits; CodeQL. SHA-pinned actions, read-only token; Dependabot for npm, pip, Docker, compose, and actions. CI also runs the phase 0 and phase 1 quickstarts and gates 0–1 from a clean checkout; the Konnect-backed gates 2–7 remain manual.

Presentation

The stakeholder documentation is rendered as the showcase and walkthrough pages on this site; repository READMEs guide operators.

Coverage required before reassessment

The full reassessment gate — prerequisites and required evidence — is defined in the Overall Technical walkthrough.