HealthClawGuardrails
Summary: HealthClaw Guardrails is an MCP server for securely accessing and modifying FHIR health records through guardrails such as PHI redaction, audit logging, tenant isolation, step-up auth, and out-of-band approval for real-world actions.
Read and search FHIR R4 US Core v9 and R6 resources with redaction and auditing.
Retrieve patient context envelopes and compiled-truth/Provenance timelines.
Validate FHIR resources and preview writes before committing.
Commit FHIR writes with step-up tokens; clinical writes also expect the X-Human-Confirmed header (documented as a known gap).
Run Observation statistics, latest-N queries, and lab interpretation.
Check preventive care gaps, R6 Permission decisions, and SubscriptionTopics.
Pre-fill SDC Questionnaires and extract completed forms into FHIR bundles.
Evaluate data quality with Curatr and apply patient-approved fixes with Provenance.
Mint step-up tokens and seed demo tenant data.
Propose real-world actions (SMS, phone, insurance), submit them for the patient's out-of-band confirmation, and check status; execution requires patient approval.
Draft prescription-transfer requests (Schedule II refused).
Inspect connected data sources and wearable sync status.
Generate SMART Health Links for patient-consented record sharing (off by default).
Run guardrail conformance self-tests.
Provide ChatGPT-connector-compatible search and fetch.
Provides a framework-neutral bridge for LangChain agents to leverage HealthClaw's FHIR guardrails, including PHI redaction, audit, and tenant isolation.
Allows OpenAI-based AI agents to use HealthClaw's guardrailed MCP tools to interact with FHIR servers, ensuring policy enforcement and data protection.
This server has a remotely hosted endpoint. Open its connector listing for connection details, authentication requirements, and setup instructions:
HealthClaw Guardrails
The open-source security layer between AI agents and clinical data.
FHIR standardized how health data is structured. MCP standardized how AI connects to tools. Nobody standardized the guardrails in between. This project does.
▶ Watch the 90-second demo All records are synthetic. The chat ran on a third-party model, best of four takes. No clinician has signed off yet. How it was made.
Quick Start · MCP Tools · Recipes · Roadmap · Claude Plugin · Architecture · healthclaw.io · Contributing · Dev Guide
What it is: an open reference implementation of the FHIR × MCP guardrail layer — PHI redaction, immutable audit, step-up auth, and tenant isolation — that sits between any AI agent and any FHIR server. Built in the open as a community project, MIT-licensed. Not a product, not a pitch: if the pattern is useful, take it; if it's wrong, tell us or fix it.
This is a community effort. It's most useful when implementers, clinicians, and standards folks poke holes in it. Issues, PRs, and "you got the SDC extraction wrong" critiques are all welcome — start with CONTRIBUTING.md and the Code of Conduct.
At a glance: v2.1.0, with 29 MCP tools.
CareAgents is the hosted consumer app: passkey sign-in, advisors, and chat on the web. iMessage works where it's offered; Telegram is not open in the beta.
Two rails run end to end — real-world actions behind a provably out-of-band gate, and forms ($populate → human review → provenance PDF).
Standards: FHIR R4 US Core v9 and R6 v6.0.0-ballot3, HL7 SDC forms, NQF 0018.
Operations: lab interpreter ($interpret), care-gaps reminders ($care-gaps) with an embedded MCP-App view, and ChatGPT-connector search/fetch.
Connectors: Fasten TEFCA, HealthEx, HBO, Flexpa, Epic, MEDENT, Open Wearables, SMART Health Links.
Also a Claude Code plugin and OpenAI/Gemini adapters.
How it stops unauthorized or irreversible agent actions
A short map for a reviewer. Each line links to the detail and to something you can run.
The problem. An AI agent connected to a health record can read more than it needs and write what nobody approved. It can also start things that cannot be undone, such as a text message or a submitted form. Most FHIR MCP servers hand the agent the record and the write path as they are.
The approach. The agent gets a narrower path than the person it works for:
It reads less. Names, identifiers, addresses and birth dates are redacted before the model sees a record. Reads and writes leave an audit record. Pinned by
tests/test_claimed_properties_are_pinned.py(search and read redaction, a read's own audit event), and per write route by the audit column intests/test_write_guard_matrix.py.It cannot write on its session alone. Each write needs a separate, tenant-bound step-up token that expires in five minutes. Expiry is pinned in
tests/test_claimed_properties_are_pinned.py; a write without a token is refused in the conformance test.It cannot approve its own action. For a real-world action the agent can only propose.
commitsubmits the action and returns HTTP 202. Nothing runs until a person approves on a separate page, with a single-use credential bound to a digest of the exact payload they were shown. If the payload changes after they saw it, the approval does not match. Pinned bytests/test_human_gate_payload_digest.py(a changed payload is refused) andtests/actions/test_confirmations.py(the credential is consumed once).It fails loudly. An action kind with no working executor ends as
failed, not as a simulated success. A decline is recorded as a decline. Pinned bytests/actions/test_free_text_calls_cannot_dial.pyandtests/actions/test_decline_is_a_state.py.It stays in its tenant. A record is not readable from another tenant. Pinned by the tenant-isolation property in
tests/test_guardrail_conformance.py.
What can run today. Form filling runs end to end. Text messages run only on a server with a provider configured. Phone calls can be proposed, but no call executor is registered. The approval page offers no Approve for a call, an approval sent another way ends as failed, and nothing dials.
Evidence you can check.
Live self-test, no key needed:
curl "https://app.healthclaw.io/r6/fhir/\$conformance?format=text"(what the grade covers).The same seven properties as a CI test:
tests/test_guardrail_conformance.py.Which control guards which write route, as one table:
tests/test_write_guard_matrix.py.The propose, commit, approve, execute sequence:
tests/test_actions_routes.py.The guardrails in front of a real FHIR server, each property asserted: Aidbox example.
Mistakes this codebase has already made, with what each cost: defect catalogue.
The
python-testsjob runspytest tests/on every pull request (ci.yml); the badge above carries the count.
Where it falls short. The full list is under Known Limitations. The three that matter most here:
Direct clinical FHIR writes do not have a real human gate. They wait for an
X-Human-Confirmedheader, and the caller sets that header itself (#214). Only the action rail has the out-of-band approval.A step-up token works for several writes inside its five minutes. It is not single-use. No test pins this; validation does not consume the token's nonce unless a caller asks it to (
r6/stepup.py).The conformance grade is a self-test on synthetic data. No third party has audited this, and no clinician has signed off.
Related MCP server: MCP Server for Google Cloud Healthcare API
Try it in 60 seconds — no clone, no keys
The hosted demo runs synthetic data behind the full guardrail stack:
# Watch the deployment grade its own guardrails (PHI redaction, audit, step-up, ...):
curl "https://app.healthclaw.io/r6/fhir/\$conformance?format=text"Point any MCP client at the public demo server — URL https://mcp-demo-production-ee2c.up.railway.app/mcp,
no key required — then ask: "Search my health records for lab results and explain them in plain
language." The demo server is unauthenticated but hard-pinned to a synthetic demo tenant, so it can
only ever serve fake data. A separate production endpoint (mcp-server-production-5112) requires a
deployment-scoped Authorization: Bearer <token> — real records stay behind auth, always. Hosted
connectors cannot attach that header, so the demo URL above is the one to paste.
One-command installs:
gemini extensions install https://github.com/aks129/HealthClawGuardrails ·
claude plugin marketplace add aks129/HealthClawGuardrails ·
skills on ClawHub
Non-developer? Step-by-step guides for Claude (web/desktop/phone), Perplexity, ChatGPT, Grok, Meta Muse and Telegram — plus a 10-minute demo script — in docs/quickstarts/.
Listed in: Official MCP Registry (io.github.aks129/healthclaw-guardrails) ·
Glama (hosted connector) ·
ClawHub (14 skills) ·
Gemini CLI Extensions · agent-skills discovery at /.well-known/agent-skills/
Release highlights
Full notes live in Releases.
Version | Highlights |
v2.1.0 | The check-in release (notes): a |
v2.0.0 | The synthetic-beta release (notes): guardrails on by default, Grade A held, and the docs claim only what is true on |
v1.9.0 | CareAgents — the hosted consumer experience: sign up with a passkey, connect records through a pluggable connector marketplace (Fasten, Apple Health via Open Wearables, sample data), and spin up a guardrailed health agent reachable on web, Telegram, and iMessage · advisor registry — specialties ported from SmartHealthConnect (healthy-habits, care-completion, medication-refills, diet-exercise) as prompt-blocks over the guarded tool set, deferred ones honestly labeled · versioned informed consent enforced server-side (HTTP 428) before any real-record connection · forms rail ships end-to-end — |
v1.8.0 | Real-actions foundation — an agent can propose a real-world action (call, SMS, form) but |
v1.7.0 | Preventive care-gaps engine ( |
v1.6.0 | Lab reference-range interpreter ( |
v1.5.0 | Read-auth hardening (tenant reads authenticated, not just scoped) · HL7 SDC forms — |
v1.4.0 | Six health-data connectors (Fasten TEFCA, HealthEx, Health Bank One, Flexpa, Epic, MEDENT) behind one guardrail stack |
v1.3.0 | Wearables → FHIR Observations (8 providers, LOINC/UCUM mapping, device Provenance) |
v1.2.0 | Compiled Truth — current state + append-only Provenance trail per resource |
What It Does
This is a vendor-neutral guardrail proxy that sits between any AI agent and any FHIR server. Every request passes through:
PHI redaction — Names truncated to initials, identifier values removed (system and type kept), addresses stripped, birth dates truncated to year
Immutable audit trail — Every read/write logged with tenant, agent, timestamp
Step-up authorization — HMAC-SHA256 tokens required for writes
Human-in-the-loop — real-world actions (calls, SMS, forms):
commitonly submits. Execution requires a provably out-of-band single-use approval bound to the action, which the agent's own toolchain cannot satisfy. Direct clinical FHIR writes answer HTTP 428 until anX-Human-Confirmedheader is present. The caller sets that header, so it is not a human gate: a known gap tracked in #214Tenant isolation — Every query scoped to tenant, cross-tenant access blocked
Medical disclaimers — Injected on all clinical resource reads
Compiled Truth — Current state + append-only evidence trail for every resource
AI Agent ──▶ MCP Server ──▶ Guardrail Proxy ──▶ Any FHIR Server
↓ (HAPI, Epic,
PHI redaction Medplum, etc.)
Audit trail
Step-up auth
Approval (action rail)How it differs from a plain FHIR MCP server
Typical FHIR MCP server | HealthClaw | |
Redaction before the model | Returns the record as the server stores it | Before the agent sees the record: names cut to initials, identifier values removed, addresses stripped, birth dates cut to the year |
Audit of every access | Left to the FHIR server behind it | Every read and write records an AuditEvent, with a PHI-free detail |
Step-up for writes | The session credential covers writes | Each write needs a tenant-bound HMAC step-up token |
Out-of-band approval for calls, texts and forms | Not in scope | The agent only proposes. A person approves on a separate page, bound to the payload they were shown |
Tenant isolation | One credential, one view of the server | Every query is scoped to a tenant; cross-tenant access is refused |
Direct clinical FHIR writes are the exception to the approval row: they still gate on a header the caller sets (#214).
Prove it: guardrail conformance
The guardrails are verifiable, not marketing. A runnable harness probes any deployment with synthetic data and emits a scorecard across all seven properties — run it against your own instance (or ours):
python scripts/guardrail_conformance.py \
--base-url https://app.healthclaw.io --tenant desktop-demo \
--step-up-token "$(mint a token via POST /r6/fhir/internal/step-up-token)"HealthClaw Guardrail Conformance — https://app.healthclaw.io [tenant=desktop-demo]
Grade: A (7/7 properties)
[PASS] PHI Redaction [PASS] Human-in-the-Loop
[PASS] Immutable Audit Trail [PASS] Tenant Isolation
[PASS] Step-Up Authorization [PASS] Medical Disclaimers
[PASS] Error Fidelity — A (local-fhir-only)"Human-in-the-Loop" is the grader's name for the property. It checks the HTTP 428 on a clinical write without the confirmation header, not that a person approved (#214).
Or hit the one-URL self-test on any running deployment — no token needed, it self-tenants internally and returns 200 at Grade A (503 otherwise):
curl "https://app.healthclaw.io/r6/fhir/\$conformance?format=text"The local FHIR profile is Grade A: unsupported local-search inputs are rejected
or reported according to Prefer: handling, and every failure path is audited.
The same harness runs against the Flask test client as a CI baseline
(tests/test_guardrail_conformance.py). --json emits a machine-readable
report; --mcp-url additionally grades MCP tools/call error signaling as a
separate profile. For an authenticated MCP deployment, set MCP_AUTH_TOKEN or
pass --mcp-auth-token. Library API:
from r6.conformance import LiveProbeClient, ProbeContext, run_conformance.
What this grade means (and what it doesn't)
The grade covers the HealthClaw guardrail layer only — a self-test of the seven properties against synthetic data it just created. It is not a HIPAA Security Rule assessment, a third-party audit, or a penetration test of your deployment: infrastructure, BAAs, encryption at rest/in transit, and access controls remain the deployer's responsibility (see Known Limitations). Because the harness is deployment-agnostic, a third party can run it against any instance as one input to a real assessment — it does not substitute for one. The report states this scope itself in every output format.
Install as a Claude Plugin
HealthClaw ships as a Claude Code plugin marketplace. Two plugins are available:
# Add the marketplace
claude plugin marketplace add aks129/HealthClawGuardrails
# Install the FHIR guardrail plugin (this repo)
claude plugin install healthclaw-guardrails@healthclaw-marketplace
# Install the personal-health companion plugin (frozen — upstream archived)
claude plugin install smarthealthconnect@healthclaw-marketplacePlugin | Skills | Source |
| curatr, fasten-connect, fhir-r6-guardrails, fhir-upstream-proxy, healthex-export, phi-redaction | |
| care-completion, diet-exercise, healthy-habits, kids-health, medication-refills, research-monitor | aks129/SmartHealthConnect (archived — skills frozen at v1.2.0; live successors are CareAgents advisors) |
Each skill is auto-discoverable — Claude loads it when your prompt matches the skill's trigger phrases (e.g. "check my care gaps", "redact this bundle", "run Curatr on my conditions").
Not on Claude/MCP? The same 28 guardrailed tools run on OpenAI, Gemini, LangChain, or plain HTTP via the framework-neutral bridge in adapters/ — see Recipe: run HealthClaw tools on any agent framework. Guardrails stay server-side, so no framework can bypass them.
Quick Start
# Install dependencies
uv sync
# Apply deterministic database migrations
STEP_UP_SECRET=your-secret uv run flask --app main init-db
STEP_UP_SECRET=your-secret uv run flask --app main seed-demo --tenant-id desktop-demo
# Run (local mode with SQLite)
STEP_UP_SECRET=your-secret python main.py
# Run with upstream FHIR server
FHIR_UPSTREAM_URL=https://hapi.fhir.org/baseR4 STEP_UP_SECRET=your-secret python main.py
# Open browser
open http://localhost:5000 # Landing page with live demo
open http://localhost:5000/r6-dashboard # Interactive dashboardDocker
docker-compose up -d --build
# macOS note: port 5000 conflicts with AirPlay Receiver — remap with:
# HOST_PORT=5050 docker-compose up -d --build
# Services:
# - fhir-mcp-guardrails (Flask, port 5000)
# - agent-orchestrator (MCP server, port 3001)
# - redis (port 6379)MCP Tools (29)
Tool names use underscores (not dots) for Claude Desktop / MCP client compatibility.
Read tools (no step-up for public tenants):
Tool | Description |
| Retrieve pre-built context envelopes |
| Read a FHIR resource (redacted) |
| Search with patient, code, status, date filters |
| Structural validation |
| Observation statistics (count/min/max/mean) |
| Most recent N observations per code |
| Lab reference-range interpretation ( |
| Preventive-care gaps ( |
| Run the guardrail conformance self-test — graded A–F scorecard across all seven properties |
| R6 Permission access control evaluation |
| List available SubscriptionTopics |
| SDC |
| Evaluate a FHIR resource for data quality issues |
| Poll a real-world action (call/SMS) |
| ChatGPT-connector-compatible search — thin wrapper over |
| ChatGPT-connector-compatible fetch by |
Write tools (require step-up token):
Tool | Description |
| Validate + preview without committing |
| Commit with step-up auth. Clinical writes also wait for the |
| SDC |
| Apply patient-approved fixes with Provenance tracking |
| Propose / commit a real-world SMS. A phone call can still be proposed but is not placed: an approved one ends failed |
| Retired: the server answers 410 and proposes nothing |
| Generate an encrypted SMART Health Link (QR). Off by default: withheld from |
Utility tools:
Tool | Description |
| Issue a 5-minute step-up token (call before any write) |
| Seed a tenant with demo Patient + Observations + Condition |
| Current state + Provenance evidence timeline |
All tools add _mcp_summary with reasoning, clinical context, and limitations.
Guardrail Demo
The 6-step demo at /r6/fhir/demo/agent-loop shows the full guardrail sequence:
PHI Redaction — Agent reads a patient, receives redacted data
$validate Gate — Agent proposes an Observation, validated before write
Permission Deny — No Permission rule exists, access denied with reasoning
Permission Permit — Permit rule created, re-evaluation succeeds
Step-up + confirmation header — Write requires a token and the
X-Human-Confirmedheader. The caller sets that header, so it is not a human gate (#214)Commit + Audit — Write succeeds, full audit trail generated
Comparison
Feature | This Project | AWS HealthLake MCP | Medplum MCP | Raw FHIR API |
Works with any FHIR server | Yes | HealthLake only | Medplum only | N/A |
PHI redaction on reads | Yes | No | No | No |
Immutable audit trail | Yes | CloudTrail (separate) | Partial | No |
Step-up auth for writes | Yes | IAM (separate) | Medplum auth | No |
Out-of-band human approval | Action rail only (#214) | No | No | No |
Permission $evaluate (R6) | Yes | No | No | No |
Setup time | 10 seconds | 30+ minutes | 15+ minutes | Varies |
FHIR Version Support
Version | Profile | Status | Resources |
R4 | US Core v9 | Stable | Patient, Condition, AllergyIntolerance, Immunization, MedicationRequest, Procedure, DiagnosticReport, CarePlan, CareTeam, Goal, DocumentReference, Coverage, ServiceRequest, Location, Organization, Practitioner, PractitionerRole, RelatedPerson, Specimen, FamilyMemberHistory |
R6 | v6.0.0-ballot3 | Experimental | Permission, SubscriptionTopic, DeviceAlert, NutritionIntake, DeviceAssociation, NutritionProduct, Requirements, ActorDefinition |
Both R4 and R6 resources flow through the same guardrail stack (PHI redaction, audit, step-up auth, tenant isolation). R6 ballot resources may change before final release.
Testing
# Python tests; the badge counts test functions, not parametrized cases (action-rail, SDC, quality, labs, ops and CareAgents suites among them)
uv run python -m pytest tests/ -v
uv run python -m pytest tests/test_r6_routes.py::test_name -v # single test
# MCP server tests
cd services/agent-orchestrator && npm ci && npm test
# Playwright end-to-end tests (UI + API, requires Flask on :5000)
cd e2e && npm ci && npx playwright install --with-deps chromium && npm test
cd e2e && npm run test:headed # headed browser
cd e2e && npm run test:ui # interactive UI modeAPI Endpoints
Endpoint | Method | Description |
| GET | CapabilityStatement |
| GET | Liveness probe (reports upstream status) |
| POST | Create resource (requires step-up) |
| GET | Search resources |
| GET | Read resource (redacted) |
| PUT | Update resource (requires step-up + ETag) |
| POST | Validate resource |
| POST | SDC — pre-fill a QuestionnaireResponse from a subject |
| POST | SDC — extract a transaction Bundle ( |
| GET | Conservative de-identification preview (expert review required) |
| GET | Observation statistics |
| GET | Most recent observations |
| POST | R6 access control evaluation |
| GET | Subscription topic discovery |
| POST | Bundle ingestion + context envelope |
| GET | Retrieve context envelope |
| GET | Search audit events |
| GET | Export audit trail (NDJSON/Bundle) |
| POST | 6-step guardrail demo |
| * | OAuth 2.1 + PKCE + SMART discovery |
| GET | Evaluate resource data quality (Curatr) |
| POST | Apply patient-approved fixes with Provenance |
Local search accepts the parameters advertised by /r6/fhir/metadata.
Unknown parameters default to lenient handling (a bounded
search.mode="outcome" warning); Prefer: handling=strict returns a 400
OperationOutcome. Unsupported modifiers and malformed supported values always
return 400. _count=0 and _summary=count are count-only searches. Self links
contain exactly the applied, URL-encoded parameters, and audit output never
echoes submitted filter values or arbitrary parameter names.
Upstream Proxy
Connect to real FHIR servers while keeping all guardrails active:
FHIR_UPSTREAM_URL=https://hapi.fhir.org/baseR4 python main.pyReads: Fetched from upstream, then redacted + audited + disclaimers added
Searches: Forwarded with all query params, results redacted per entry
Writes: Validated locally first, then forwarded with step-up auth check
URL rewriting: Upstream URLs never leak to clients
Tested with: HAPI FHIR R4/R5, SMART Health IT, Epic Sandbox.
Put the guardrails in front of your FHIR server — recipe for running the
redaction + audit + step-up stack in front of Medplum
(the same pattern works for Aidbox, Google Cloud Healthcare, or any FHIR R4
server): docs/recipes/healthclaw-in-front-of-medplum.md.
A repeatable integration test (tests/test_medplum_in_front.py) proves a
Medplum-returned Patient comes back redacted + audited and writes are step-up
gated before reaching Medplum.
Curatr — Patient-Owned Data Quality
Curatr is a patient-facing data quality skill that evaluates FHIR health records for coding issues and lets the patient decide how to resolve them.
1. Patient connects data → HealthClaw Guardrails deidentifies and loads it
2. OpenClaw calls curatr.evaluate → checks codes against live terminology APIs
3. Issues presented in plain language with impact and fix suggestions
4. Patient approves fixes → curatr.apply_fix updates resource + creates Provenance
5. Optional: generate a structured correction request for the source providerWhat Curatr checks on a Condition:
Check | Service | Example |
Deprecated code system | Local lookup (no network) | ICD-9-CM → critical |
ICD-10-CM code validity | NLM Clinical Tables API | Invalid code → warning |
SNOMED CT / LOINC validity | tx.fhir.org (HL7 public) | Unknown code → warning |
RxNorm drug code | RXNAV API (NLM) | Missing RXCUI → warning |
Display name accuracy | Cross-checked with canonical term | Mismatch → suggestion |
Missing required fields | Structural | No clinicalStatus → warning |
Every fix creates a linked Provenance resource recording patient intent, field changes, and agent attribution. All changes are audited in the immutable trail.
OpenClaw skill: skills/curatr/SKILL.md
SMART Health Links (Kill the Clipboard)
Patient-controlled encrypted record sharing via QR code, implemented on top of
jmandel/kill-the-clipboard-skill
(MIT, pinned fa0020d) — credit Josh Mandel. HealthClaw governs what enters the
bundle (step-up auth, profiles, guardrails, audit trail); KTC governs sharing
(zero-knowledge server-side storage, SHL STU 1 protocol, revocation, in-browser
viewer).
Off by default. shl_generate is withheld from tools/list and a call is
refused unless the operator sets MCP_ENABLE_SHL_GENERATE=true. Patient-initiated
sharing is being rebuilt behind a consent page.
What it does: The shl_generate MCP tool (Write group, step-up required)
fetches the patient's guardrailed FHIR bundle, encrypts it client-side in the MCP
server (the SHL server never sees plaintext), uploads ciphertext, and returns:
shlink— theshlink:/URI to encode in a QR (an encrypted pointer, not data)viewer_link— browser URL for clinic staffmanage_link— patient-only revocation + access-log URL
Security: The QR encodes only the encrypted pointer. PHI never appears in the
QR image. The SHL server stores only ciphertext + sha256(auth_token). Persona
hard rule: see skills/share-health-qr/SKILL.md — never direct-encode PHI into
QR images (incident 2026-06-12).
Quick Start (local)
# Start the SHL storage server (profile `shl`)
docker-compose --profile shl up -d
# Tell the MCP server where the SHL server lives
# Add to services/agent-orchestrator/.env or export:
export SHL_SERVER_URL=http://localhost:8000Without SHL_SERVER_URL, shl_generate returns an explicit simulation stub
(simulated: true) — never a fake link.
Railway Deploy
# 1. Add the SHL service
railway add --service shl-server
# 2. Attach a persistent volume (SQLite lives here)
railway service shl-server && railway volume add --mount-path /data
# 3. Configure the SHL server
railway variables --service shl-server \
--set BASE_URL=<public-url-of-shl-server> \
--set DB_PATH=/data/db.sqlite
# 4. Expose a public domain
railway domain --service shl-server
# 5. Deploy — MUST run from the shl-server directory
cd services/shl-server && railway up --service shl-server
# 6. Wire the MCP server to the SHL server
railway variables --service mcp-server \
--set SHL_SERVER_URL=<public-url-of-shl-server>Caveat 1 — deploy from the right directory: The repo-root
railway.tomltargets the Flask Dockerfile. If you runrailway up --service shl-serverfrom the repo root, Railway uses the wrong Dockerfile and the deploy fails. Alwayscd services/shl-serverfirst — that directory has its ownrailway.tomlthat points to the correct image.Caveat 2 — watchPatterns skip: A service that inherited
watchPatternsfrom the root config may silently skip Dockerfile-only deploys (no source file changes detected). The per-servicerailway.tomlinservices/shl-server/overrides this after the first successful build. If deploys are skipped, force one withrailway up --service shl-serverfrom the shl-server directory.Caveat 3 — simulation mode: Without
SHL_SERVER_URLon the MCP server,shl_generatereturns{ simulated: true, note: "SHL_SERVER_URL not configured — returned stub." }. Personas surface this note verbatim and never improvise an alternative.
OpenClaw skill: skills/share-health-qr/SKILL.md
R6-Specific Resources (Experimental)
These resources are part of the FHIR R6 ballot3 specification and may change before final release.
Resource | What's New in R6 |
Permission | Access control (separate from Consent), |
SubscriptionTopic | Restructured pub/sub (introduced R5, maturing R6) |
DeviceAlert | ISO/IEEE 11073 device alarms |
NutritionIntake | Dietary consumption tracking |
DeviceAssociation | Device-patient relationships |
NutritionProduct | Nutritional product definitions |
Requirements | Functional requirements tracking |
ActorDefinition | Actor role definitions |
US Core v9 R4 Resources (Stable)
Standard FHIR R4 resources conforming to US Core Implementation Guide v9. These are widely deployed in US healthcare and stable for production use.
AllergyIntolerance, Immunization, MedicationRequest, Medication, MedicationDispense, Procedure, DiagnosticReport, CarePlan, CareTeam, Goal, DocumentReference, Location, Organization, Practitioner, PractitionerRole, RelatedPerson, Coverage, ServiceRequest, Specimen, FamilyMemberHistory
Environment Variables
Variable | Required | Default | Description |
| Production | — | HMAC-SHA256 signing secret |
| No | — | Upstream FHIR server (enables proxy mode) |
| Production |
| Database connection |
| No | (dev key) | Flask session secret |
| Production |
| Require tenant-bound credentials on protected reads |
| Production | — | Explicit comma-separated synthetic/demo tenant allowlist |
| Production | — | Shared nonce, OAuth, rate-limit, and worker state |
| HTTP MCP | — | Bearer credential required by MCP HTTP transports |
| No |
| Run an unauthenticated MCP server hard-pinned to a synthetic demo tenant (the public keyless demo). Never set on a server that reaches real tenants |
| No |
| Synthetic tenant the demo server is pinned to when |
| No | 15 | Upstream request timeout (seconds) |
| No | — | Local URL for response URL rewriting |
Database DDL is never run during WSGI import. Run flask --app main init-db
before each release; it applies the locked Alembic revisions. Operators adopting
Alembic on an existing v1.8.0 Postgres deployment must follow the
database migration runbook to verify and
stamp the compatibility baseline before upgrading.
Project Structure
main.py Flask app entry point
app.py Web UI routes (landing, dashboard)
r6/
routes.py R6 FHIR REST Blueprint (1,732 lines)
models.py R6Resource, ContextEnvelope, AuditEventRecord
validator.py FHIR R6 structural validation
redaction.py PHI redaction (names, identifiers, addresses, DOB, telecom)
audit.py Immutable AuditEvent recording
stepup.py HMAC-SHA256 step-up token management
oauth.py OAuth 2.1 + PKCE + SMART-on-FHIR discovery
health_compliance.py Disclaimers, HITL, de-identification preview, audit export
context_builder.py Bundle ingestion + context envelopes
rate_limit.py Per-tenant rate limiting
fhir_proxy.py Upstream FHIR server proxy with URL rewriting
curatr.py Curatr data quality engine (terminology lookups + fix application)
services/agent-orchestrator/
src/index.ts MCP server (Streamable HTTP + SSE)
src/tools.ts 12 tool definitions + executor (incl. curatr.evaluate, curatr.apply_fix)
e2e/ Playwright end-to-end tests
templates/ Jinja2 (landing page, dashboard)
static/ CSS + JS for interactive dashboard
skills/curatr/ Curatr OpenClaw skill definition
tests/ pytest suite (incl. test_us_core_r4.py)Personal FHIR data store — patient import flow
This walkthrough shows how to go from a raw HealthEx export to querying your own records through Claude Code's MCP tools.
1. Start the stack
uv sync
uv run python main.py # Flask on :5000
cd services/agent-orchestrator && npm ci && npm start # MCP on :30012. Import your HealthEx / Flexpa / generic FHIR bundle
# Dry-run first to preview without writing
python scripts/import_healthex.py \
--bundle-file ~/Downloads/my-records.json \
--dry-run
# Real import — prints context_id on success
python scripts/import_healthex.py \
--bundle-file ~/Downloads/my-records.json \
--tenant-id my-patient \
--step-up-secret "$STEP_UP_SECRET"3. Connect Claude Code via MCP
.mcp.json in this repo auto-configures Claude Code when you open the project.
Update X-Tenant-ID to match your --tenant-id:
{
"mcpServers": {
"healthclaw-local": {
"type": "http",
"url": "http://localhost:3001/mcp",
"headers": { "X-Tenant-ID": "my-patient" }
}
}
}Then in Claude Code:
Use fhir_search to find all my Conditions
Use context_get with context_id <ctx-id> to get my full context envelope
Use curatr_evaluate on Condition/<id> to check data quality4. Set up Fasten Connect (optional)
# .env additions
FASTEN_PUBLIC_KEY=<key>
FASTEN_PRIVATE_KEY=<key>
FASTEN_WEBHOOK_SECRET=<secret>
FASTEN_CURATR_SCAN=true # auto-run Curatr after each importRecords arrive via webhook at /r6/fasten/webhook and are stored under the
patient's canonical tenant ID.
5. Deidentify for sharing
# De-identification preview (not a legal Safe Harbor determination)
curl -H "X-Tenant-ID: my-patient" \
http://localhost:5000/r6/fhir/Patient/pt-1/\$deidentify
# Patient-controlled (preserves birthDate, strips institutional identifiers)
curl -H "X-Tenant-ID: my-patient" \
"http://localhost:5000/r6/fhir/Patient/pt-1/\$deidentify?mode=patient-controlled&patient_id=my-patient"6. Telegram bot (optional)
TELEGRAM_BOT_TOKEN=<token> TENANT_ID=my-patient \
FHIR_BASE_URL=http://localhost:5000/r6/fhir \
python openclaw/bot.pyCommands: /health, /conditions, /labs, /curatr, /curatr fix, /approve.
Or via Docker Compose:
docker-compose --profile openclaw up -d7. Use Medplum as the backing FHIR store (optional)
Set in .env (leave FHIR_UPSTREAM_URL empty):
MEDPLUM_BASE_URL=https://api.medplum.com/fhir/R4
MEDPLUM_CLIENT_ID=<id>
MEDPLUM_CLIENT_SECRET=<secret>All guardrails apply to Medplum responses identically to local SQLite mode.
Access tokens are cached in Redis (key medplum:access_token; falls back to
in-process cache when Redis is unavailable).
Known Limitations
The conformance grade is a self-test of the guardrail layer, not a HIPAA assessment or third-party audit — see What this grade means
Local mode: JSON blob storage with table-scan search (no indexed fields)
Redaction is HIPAA Safe-Harbor-style field redaction (demographics), not Expert Determination. It's a compensating control that removes identifier-class fields (identifier values are removed outright, not truncated); it is not a legal de-identification determination. Production de-id rigor (profile-specific recursive allowlists, an Expert-Determination path) is on the roadmap (#112).
Validation is structural, not full StructureDefinition/profile conformance or terminology binding. What's demonstrated is the guardrail contract (redact + audit + step-up + human-confirm + tenant isolation + error fidelity), not production validation depth — that's tracked in #112.
SubscriptionTopic stored but notifications not dispatched
Direct clinical FHIR writes have no real human gate. They answer HTTP 428 until the caller sends
X-Human-Confirmed, and the caller sets that header about itself, so it proves nothing about a human. This is a known gap (#214); do not build on it. The real human gate is the action rail, used by real-world actions (phone/SMS/forms), and it does not accept that header.commitonly submits the action for out-of-band approval (202awaiting_confirmation). The patient's Approve tap consumes a single-useActionConfirmationcredential server-side before anything executes.OAuth endpoints are for discovery/SMART advertisement; route enforcement is via step-up + read-auth tokens, and the auto-approve authorize flow is limited to public/demo tenants (no per-user consent screen)
No historical versioning (version_id increments but old versions not retrievable)
Upstream proxy: no response caching, no cross-version translation
Security is config-dependent — production requires
READ_AUTH_ENABLED=true(authenticate non-public reads),INTERNAL_TOKEN_MINT_SECRET(gate token mint/seed for non-public tenants; fail-closed in prod when unset),PUBLIC_TENANTSlimited to synthetic demo tenants, a realSESSION_SECRET/STEP_UP_SECRET, and https-only upstreamsStep-up tokens are valid for multiple writes within their 5-min TTL (not single-use); irreversible actions rely on state-machine idempotency (guarded
WHERE status='proposed'claim) rather than nonce consumption
Contributing — this is a community effort
HealthClaw Guardrails is developed in the open as a shared reference, not a commercial product. The guardrail layer between AI agents and clinical data only gets trustworthy if a lot of people with different vantage points pressure-test it. We especially want:
Implementers building FHIR × MCP integrations — tell us where the patterns break in the real world.
Clinicians & compliance folks — challenge the redaction profiles, audit model, and the documented HIPAA postures.
Standards people (HL7 / SDC / SMART) — tell us where we've diverged from the spec, especially on
$populate/$extract.Anyone — open an issue, file a "you got this wrong," or send a PR.
Start here: CONTRIBUTING.md · Roadmap · Dev Guide · Code of Conduct · CHANGELOG.md · Security policy
Good first contributions are labeled in the issue tracker. Contributions are DCO-signed (git commit -s) under the MIT license — see LICENSING.md for the project's licensing posture going forward.
Community
GitHub Discussions — questions, ideas, show-and-tell.
good first issues — scoped, ~15-minute-to-start contributions.
Building on OpenClaw or Hermes? The skills are on ClawHub; the MCP server is in the Hermes catalog.
License
MIT — free to use, fork, and build on. See LICENSE.
Available Tools
29 toolsaction_commitSubmit Real-World Action for ConfirmationADestructiveInspect
Submit a previously proposed action for the patient's OWN out-of-band confirmation (their dashboard or Telegram) AFTER they've reviewed and verbally/textually agreed to the draft. Requires step-up authorization (call fhir_get_token first; pass as _stepUpToken). This call does NOT execute anything and never accepts or sends any 'human confirmed' flag — only the patient tapping Approve in their own out-of-band channel can trigger execution. Returns status 'awaiting_confirmation' and is terminal for your turn: do not call action_commit again for the same action_id. Use action_status to check whether the patient has approved yet.
Inputs: action_id (required).
action_proposePropose Real-World ActionARead-onlyInspect
Propose a real-world action (phone call or SMS) on the patient's behalf. Returns a draft (id + script) the patient MUST review before submitting via action_commit. Does not execute anything.
Inputs: kind (required), payload (required).
action_statusAction StatusARead-onlyInspect
Check the status and outcome of an action (proposed/awaiting_confirmation/executing/completed/failed/needs_review/unknown/expired). needs_review means it ran but the outcome could not be confirmed - show the patient the evidence. unknown means the provider MAY have acted - never re-propose the same action. Use after action_commit to see whether the patient has approved yet, and to report the final result back to them.
Inputs: action_id (required).
care_gapsPreventive Care GapsARead-onlyInspect
Check which preventive-care screenings/immunizations a patient may be due for (blood pressure, cholesterol, colorectal/cervical/breast cancer screening, flu, diabetes A1c), from their own connected records. Decision support based on USPSTF/ACIP/ADA guidelines — not a diagnosis or directive. Response includes _meta.ui.resourceUri pointing to an embeddable review UI.
Inputs: subject.
context_getGet Health ContextBRead-onlyInspect
Retrieve a pre-built context envelope with patient-centric FHIR resources. Returns bounded, policy-stamped, time-limited context.
Inputs: context_id (required).
curatr_apply_fixApply Data Quality FixAInspect
Apply patient-approved data quality fixes to a FHIR resource. Creates a linked Provenance record with full attribution. Requires step-up authorization (X-Step-Up-Token) and human confirmation (X-Human-Confirmed: true) for clinical resources like Condition.
Inputs: fixes (required), resource_id (required), resource_type (required), patient_intent (required).
curatr_evaluateEvaluate Data QualityARead-onlyInspect
Evaluate a FHIR resource for data quality issues. Checks coding elements against public terminology services (tx.fhir.org for SNOMED/LOINC, NLM for ICD-10-CM, RXNAV for RxNorm) and structural rules. Returns issues in plain language with patient-facing impact descriptions and resolution suggestions. Read-only — no step-up required.
Inputs: resource_id (required), resource_type (required).
fetchFetch Health RecordARead-onlyInspect
ChatGPT-connector-compatible fetch of one FHIR resource by id ('ResourceType/id', as returned by search). Returns the full document (PHI-redacted server-side) with metadata.
Inputs: id (required).
fhir_commit_writeCommit FHIR WriteCDestructiveInspect
Commit a previously proposed write. Requires step-up authorization token. This is a destructive operation.
Inputs: resource (required), operation (required).
fhir_compiled_truthCompiled Truth TimelineARead-onlyInspect
Return the current best understanding of a FHIR resource plus the append-only evidence trail (Provenance entries) of how it got there. Use this before presenting resource-specific facts to a patient — surfaces curation_state and quality_score so the agent can say not just WHAT the record says but WHY it says it. Redacted, audited. Response includes _meta.ui.resourceUri pointing to an embeddable review UI.
Inputs: resource_id (required), resource_type (required).
fhir_get_tokenMint Step-Up TokenARead-onlyInspect
Get a fresh step-up authorization token for write operations. Call this before fhir_propose_write, fhir_commit_write, or curatr_apply_fix. Tokens expire after 5 minutes. Returns the token string — pass it as _stepUpToken in subsequent write tool calls.
Inputs: tenant_id (required).
fhir_interpret_labsInterpret Lab ResultsARead-onlyInspect
Interpret lab Observations against reference ranges — flags each value low/normal/high/critical (HL7 v3 ObservationInterpretation) and returns clinician + consumer summaries. Decision support, not diagnosis. Read-tier.
Inputs: bundle, subject, observation.
fhir_lastnLatest ObservationsARead-onlyInspect
Get the last N observations per code. Standard FHIR $lastn (since R4). Returns most recent observations by storage order.
Inputs: max, code, patient.
fhir_permission_evaluateEvaluate Access PermissionARead-onlyInspect
Evaluate R6 Permission resources for access control decisions. Returns permit/deny based on stored Permission rules. Separates access control (Permission) from consent records (Consent).
Inputs: action (required), subject, resource.
fhir_propose_writePropose FHIR WriteARead-onlyInspect
Propose a write — validates the resource and returns a preview. Does NOT commit. Safe to call without step-up authorization.
Inputs: resource (required), operation (required).
fhir_readRead FHIR ResourceARead-onlyInspect
Read a specific FHIR resource by type and ID. Supports FHIR R4 US Core v9 stable resources and FHIR R6 ballot3 experimental resources. Returns redacted resource with PHI protection.
Inputs: resource_id (required), resource_type (required).
fhir_searchSearch FHIR ResourcesARead-onlyInspect
Search for FHIR resources. Supports FHIR R4 US Core v9 stable resources and FHIR R6 ballot3 experimental resources. Supports patient, code, status, _lastUpdated, _count, _sort parameters. Returns paginated, redacted Bundle.
Inputs: resource_type (required), code, _sort, _count, +3 more.
fhir_seedSeed Demo DataAInspect
Seed a tenant with a realistic Patient + Observations + Condition bundle for live testing. Use this at the start of a demo session to populate data. Returns created resource IDs and a ready-to-use step_up_token.
Inputs: tenant_id.
fhir_statsObservation StatisticsARead-onlyInspect
Compute statistics (count, min, max, mean) over numeric Observation values. Standard FHIR $stats (since R4). Only supports valueQuantity. Filter by patient and/or code.
Inputs: code, patient.
fhir_subscription_topicsList Subscription TopicsARead-onlyInspect
List available SubscriptionTopics for event-driven subscriptions. R6 moves topic-based subscriptions toward Normative. Agents discover what events they can subscribe to.
Inputs: no named parameters.
fhir_validateValidate FHIR ResourceARead-onlyInspect
Validate a proposed FHIR R6 resource against structural rules. Returns OperationOutcome.
Inputs: resource (required).
guardrail_conformanceGuardrail Conformance ScorecardARead-onlyInspect
Run the guardrail conformance self-test on the connected HealthClaw deployment and return the graded scorecard across seven guardrail properties: PHI redaction, immutable audit, step-up auth, human-in-the-loop, tenant isolation, medical disclaimers, and error fidelity. Uses synthetic data only. Set fresh=true to force a new run instead of the cached result.
Inputs: fresh.
questionnaire_extractExtract Form Data to FHIRADestructiveInspect
SDC $extract — extract FHIR resources from a completed QuestionnaireResponse into a transaction Bundle. Write tier; requires step-up unless dry_run=true.
Inputs: questionnaire_response (required), dry_run, questionnaire.
questionnaire_populatePre-fill Health FormARead-onlyInspect
SDC $populate — pre-fill a Questionnaire for a subject. Returns a QuestionnaireResponse. Read tier; mints a tenant token for non-public tenants.
Inputs: subject_reference (required), questionnaire, questionnaire_id.
rx_transfer_requestRequest Prescription TransferARead-onlyInspect
Draft a prescription-transfer request: assembles the patient's active medications and stages a phone call to the RECEIVING pharmacy asking it to pull the prescriptions from the current pharmacy (how US transfers actually work). Schedule II medications are refused (never transferable — new prescription required). Returns a draft the patient MUST review; submit with action_commit for the patient's own out-of-band confirmation after they explicitly agree — action_commit does not execute the call itself.
Inputs: to_pharmacy_name (required), to_pharmacy_phone (required), medication_names, from_pharmacy_name, +1 more.
searchSearch Health RecordsARead-onlyInspect
ChatGPT-connector-compatible search over the tenant's FHIR records. Query is a FHIR search string (e.g. 'Observation?code=4548-4' or 'Patient?name=smith'); bare resource type works too. Returns compact results: id, title, url. Reads are PHI-redacted and audit-logged server-side.
Inputs: query (required).
shl_generateGenerate SMART Health LinkAInspect
Generate a SMART Health Link (shlink:/ QR payload) sharing the patient's record with a clinic. Fetches the guardrailed share-bundle from HealthClaw (step-up required — pass _stepUpToken), encrypts it client-side (the SHL server never sees plaintext), uploads ciphertext, and returns the shlink URI, viewer link, and the patient's private manage link. ALWAYS get the patient's explicit consent before generating, and deliver the manage link ONLY to the patient.
Inputs: label, profile, patient_id, expires_in_days.
sources_checkCheck Data SourcesARead-onlyInspect
Survey ALL connected health data sources (Fasten, HealthEx, Health Bank One, MEDENT, Flexpa, Epic/Health Skillz, wearables) at once — returns each source's connection status and the patient's record counts by type. Use when the patient asks what's connected or to check for data across services.
Inputs: no named parameters.
wearables_sync_statusWearables Sync StatusARead-onlyInspect
List wearable connections (Garmin, Oura, Polar, Suunto, Whoop, Fitbit, Strava, Ultrahuman) for a tenant, with last sync time, observation count, and status. Use this to tell a patient what's connected, when data last arrived, and surface a connection-management UI (via _meta.ui.resourceUri) so they can connect more providers. Data flows into HealthClaw as FHIR Observations with LOINC codes — agents read it via fhir_search like any other Observation.
Inputs: tenant_id.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 29 tools
Several boundaries are fuzzy despite detailed descriptions: fhir_read vs fetch (both read one resource by id), search vs fhir_search (both query records), sources_check vs wearables_sync_status (both survey connections), and fhir_validate vs fhir_propose_write (the latter also validates). The ChatGPT-connector vs native duplication is somewhat explained by descriptions, but an agent could still misselect.
A domain-prefix pattern exists (fhir_, curatr_, questionnaire_, action_), but ordering and form are inconsistent: verb_noun for most, yet noun_noun for action_status, care_gaps, guardrail_conformance, and noun_verb for sources_check. The bare search/fetch also break the prefix convention used by their near-twins fhir_search/fhir_read.
At 29 tools the surface is heavy and the count is inflated by overlapping pairs (read/fetch, search/fhir_search), but the domain genuinely spans FHIR CRUD, data quality, real-world actions, sharing, wearables, and conformance, so most tools have a plausible place. Borderline rather than clearly excessive.
The FHIR lifecycle is well covered: read, search, stats, lastn, compiled-truth with provenance, propose/validate/commit writes, permission evaluation, questionnaire populate/extract, and data-quality fixes. Minor gaps remain (no explicit delete, no patient enumeration), but core workflows and guardrail operations are present.
Maintenance
Related MCP Connectors
AgentGuard — 20-tool AI safety MCP: policy preflight, risk scoring, audit logging, rate limits.
MCP gateway: one connection for your AI apps, with tool policies, PII redaction and audit logs.
Zero-secret MCP gateway for AI agents: risk-scored, audited calls with human-in-the-loop approval.
Human-in-the-loop for AI agents over MCP: durable approvals with a hosted review page & audit trail
Related MCP Servers
- AlicenseBqualityDmaintenanceA Model Context Protocol server providing AI assistants with access to healthcare data tools, including FDA drug information, PubMed research, health topics, clinical trials, and medical terminology lookup.7133MIT
- AlicenseBqualityNot gradedmaintenanceMCP Server for Google Cloud Healthcare API enables Agentic AI for a variety of FHIR-based digital health solutions, from smarter clinical workflows for Health Systems to Pre-Auth frameworks for Payers!158-
- AlicenseNot gradedqualityCmaintenanceA clean-room SHARP-on-MCP compliant FHIR R4 MCP server that enables AI agents to interact with any FHIR R4 endpoint using SHARP context headers, without server-side OAuth. It provides clinical tools, lab results, imaging, and interactive MCP-UI dashboards.MIT
- AlicenseAqualityCmaintenanceMCP server and CLI for detecting, redacting, and auditing PHI in medical text before it reaches AI agents.4MIT