On this page
Putting an agent in front of a clinical record is an authorization problem before it is an AI problem. A FHIR server already has an answer to who may read what: SMART on FHIR scopes, issued per app and per patient. A Model Context Protocol server that sits between an agent and that FHIR server has to carry the answer through, tool by tool, and it is the only component in a position to do so.
This article builds one and tests it. Seven tools sit in front of HAPI FHIR 8.0.0. Each tool declares the SMART v2 scope it needs. Eight tokens with different scopes list the tools and make 39 calls, some of them attempts to reach another patient’s records, a category outside the grant, or a tool the token was never shown. The same tokens are then pointed at the design most people try first, a single tool that accepts any FHIR query, written two ways.
The seven typed tools returned nothing outside scope in 39 calls. The generic tool with the obvious checks returned records outside the token’s scopes on 9 of 12 hostile requests, through _include, _revinclude, _has, $everything, reads by id and ignored category filters. The data is synthetic and none of this is clinically validated.
The problem
SMART scopes were designed for apps that call a FHIR API directly. The FHIR server enforces them. An MCP server changes the shape of that arrangement in three ways.
- The token is not for the FHIR server. The MCP authorization specification requires a server to accept only tokens issued for itself, and forbids passing the token it received to an upstream API. The MCP server calls FHIR with its own credential, which usually has broad access. The narrowing has to happen in the MCP server.
- The caller is a model. Whatever parameters a tool accepts will be filled with whatever text reaches the model, including text from the records it has just read. A parameter that accepts a query language is an invitation.
- FHIR search reaches sideways. One search can return resources of other types and of other patients. A check on the resource type named in the URL says little about what comes back.
The SMART Backend Services article found the third point on the FHIR side: HAPI answered Patient?_revinclude=Observation:subject for any caller. An MCP server in front of it inherits the problem, with a model composing the queries. It is also the textbook position for the confused deputy described in the red-team article: a component with more authority than its caller, acting on the caller’s words.
An agent that reads a clinical record can mislead a clinician, and one that writes to it can harm a patient. Authorization limits what can be reached, and does nothing for the correctness of what the model says about it. The write tool in this article creates records with status preliminary for a person to confirm. Nothing here has been clinically validated, and all data is synthetic.
Architecture
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','clusterBkg':'#F8FAFC','clusterBorder':'#CBD5E1','edgeLabelBackground':'#FFFFFF','nodeTextColor':'#232F3E'}}}%%
flowchart TD
AG["Agent and MCP client"] -- "access token: audience is the MCP server,
SMART scopes, patient in context" --> V["Verify token:
signature, issuer, audience, expiry"]
AS["Authorization server"] -. "issues" .-> AG
V --> L["List tools the scopes can use"]
V --> D["Decide each call:
scope, patient, category"]
D -- "refused" --> AU["Audit log:
one line per call"]
D -- "allowed" --> T["Typed tool builds
a fixed FHIR request"]
T -- "server's own credential" --> F["FHIR server"]
F --> C["Check every returned resource
against the decision"]
C --> AU
C --> AG
style V fill:#F3E8FF,stroke:#7C3AED,stroke-width:2px,color:#4C1D95
style D fill:#F3E8FF,stroke:#7C3AED,stroke-width:2px,color:#4C1D95
style F fill:#EBF8FF,stroke:#0073BB,stroke-width:2px,color:#004C74
style AU fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202
style C fill:#F3E8FF,stroke:#7C3AED,stroke-width:2px,color:#4C1D95There are three controls and one convenience. The token is verified once per HTTP request. Every tool call gets a decision from the scopes before any FHIR request is made. Every resource that comes back is checked against that decision before it is returned. Filtering the tool list is the convenience: it saves the model from seeing tools it cannot use, and it protects nothing, because a client can call a tool it was never shown.
Tool design
Each tool maps to one resource type and one SMART permission. That makes the scope a tool needs a fact about the tool, written down in one table, and makes the tool list for a token a direct reading of its scopes.
| Tool | Needs | Notes |
|---|---|---|
get_patient | Patient.r | The patient in context, or a named one for a user-level token |
search_patients | user/Patient.s | Across patients. A patient-level scope never satisfies it |
list_observations | Observation.s | Optional category and LOINC code. Honours ?category= filters on the scope |
get_observation | Observation.r | By id. Same answer for “does not exist” and “not yours” |
list_medications | MedicationRequest.s | |
list_conditions | Condition.s | |
record_observation | Observation.c | Subject comes from the decision. Status is preliminary |
Three choices matter more than the list itself.
- No tool accepts a FHIR path or query string. Parameters are typed: a category from a fixed list, a LOINC code checked against a pattern, an id checked against the FHIR id format. There is nowhere to put
_revinclude. - The patient is not an argument for patient-level tokens. It comes from the token. A
patient_idargument exists for clinician sessions, and for a patient-level token it is accepted only if it equals the patient in context. - Tools return summaries, not resources. A handful of fields per record. It keeps results small, which the context cost article argues for, and it keeps fields nobody reviewed out of the model’s context.
Scope parsing
SMART App Launch 2.2.0 defines clinical scopes as a context, a resource type and a subset of the letters cruds in that order, optionally followed by search parameters that narrow the grant. Version 1 scopes are still common and map onto the letters. The parser turns each into a grant and ignores everything that is not a clinical scope:
PATTERN = re.compile(r"^(patient|user|system)/([A-Z][A-Za-z]+|\*)\.(\*|read|write|c?r?u?d?s?)(?:\?(.+))?$")
V1 = {"read": "rs", "write": "cud", "*": "cruds"}
@dataclass(frozen=True)
class Grant:
"""One granted scope."""
context: str # patient, user or system
resource: str # a FHIR resource type, or * for all
permissions: frozenset[str] # of c, r, u, d, s
filters: tuple[tuple[str, str], ...] = field(default=()) # search parameters the resource must match
def covers(self, resource: str, permission: str) -> bool:
return self.resource in ("*", resource) and permission in self.permissions
def parse(scopes: list[str]) -> list[Grant]:
"""The clinical scopes in a token. Anything else (openid, launch, offline_access) is ignored here."""
grants = []
for scope in scopes:
match = PATTERN.match(scope)
if not match or not match.group(3):
continue
context, resource, permissions, query = match.groups()
grants.append(Grant(context, resource, frozenset(V1.get(permissions, permissions)), tuple(parse_qsl(query or ""))))
return grantsTwo details are easy to get wrong. Search and read are separate permissions in version 2, so patient/Observation.s allows listing and not reading by id. And scopes add up: a token holding a filtered grant and an unfiltered grant for the same resource is not limited by the filter.
def allowed_values(grants: list[Grant], parameter: str) -> set[str] | None:
"""The values of one search parameter that these grants are limited to, or None for no limit.
Scopes add up: one unfiltered grant among them lifts the limit.
"""
values: set[str] = set()
for grant in grants:
own = {value for name, value in grant.filters if name == parameter}
if not own:
return None
values |= own
return valuesAuthorization decision
The decision for one call is a pure function of the grants, the patient in the token, the tool and two arguments. It has no network access and no framework in it, which is what makes it testable. It answers three questions in order: is there a scope for this resource and permission, which single patient may this call touch, and which observation categories.
def decide(grants: list[Grant], token_patient: str | None, tool: str, patient_id: str | None = None, category: str | None = None) -> Decision:
need = NEEDS[tool]
found = usable(grants, need)
if not found:
raise Denied("scope", f"no scope grants {need.resource}.{need.permission}")
wide = [grant for grant in found if grant.context in ("user", "system")]
if need.across_patients:
return Decision(None, None)
if wide:
if not patient_id:
raise Denied("context", "a user-level token must name the patient")
patient, chosen = patient_id, wide
else:
if not token_patient:
raise Denied("context", "patient-level scope without a patient in the token")
if patient_id and patient_id != token_patient:
raise Denied("compartment", f"asked for Patient/{patient_id}, token is for Patient/{token_patient}")
patient, chosen = token_patient, found
categories = allowed_values(chosen, "category") if need.resource == "Observation" else None
if categories is not None:
categories = {value.removeprefix(CATEGORY_SYSTEM + "|") for value in categories}
if category and category not in categories:
raise Denied("filter", f"category {category} is outside the granted {sorted(categories)}")
return Decision(patient, categories)%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','clusterBkg':'#F8FAFC','clusterBorder':'#CBD5E1','edgeLabelBackground':'#FFFFFF','nodeTextColor':'#232F3E'}}}%%
flowchart TD
S{"Scope covers the tool's
resource and permission?"} -- "no" --> X["Refuse: scope"]
S -- "yes" --> U{"A user-level or
system-level grant?"}
U -- "yes" --> N{"Patient named
in the arguments?"}
N -- "no" --> X2["Refuse: context"]
N -- "yes" --> CAT
U -- "no, patient-level only" --> M{"Argument absent or equal
to the token's patient?"}
M -- "no" --> X3["Refuse: compartment"]
M -- "yes" --> CAT{"Category asked for is
inside the granted filter?"}
CAT -- "no" --> X4["Refuse: filter"]
CAT -- "yes" --> OK["Decision: one patient,
allowed categories"]
style OK fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202
style X fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1B
style X2 fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1B
style X3 fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1B
style X4 fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1BThe decision is applied twice. It shapes the FHIR request, so the search carries the patient and the categories. Then it is applied to what comes back, because a request that was built correctly can still return something unexpected from a server that behaves differently from the one it was tested against:
def in_scope(resource: dict, decision: Decision) -> bool:
"""Check a resource that came back from the FHIR server against the decision. The last line of defence."""
if decision.patient is not None:
if resource["resourceType"] == "Patient":
if resource.get("id") != decision.patient:
return False
elif (resource.get("subject") or resource.get("patient") or {}).get("reference") != f"Patient/{decision.patient}":
return False
if decision.categories is not None and resource["resourceType"] == "Observation":
held = {coding.get("code") for concept in resource.get("category", []) for coding in concept.get("coding", []) if coding.get("system") == CATEGORY_SYSTEM}
if not held & decision.categories:
return False
return TrueA refusal carries a kind and a reason for the audit log. The caller gets one fixed sentence, whatever the cause, so that a model probing the server learns nothing about which patients or records exist.
Server
The server is built on the MCP Python SDK. The token verifier checks signature, issuer, audience and expiry, with the algorithm fixed in code, and attaches the patient in context to the token object the tools will see:
class SmartToken(AccessToken):
"""An access token plus the two SMART facts the tools need."""
subject: str = ""
patient: str | None = None # the patient in context, for patient/ scopes
class JwtVerifier(TokenVerifier):
"""Signature, issuer, audience and expiry, checked here. Scopes are checked per tool call."""
def __init__(self, public_key: str, issuer: str, audience: str) -> None:
self.public_key, self.issuer, self.audience = public_key, issuer, audience
async def verify_token(self, token: str) -> AccessToken | None:
try:
claims = jwt.decode(
token,
self.public_key,
algorithms=["RS256"], # never taken from the token header
issuer=self.issuer,
audience=self.audience,
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.InvalidTokenError:
return None
if claims["exp"] <= time.time():
return None
return SmartToken(
token=token,
client_id=claims.get("client_id", claims["sub"]),
scopes=str(claims.get("scope", "")).split(),
expires_at=int(claims["exp"]),
resource=self.audience,
subject=claims["sub"],
patient=claims.get("patient"),
)The tool list is filtered per token by overriding one method, and every tool starts with the same call to authorize, which writes the audit line whether the answer is yes or no:
class ScopedMCP(FastMCP):
"""Lists only the tools the caller's scopes can use. Every call is still checked: see authorize()."""
async def list_tools(self) -> list[Tool]:
token = get_access_token()
shown = set(visible(parse(token.scopes))) if token else set()
return [tool for tool in await super().list_tools() if tool.name in shown]def audit(token: SmartToken | None, tool: str, outcome: str, patient: str | None, detail: str = "") -> None:
"""One line per call, allowed or refused. Identifiers only: no token and no clinical content."""
entry = {"time": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "subject": token.subject if token else None, "client": token.client_id if token else None, "tool": tool, "patient": patient, "outcome": outcome, "detail": detail}
with open(AUDIT_LOG, "a", encoding="utf-8") as handle:
handle.write(json.dumps(entry) + "\n")
def authorize(tool: str, patient_id: str | None = None, category: str | None = None) -> tuple[SmartToken, Decision]:
"""Called first by every tool. Raises Denied, which the caller sees as one fixed sentence."""
token = get_access_token()
if not isinstance(token, SmartToken):
raise Denied("token", "no verified token")
try:
if patient_id is not None and not IDENTIFIER.fullmatch(patient_id):
raise Denied("input", "patient_id is not a FHIR id")
if category is not None and category not in CATEGORIES:
raise Denied("input", "unknown category")
decision = decide(parse(token.scopes), token.patient, tool, patient_id, category)
except Denied as denied:
audit(token, tool, f"denied:{denied.kind}", token.patient, denied.reason)
raise
audit(token, tool, "allowed", decision.patient)
return token, decisionA tool is then a few lines: authorize, build a fixed request from the decision, check what came back, summarise.
@mcp.tool(annotations=READ_ONLY)
async def list_observations(category: str | None = None, code: str | None = None, patient_id: str | None = None) -> list[dict]:
"""Observations for one patient, newest first. category is laboratory or vital-signs; code is a LOINC code."""
_, decision = authorize("list_observations", patient_id, category)
wanted = [category] if category else sorted(decision.categories) if decision.categories is not None else []
parameters = {"patient": decision.patient, "_sort": "-date"}
if wanted:
parameters["category"] = ",".join(f"{CATEGORY_SYSTEM}|{value}" for value in wanted)
if code:
if not re.fullmatch(r"[0-9]{1,7}-[0-9]", code):
raise ValueError("code must be a LOINC code such as 4548-4")
parameters["code"] = f"http://loinc.org|{code}"
found = await fhir.search("Observation", parameters)
return [observation_summary(resource) for resource in found if in_scope(resource, decision)]
@mcp.tool(annotations=READ_ONLY)
async def get_observation(observation_id: str, patient_id: str | None = None) -> dict:
"""One observation by id."""
_, decision = authorize("get_observation", patient_id)
resource = await fhir.read("Observation", observation_id) if IDENTIFIER.fullmatch(observation_id) else None
if resource is None or not in_scope(resource, decision):
return {"found": False} # the same answer for "does not exist" and "not yours"
return {"found": True, **observation_summary(resource)}%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','signalColor':'#0073BB','signalTextColor':'#0F172A','actorBkg':'#FFF3E0','actorBorder':'#FF9900','actorTextColor':'#232F3E','noteBkgColor':'#FFF8E7','noteBorderColor':'#FF9900','noteTextColor':'#232F3E'}}}%%
sequenceDiagram
participant C as MCP client
participant M as MCP server
participant F as FHIR server
C->>M: tools/call list_observations, token for patient P1, labs only
Note over M: Token verified. Decision: patient P1, category laboratory
M->>F: Observation?patient=P1&category=laboratory
F-->>M: Bundle
Note over M: Each resource checked against the decision
M-->>C: Summaries of P1 laboratory results
C->>M: tools/call list_observations, category vital-signs
Note over M: Refused: filter. Audit line written. No FHIR request
M-->>C: Fixed refusal sentenceThe MCP authorization specification says a server should answer a request with insufficient scope with HTTP 403 and a WWW-Authenticate header naming the scopes needed, so that a client can ask for more. This sample refuses inside the tool result and names nothing. That is a deliberate choice for a clinical system, where the scopes a session holds are set at launch and telling a model which scope would open another patient’s data helps nobody. A server that wants step-up authorization would add the challenge for the scope case only.
Test setup
HAPI FHIR 8.0.0 runs in a container on the build runner, loaded with three invented patients, each with two laboratory results, two vital signs, a medication request and a condition. The lab signs its own tokens with a key generated for the run. No authorization server is involved, and the patient in context travels as a patient claim in the token; SMART returns it next to the access token in the token response, and how it reaches a resource server is left to the deployment.
| Token | Scopes | Patient |
|---|---|---|
| patient-app | patient/Patient.r patient/Observation.rs | P1 |
| labs-only | patient/Observation.rs?category=…|laboratory | P1 |
| meds-view | patient/Patient.r patient/MedicationRequest.rs patient/Condition.rs | P1 |
| search-only | patient/Observation.s | P1 |
| self-recorder | patient/Observation.c?category=…|vital-signs patient/Observation.rs | P2 |
| clinician | user/Patient.rs user/Observation.rs user/MedicationRequest.rs user/Condition.rs | none |
| legacy-v1 | patient/*.read | P3 |
| identity-only | openid profile fhirUser | none |
Each call has an expected outcome written down before the run: an answer with records, an answer with none, or a refusal. A separate judge, which does not share code with the server’s policy, looks up every record id in every answer and reports any that the token’s scopes do not cover.
No model is involved; the lab calls the tools as a client would. The requests were written by the person who wrote the server, so the result shows that the design holds against the attacks its author thought of, on one FHIR server.
Test results
The tool list followed the scopes. A token with no clinical scope saw no tools at all.

| Check | Result |
|---|---|
| Calls that ended as expected | 39 of 39 |
| Answers holding a record outside the token’s scopes | 0 |
| Calls to a tool that was not listed for the token | 11, all refused |
| Refusals by kind | 11 scope, 3 compartment, 2 filter, 1 input, 1 context |
| Audit lines | 39, one per call; none held a token, a name or a result |
| Unusable tokens (none, expired, wrong key, wrong audience, unsigned) | 5 of 5 answered HTTP 401 |
A few of the 39 are worth reading individually. The search-only token could list observations and was refused the read by id. The labs-only token listing observations with no category got laboratory results only, and asking for one of the same patient’s vital signs by id got “not found”. The self-recorder could create a vital sign for its own patient and was refused a laboratory result and a different patient. The clinician token was refused when it named no patient. The version 1 wildcard, patient/*.read, opened five read tools and no write.
Generic tool comparison
The alternative design is one tool, fhir_request(path), on the grounds that the model already knows FHIR. The lab has two versions. The naive one does what a first implementation does: it checks that the token has a scope for the resource type at the start of the path, with read for a path with an id and search otherwise, and it forces the patient parameter on searches for patient-level tokens.
@mcp.tool()
async def fhir_request_naive(path: str) -> dict:
"""GET any FHIR path, for example Observation?code=4548-4 or Patient/123."""
token = get_access_token()
resource, identifier, query, _ = split(path)
grants = matching(parse(token.scopes), resource, "r" if identifier else "s")
if not grants:
raise Denied("lab", "no scope for this resource type")
if not identifier and resource != "Patient" and all(grant.context == "patient" for grant in grants):
query = [(name, value) for name, value in query if name not in ("patient", "subject")] + [("patient", token.patient)]
path = f"{resource}?{urlencode(query)}"
return await fhir.raw(path)Fifteen requests went to both versions as two patient-level tokens: T1 with Patient.rs and Observation.rs, T2 with laboratory observations only. Three are fair requests the token should be served. Twelve are not.
| Token | Request | Naive | Guarded |
|---|---|---|---|
| T1 | Observation/syn-o2-lab1 (another patient’s result) | Leaked 1 | Not found |
| T1 | Observation?patient=syn-p2 | Own results (parameter overridden) | Refused |
| T1 | Patient?family=Alder | Leaked 1 patient | Refused |
| T1 | Patient?_id=syn-p1&_revinclude=MedicationRequest:subject | Leaked 1 | Refused |
| T1 | Patient/syn-p1/$everything | Leaked 2 | Refused |
| T1 | Patient?_has:Observation:patient:code=4548-4 | Leaked 2 patients | Refused |
| T1 | Observation?subject.family=Birch | Nothing | Refused |
| T2 | Observation?_include=Observation:subject | Leaked 3 | Refused |
| T2 | Observation?category=vital-signs | Leaked 2 | Refused |
| T2 | Observation/syn-o1-vit1 | Leaked 1 | Not found |
| T2 | Observation (no category) | Leaked 2 | Laboratory only |
| T1 | MedicationRequest?patient=syn-p1 | Refused | Refused |

The naive tool leaked on 9 of the 12, 15 records in all, and served the three fair requests. Each leak is a different FHIR feature doing what it is specified to do: includes bring other types, reverse chaining finds other patients, an operation returns a whole record, and a read by id has no patient parameter to force. The granular scope was ignored entirely because nothing in a resource-type check looks at it.
The guarded version leaked nothing and still served the three fair requests. It gets there by allow-listing search parameters per resource type, refusing operations and anything after an id, forcing patient and category, and running every returned resource through the same in_scope check as the typed tools. By the time it is safe it accepts a small fixed set of parameters per resource type, which is what the typed tools are, with a parser in front. And it passed fifteen requests written by its author, which is weaker evidence than it looks.
An allow-list is only as good as the understanding of each parameter on it. FHIR servers add search parameters, modifiers and operations between versions, and a guard that refuses by pattern has to be reviewed against every upgrade. A typed tool cannot express a request nobody wrote code for.
Cost
Nothing in this lab measured cost or latency. Two costs are structural and worth naming. Each tool call makes one FHIR request and one policy evaluation, and the policy is arithmetic on a handful of strings, so the FHIR request dominates. And seven tool definitions are sent to the model on every turn of a session that can see all seven; filtering the list by scope reduces that for narrow tokens as a side effect. The context cost article has the method for measuring it.
Production considerations
- Keep the FHIR server unreachable by callers. The MCP server holds a credential broader than any caller’s. It belongs on a network where only the MCP server can reach FHIR, and the credential should be as narrow as the tool set allows: read on four resource types and create on one, here.
- Decide how patient context arrives. A claim in a signed token, as here, or token introspection at the authorization server. Do not take it from a header or a tool argument.
- Treat tokens as short-lived. A session’s scopes are fixed at launch. A long agent run needs refresh handled by the client, and the server should keep verifying expiry on every request.
- Implement paging deliberately. The sample returns one page of fifty. Following a server’s next link means fetching a URL the server composed; check each page with the same decision.
- Add granular filters as tools need them. Only
categoryon Observation is enforced. A scope filter the server parses and does not enforce is a leak waiting for the tool that touches it. Refuse tokens with filters you do not implement. - Put a person before writes.
preliminarystatus and a note naming the client make the origin visible. Whether an agent may write at all is a clinical governance decision, not an engineering one. - Send the audit log somewhere the MCP server cannot edit. One line per call with subject, client, tool, patient and outcome is the minimum. The FHIR server’s own audit will show only the MCP server’s identity.
- Rerun the lab on every FHIR server upgrade. The checks on returned resources exist because server behaviour changes.
SMART scopes express what an app was authorized to do. They do not express consent directives, sensitivity labels on individual records, or a legal basis for processing. Under GDPR, sending record content to a hosted model is processing that needs its own legal basis and agreements with the processor. None of that is modelled here. A deployment needs it settled before the first real record is read.
Decision framework
| Your situation | What to do | Why |
|---|---|---|
| Agent for one patient’s own data | Typed tools, patient from the token, no patient argument | The compartment is then impossible to get wrong from the model’s side |
| Clinician-facing agent | User-level scopes, patient named per call, across-patient tools kept separate | A patient-level scope must never satisfy a search across patients |
| Tempted by one generic FHIR tool | Do not, unless every parameter is allow-listed and every result checked | The naive version leaked on 9 of 12 hostile requests |
| Authorization server issues granular scopes | Enforce each filter in both the request and the result check, or refuse the token | An ignored filter widened access in this lab |
| Agent needs to write | One narrow create tool per record type, preliminary status, human confirmation | Subject and category come from the decision |
| FHIR server enforces SMART itself | Still enforce in the MCP server, and use token exchange for the upstream call | The caller’s token must not be passed through |
Key takeaways
- An MCP server over FHIR calls FHIR with its own credential, so it is the place where SMART scopes are enforced or lost.
- One tool per resource type and permission makes the scope mapping a table. Seven typed tools returned nothing outside scope across 39 calls with eight tokens.
- Filtering the tool list is a convenience. All 11 calls to tools that were not listed still reached the server, and were refused by the per-call check.
- A generic FHIR query tool with resource-type checks leaked on 9 of 12 hostile requests against HAPI FHIR 8.0.0. Making it safe turned it into the typed tools.
- Check what the FHIR server returns, not only what was asked. Refuse with one fixed sentence and put the reason in the audit log.
If you have built tools over a FHIR server with a different authorization model, or found a search feature that gets past checks like these, leave a comment.
Everything above ran in GitHub Actions on a hosted Linux runner with Python 3.13.18, MCP Python SDK 1.27.0 (protocol revision 2025-11-25), PyJWT 2.12.1, cryptography 46.0.6 and HAPI FHIR 8.0.0 from the hapiproject/hapi:v8.0.0 image, with other dependencies resolved as they stood on 7 April 2026. The lab loaded 21 synthetic resources, started the MCP server and the generic-tool server over streamable HTTP on loopback, and made 39 typed calls as eight tokens, five requests with unusable tokens, and 15 requests to each generic tool. Every answer was checked by a judge that shares no code with the server’s policy. 24 unit tests cover the scope parser, the policy and the judge. The same lab also passed against an in-memory stand-in, which does not implement _has or chained search; the figures in this article are from HAPI. Not run: any model; a real authorization server, token introspection or token exchange; an authenticated connection to the FHIR server; paging; other FHIR servers; consent or security labels. Nothing was measured for latency or cost. The run is here.
The complete sample for this article is on GitHub: nithinmohantk/blog-samples-working-repo/mcp-fhir-smart-scopes. Clone it with git clone https://github.com/nithinmohantk/blog-samples-working-repo.git and open the mcp-fhir-smart-scopes folder. Its README says how to run it and what has been verified.
Glossary
- FHIR— HL7’s standard for exchanging healthcare data as resources over a REST API. R4 is the version used here.
- SMART on FHIR— The profile of OAuth 2.0 that FHIR servers use to authorize apps, including the scope syntax.
- Scope— A string in an access token naming something the holder may do, such as patient/Observation.rs.
- Granular scope— A SMART v2 scope narrowed by search parameters, such as a category of observation.
- Patient context— The one patient a patient-level token is about, established when the app was launched.
- Compartment— The set of resources that belong to one patient.
- MCP— Model Context Protocol, the protocol through which an agent discovers and calls tools.
- Resource server— In OAuth, the service that accepts access tokens. The MCP server is one.
- Token passthrough— Forwarding a caller’s token to an upstream API. The MCP specification forbids it.
- Confused deputy— A component that uses its own authority on behalf of a caller who should not have it.
- _include and _revinclude— FHIR search parameters that add related resources of other types to the results.
- LOINC— The coding system used here to identify laboratory tests and measurements.
References & Further Reading
- → SMART App Launch 2.2.0: Scopes and Launch Context— Scope syntax, the cruds permissions, version 1 mapping, granular scopes and patient context
- → MCP specification 2025-11-25: Authorization— Audience validation, the ban on token passthrough, and insufficient-scope responses
- → MCP specification 2025-11-25: Security Best Practices— Token passthrough risks and scope minimization
- → mcp 1.27.0 on PyPI— The MCP Python SDK release used for the server and the lab client
- → Sample code for this article— The server, the scope parser and policy, the generic tools, the lab and its judge
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.