|
| 1 | +--- |
| 2 | +id: mcp |
| 3 | +title: MCP Server (LLM bridge) |
| 4 | +sidebar_label: MCP Server |
| 5 | +--- |
| 6 | + |
| 7 | +# MCP Server (LLM bridge) |
| 8 | + |
| 9 | +`@fhir-dsl/mcp` exposes a FHIR endpoint as a [Model Context Protocol](https://modelcontextprotocol.io/) tool surface, so an LLM agent can `read`, `search`, `vread`, `history`, and (opt-in) `create`/`update`/`delete` against a real FHIR server with full audit + auth. |
| 10 | + |
| 11 | +One server === one upstream FHIR endpoint, scoped to one IG (the IG pin lives at generate time; the runtime just receives the resource-types list). |
| 12 | + |
| 13 | +## Install |
| 14 | + |
| 15 | +```bash |
| 16 | +npm install @fhir-dsl/mcp |
| 17 | +# Auth strategies that need it: |
| 18 | +npm install @fhir-dsl/smart jose # required only for backend-services / patient-launch auth |
| 19 | +``` |
| 20 | + |
| 21 | +`@fhir-dsl/smart` and `jose` are optional peer dependencies — bearer-token-only deployments never load them. |
| 22 | + |
| 23 | +## Minimal example |
| 24 | + |
| 25 | +```ts |
| 26 | +import { createServer, stdioTransport } from "@fhir-dsl/mcp"; |
| 27 | + |
| 28 | +const server = createServer({ |
| 29 | + name: "us-core-mcp", |
| 30 | + version: "1.0.0", |
| 31 | + baseUrl: "https://hapi.fhir.org/baseR4", |
| 32 | + resourceTypes: ["Patient", "Observation", "Encounter"], |
| 33 | + auth: { kind: "bearer", token: process.env.FHIR_TOKEN! }, |
| 34 | +}); |
| 35 | + |
| 36 | +await server.listen(stdioTransport()); |
| 37 | +``` |
| 38 | + |
| 39 | +That's a fully functional MCP server: read-only, audited to stderr, ready to plug into Claude Desktop, Cursor, or any other MCP client. |
| 40 | + |
| 41 | +## Transports |
| 42 | + |
| 43 | +### `stdioTransport()` |
| 44 | + |
| 45 | +Newline-delimited JSON over stdin/stdout. Default for CLI MCP clients (Claude Desktop, the `claude` CLI, etc.) which spawn the server as a child process. |
| 46 | + |
| 47 | +```ts |
| 48 | +import { stdioTransport } from "@fhir-dsl/mcp"; |
| 49 | +await server.listen(stdioTransport()); |
| 50 | +``` |
| 51 | + |
| 52 | +Options: `input` and `output` streams (defaults to `process.stdin` / `process.stdout`). The transport idles indefinitely; the host process kills it on shutdown. |
| 53 | + |
| 54 | +### `httpTransport()` |
| 55 | + |
| 56 | +Streamable HTTP transport for hosted deployments — POST a JSON-RPC body to a single endpoint, get a `Content-Type: application/json` response. Spec: [Streamable HTTP](https://modelcontextprotocol.io/docs/concepts/transports#streamable-http). |
| 57 | + |
| 58 | +```ts |
| 59 | +import { createServer, httpTransport } from "@fhir-dsl/mcp"; |
| 60 | + |
| 61 | +const transport = httpTransport({ |
| 62 | + port: 8080, |
| 63 | + cors: true, |
| 64 | + authenticate: (req) => |
| 65 | + req.headers.authorization === `Bearer ${process.env.MCP_TOKEN}`, |
| 66 | +}); |
| 67 | + |
| 68 | +await server.listen(transport); |
| 69 | +console.log(`MCP listening on ${transport.url()}`); |
| 70 | +``` |
| 71 | + |
| 72 | +Options: |
| 73 | + |
| 74 | +| Option | Default | What it does | |
| 75 | +|---|---|---| |
| 76 | +| `port` | `0` (ephemeral) | TCP port. Read the actual port back via `transport.url()` after `start()`. | |
| 77 | +| `host` | `127.0.0.1` | Bind host. | |
| 78 | +| `path` | `/mcp` | Endpoint path. | |
| 79 | +| `cors` | `false` | Adds `Access-Control-Allow-Origin: *` and a preflight handler. | |
| 80 | +| `authenticate` | none | `(req) => boolean \| Promise<boolean>`. Return `false` to short-circuit with `401`. | |
| 81 | +| `maxRequestBytes` | `1 << 20` (1 MiB) | Hard cap on request body size; over-cap requests get `413`. | |
| 82 | +| `server` | none | Pre-built `http.Server` to mount onto, instead of starting a new one. Useful when MCP shares a process with an unrelated HTTP service. | |
| 83 | + |
| 84 | +Calling `transport.url()` before `start()` throws; call it afterwards to get the resolved URL (with the actual port if you passed `0`). |
| 85 | + |
| 86 | +#### Mounting onto an existing server |
| 87 | + |
| 88 | +```ts |
| 89 | +import { createServer as createHttpServer } from "node:http"; |
| 90 | +import { httpTransport } from "@fhir-dsl/mcp"; |
| 91 | + |
| 92 | +const httpServer = createHttpServer((req, res) => { |
| 93 | + // Your existing routes go here. The transport only handles `/mcp`. |
| 94 | +}); |
| 95 | +httpServer.listen(8080); |
| 96 | + |
| 97 | +const transport = httpTransport({ server: httpServer, path: "/mcp" }); |
| 98 | +await server.listen(transport); |
| 99 | +``` |
| 100 | + |
| 101 | +When `options.server` is provided, the transport never calls `listen()` or `close()` — the caller owns the lifecycle. |
| 102 | + |
| 103 | +#### Currently out of scope (planned for v1) |
| 104 | + |
| 105 | +- GET `/mcp` opening an SSE stream for server-initiated notifications. |
| 106 | +- `text/event-stream` responses for streaming tool output. |
| 107 | +- Batched JSON-RPC arrays. |
| 108 | + |
| 109 | +The dispatcher today only emits single synchronous responses, so SSE has no producer yet. Tracked in `V1_PLAN.md` Theme 1.1. |
| 110 | + |
| 111 | +## Auth strategies |
| 112 | + |
| 113 | +Three pinned variants behind one `AuthStrategy` interface. Every strategy resolves an outbound HTTP header set per request, so token refresh, JWT resigning, and zero-config bearer all coexist. |
| 114 | + |
| 115 | +```ts |
| 116 | +// Bearer (dev / static tokens): |
| 117 | +auth: { kind: "bearer", token: process.env.FHIR_TOKEN! } |
| 118 | + |
| 119 | +// SMART v2 backend-services (signed JWT — RS384 or ES384): |
| 120 | +auth: { |
| 121 | + kind: "backend-services", |
| 122 | + issuer: "https://hapi.example.org/fhir", |
| 123 | + clientId: "my-bot", |
| 124 | + privateKey: process.env.JWT_PRIVATE_KEY!, |
| 125 | + scope: "system/*.read", |
| 126 | +} |
| 127 | + |
| 128 | +// SMART v2 patient launch (refresh-token flow with auto-rotation): |
| 129 | +auth: { |
| 130 | + kind: "patient-launch", |
| 131 | + issuer: "https://hapi.example.org/fhir", |
| 132 | + clientId: "my-spa", |
| 133 | + refreshToken: session.refreshToken, |
| 134 | + scope: "patient/*.read", |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +`@fhir-dsl/smart` is loaded lazily, so bearer-only servers never pay the `jose` cost. |
| 139 | + |
| 140 | +## Write gating |
| 141 | + |
| 142 | +Writes are off by default. Enable them surgically: |
| 143 | + |
| 144 | +```ts |
| 145 | +createServer({ |
| 146 | + // ... base config |
| 147 | + writes: ["create", "update"], // which verbs to expose |
| 148 | + writeResourceTypes: ["Observation"], // narrow further to specific resources |
| 149 | + confirmWrites: true, // require {confirm: true} per call |
| 150 | + dryRun: false, // set true to short-circuit with synthetic OperationOutcome |
| 151 | +}); |
| 152 | +``` |
| 153 | + |
| 154 | +A typical safe setup for an LLM that should only ever create observations: `writes: ["create"], writeResourceTypes: ["Observation"], confirmWrites: true`. |
| 155 | + |
| 156 | +## Token economy |
| 157 | + |
| 158 | +Defaults that prevent an LLM from reading 50 MB of bundle and burning your context: |
| 159 | + |
| 160 | +| Option | Default | What it does | |
| 161 | +|---|---|---| |
| 162 | +| `defaultSearchCount` | `20` | Default `_count` when the LLM omits one. `0` disables. | |
| 163 | +| `defaultReadSummary` | none | Default `_summary` for read verbs (`text`, `data`, `count`, etc.). | |
| 164 | +| `maxResponseBytes` | `64 * 1024` | Hard cap on JSON response bytes. Oversized bodies are swapped for a `too-costly` `OperationOutcome`; the audit retains the original. `0` disables. | |
| 165 | + |
| 166 | +## Audit |
| 167 | + |
| 168 | +Every verb call routes through an `AuditSink` regardless of outcome. Three implementations ship: |
| 169 | + |
| 170 | +- `JsonLogAuditSink` (default) — structured JSON to stderr. |
| 171 | +- `MemoryAuditSink` — keep events in memory; useful for tests and integration smoke. |
| 172 | +- `NullAuditSink` — drop events; for performance benchmarks. |
| 173 | + |
| 174 | +```ts |
| 175 | +import { MemoryAuditSink, createServer } from "@fhir-dsl/mcp"; |
| 176 | + |
| 177 | +const audit = new MemoryAuditSink(); |
| 178 | +const server = createServer({ /* ... */, audit }); |
| 179 | + |
| 180 | +// later in tests: |
| 181 | +expect(audit.events.map((e) => e.call.verb)).toContain("read"); |
| 182 | +``` |
| 183 | + |
| 184 | +A custom sink is just an object with `record(event: AuditEvent): void | Promise<void>` — drop-in for Splunk, Loki, OTLP, or a `FhirAuditEventSink` writing `AuditEvent` resources back to the upstream. |
| 185 | + |
| 186 | +## Generating a server alongside the typed client |
| 187 | + |
| 188 | +```bash |
| 189 | +fhir-gen generate --version r4 --ig hl7.fhir.us.core@6.1.0 \ |
| 190 | + --out ./src/fhir --mcp ./mcp-server |
| 191 | +``` |
| 192 | + |
| 193 | +`./mcp-server/` gets a `server.ts` shim, `mcp.config.json` seeded with the IG's resource types, and a README. Launch it with `FHIR_BASE_URL=… node mcp-server/server.ts`. |
| 194 | + |
| 195 | +## Or run inline (no generated types) |
| 196 | + |
| 197 | +```bash |
| 198 | +fhir-gen mcp https://hapi.fhir.org/baseR4 \ |
| 199 | + --resources Patient,Observation \ |
| 200 | + --writes create --confirm-writes \ |
| 201 | + --auth-bearer-env FHIR_TOKEN |
| 202 | +``` |
0 commit comments