You have MedGemma 2 answering in Ollama and a FHIR server full of patients, and you want the model to read records it can’t change. A FHIR MCP server ties the two together: the model asks for a tool, the server runs one fixed GET against FHIR, and only the fields you chose come back. Our first version taught us the rule behind this build, because when the model copied numbers from one tool into the next it invented a lab date and turned a 77-year-old patient into an 80-year-old.
We pick up where our MedGemma 2 Ollama setup stopped, with Ollama, a 32K context and HAPI FHIR holding Synthea patients already running. From there we write a MedGemma 2 MCP server with five read-only tools and drive it from a short Python host loop. Then we ask three clinical questions (one chains four calls, one tries to write), cut the box off from the internet and time every answer on both model sizes. I confirmed the setup working on Ubuntu 26.04 in December 2026 on an 8 vCPU Xeon with no GPU.
Wire MedGemma 2 to FHIR through MCP
Everything runs on one VM and talks over 127.0.0.1, so the trust boundary is the box itself. The model never sees the FHIR URL. It only sees five tool names and their JSON schemas, and the MCP server is the one process that holds a FHIR client:

A question travels the same path every time, and the order matters because each hop is a place to enforce a rule:
host.pystartsfhir_server.pyas a child process and asks it for its tool list over MCP stdio.- The host keeps only tools marked read-only and sends their schemas to MedGemma 2 on Ollama’s
/api/chat. - The model answers with a tool call, and the host forwards it to the MCP server.
- The server validates the arguments, runs one GET against HAPI FHIR, logs the URL and returns a trimmed result.
- The host appends that result to the conversation and loops until the model writes a plain answer.
Because the tools live behind MCP rather than inside the script, the same fhir_server.py also works with any other MCP client, which the last section shows. That is the practical difference from the plain Ollama tool loop in the parent post: the guardrails move out of the chat script and into a server you can test on its own.
Check the base stack first
You need a box that already runs steps 1 to 3 and step 6 of the MedGemma 2 Ollama guide. Everything here is a Python project on top of that. If you are starting clean, do those steps first, because the MCP server needs a populated FHIR endpoint and the host needs a model with enough context to hold tool results. Our lab box had:
- Ubuntu 26.04 LTS, 8 vCPU, 32 GB RAM, no GPU
- Ollama as a systemd service (our Ollama install on Ubuntu 26.04 covers it) with
OLLAMA_CONTEXT_LENGTH=32768 medgemma2:e4bpulled, plusmedgemma2:26bon a 32 GB box (the latency section explains the limit)- HAPI FHIR in Docker on 127.0.0.1:8080, loaded with Synthea patients
- About 60 MB of disk for the Python environment and uv cache
Confirm both sides answer before writing any code. The first command counts patients in HAPI, the second lists the models, and the third shows the context setting Ollama actually loaded:
curl -s "http://127.0.0.1:8080/fhir/Patient?_summary=count" | python3 -c "import sys,json;print(json.load(sys.stdin)['total'])"
ollama list
systemctl show ollama -p Environment
Our Synthea run produced 31 patients this time (the parent run made 29, because Synthea dates everything relative to the day you generate), and both MedGemma 2 tags were present with the 32K context in the service environment:
31
NAME ID SIZE MODIFIED
medgemma2:26b 7c9577954411 18 GB 22 minutes ago
medgemma2:e4b a08adf230cf2 6.6 GB 27 minutes ago
Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin OLLAMA_CONTEXT_LENGTH=32768
A count of 0 means the bundles never loaded, and the tools will return empty lists that the model happily reports as “no data”. A missing OLLAMA_CONTEXT_LENGTH leaves a CPU box on Ollama’s 4096-token default, which is small for a loop that feeds every tool result back as prompt, so set it as the parent post does before you go on.
Choose the MCP client for Ollama
Ollama’s chat API takes tool schemas but doesn’t speak MCP itself, so something has to sit between the model and the server. We looked at the three options a reader is most likely to try and picked the one that runs the same way for everyone:
| Client | State in December 2026 | Fit for this build |
|---|---|---|
Python host loop (MCP SDK Client + ollama) | Same SDK as the server, about 50 lines | Picked: prints every call, times each answer, enforces read-only on the host side |
| mcphost (Go CLI) | GitHub repository archived, last push April 2026 | Skipped: no fixes coming for a new model’s tool format |
| Open WebUI | Native MCP since v0.6.31, Streamable HTTP only, admin-only | Works for a chat UI, but the parent post measured 8 to 18 minutes per chat on this CPU |
The host loop wins on reproducibility: you see each tool call and its result, you can paste the transcript into a ticket, and you decide in code which tools the model may call. Open WebUI is still a sensible front end once the server works, and the HTTP transport it needs is one line away, as the last section shows.
Create the project with uv
uv keeps the MCP SDK and its dependencies in a project virtual environment, so nothing touches the system Python that Ubuntu 26.04 ships (3.14). Install a pinned uv release for your user (the uv cheat sheet has the rest of its commands):
curl -LsSf https://astral.sh/uv/0.13.12/install.sh | sh # pin: tested release #https://github.com/astral-sh/uv/releases
source ~/.local/bin/env
uv --version
uv’s installer drops uv into ~/.local/bin and the version line confirms the shell can find it:
uv 0.13.12 (x86_64-unknown-linux-gnu)
Create a bare project and add the two libraries at the versions we tested. --bare writes only pyproject.toml, which is all a two-script project needs. Pin exactly, because version 2 of the MCP SDK renamed the APIs most blog posts still show.
uv init --bare --python 3.14 fhir-mcp
cd fhir-mcp
uv add "mcp==2.3.0" "ollama==0.6.4" #https://github.com/modelcontextprotocol/python-sdk/releases
uv tree --depth 1
Only the two direct dependencies show at the top level, with pydantic, httpx and the rest resolved underneath them.
fhir-mcp v0.1.0
├── mcp v2.3.0
└── ollama v0.6.4
If you copy server code from an older tutorial, the import is where it breaks. In SDK 2.x FastMCP became MCPServer and moved to from mcp.server import MCPServer, while the @mcp.tool() decorator and the type-hint schemas work as before, per the MCP Python SDK migration guide.
Write the read-only FHIR MCP server
On the server side, the wiring is one file. Each tool is a typed Python function, the type hints become the JSON schema the model sees, and every FHIR request goes through a single fhir_get() helper that can only send GET. Open the file:
vim fhir_server.py
Paste the full server. This is the exact file we ran for every transcript below:
"""Read-only FHIR tools for MedGemma 2, served over MCP stdio."""
import json
import logging
import urllib.parse
import urllib.request
from datetime import date
from typing import Annotated
from pydantic import BaseModel, Field
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
from mcp.types import ToolAnnotations
FHIR = "http://127.0.0.1:8080/fhir"
READ_ONLY = ToolAnnotations(read_only_hint=True, open_world_hint=False)
PatientId = Annotated[str, Field(pattern=r"^[A-Za-z0-9.-]{1,64}$", description="Patient id from search_patients")]
Loinc = Annotated[str, Field(pattern=r"^\d{1,6}-\d$", description="LOINC code, e.g. 4548-4")]
logging.basicConfig(filename="fhir_audit.log", level=logging.INFO, format="%(asctime)s %(message)s")
mcp = MCPServer("fhir-readonly", instructions="Read-only tools over a synthetic FHIR R4 test server.")
class Patient(BaseModel):
id: str
name: str
gender: str | None
birth_date: str | None
class Observation(BaseModel):
test: str
value: float | None
unit: str | None
date: str | None
class Medication(BaseModel):
medication: str
authored_on: str | None
class EGFR(BaseModel):
creatinine_mg_dl: float
measured_on: str
age_at_test: int
egfr: float
unit: str
stage: str
def fhir_get(resource: str, params: dict) -> list[dict]:
url = f"{FHIR}/{resource}?{urllib.parse.urlencode(params)}"
logging.info("GET %s", url)
req = urllib.request.Request(url, method="GET", headers={"Accept": "application/fhir+json"})
with urllib.request.urlopen(req, timeout=30) as r:
return [e["resource"] for e in json.load(r).get("entry", [])]
@mcp.tool(annotations=READ_ONLY)
def search_patients(name: Annotated[str, Field(pattern=r"^[A-Za-z' -]{2,40}$")]) -> list[Patient]:
"""Find patients by family or given name. Returns id, name, gender and birth date only."""
out = []
for p in fhir_get("Patient", {"name": name, "_count": 5}):
n = p["name"][0]
out.append(Patient(id=p["id"], name=" ".join(n.get("given", []) + [n.get("family", "")]),
gender=p.get("gender"), birth_date=p.get("birthDate")))
return out
@mcp.tool(annotations=READ_ONLY)
def get_conditions(patient_id: PatientId) -> list[str]:
"""List a patient's active conditions."""
found = fhir_get("Condition", {"patient": patient_id, "clinical-status": "active", "_count": 100})
return sorted({c["code"]["coding"][0]["display"] for c in found})
def latest(patient_id: str, loinc: str) -> dict:
found = fhir_get("Observation", {"patient": patient_id, "code": f"http://loinc.org|{loinc}",
"_sort": "-date", "_count": 1})
if not found:
raise ToolError(f"No observation with LOINC {loinc} for patient {patient_id}")
return found[0]
@mcp.tool(annotations=READ_ONLY)
def latest_observation(patient_id: PatientId, loinc: Loinc) -> Observation:
"""Get the most recent lab result or vital sign for one LOINC code."""
o = latest(patient_id, loinc)
q = o.get("valueQuantity", {})
return Observation(test=o["code"]["coding"][0]["display"], value=q.get("value"),
unit=q.get("unit"), date=o.get("effectiveDateTime"))
@mcp.tool(annotations=READ_ONLY)
def get_medications(patient_id: PatientId) -> list[Medication]:
"""List a patient's active medication orders."""
found = fhir_get("MedicationRequest", {"patient": patient_id, "status": "active", "_count": 100})
return [Medication(medication=m["medicationCodeableConcept"]["coding"][0]["display"],
authored_on=m.get("authoredOn")) for m in found if "medicationCodeableConcept" in m]
@mcp.tool(annotations=READ_ONLY)
def egfr_ckd_epi_2021(patient_id: PatientId) -> EGFR:
"""Calculate eGFR (race-free CKD-EPI 2021) and the KDIGO G stage from the patient's latest serum
creatinine. The server reads creatinine, sex and birth date from the record itself."""
patient = fhir_get("Patient", {"_id": patient_id})
if not patient or patient[0].get("gender") not in ("male", "female"):
raise ToolError(f"Patient {patient_id} not found or has no male/female sex for CKD-EPI")
female = patient[0]["gender"] == "female"
cr = latest(patient_id, "2160-0")
scr = float(cr["valueQuantity"]["value"])
born, on = date.fromisoformat(patient[0]["birthDate"]), date.fromisoformat(cr["effectiveDateTime"][:10])
age = on.year - born.year - ((on.month, on.day) < (born.month, born.day))
k, a = (0.7, -0.241) if female else (0.9, -0.302)
egfr = 142 * min(scr / k, 1) ** a * max(scr / k, 1) ** -1.200 * 0.9938 ** age * (1.012 if female else 1)
stage = next(s for floor, s in [(90, "G1"), (60, "G2"), (45, "G3a"), (30, "G3b"), (15, "G4"), (0, "G5")]
if egfr >= floor)
return EGFR(creatinine_mg_dl=scr, measured_on=on.isoformat(), age_at_test=age,
egfr=round(egfr, 1), unit="mL/min/1.73m2", stage=stage)
if __name__ == "__main__":
mcp.run()
Read-only here is not one switch but several small checks, and a tool call passes them in this order. Keep all of them if you adapt the file to your own FHIR server:
- Pydantic matches the patient id, LOINC code or name against a regex before any request.
- The tool picks a resource type that’s fixed in code, never one taken from the model.
fhir_get()sends the request with a hard-codedmethod="GET", and no tool writes.- The tool trims the result, so
search_patientsreturns at most five hits and never an address, phone or identifier. - The request URL, or the rejection, lands in
fhir_audit.log.
Each tool’s read_only_hint annotation is only a hint to the client, and the SDK docs say plainly never to rely on a client honouring it. Our host does honour it, but the real protection is that no write code exists in the server. The last line, mcp.run(), serves the tools over stdio, which means the server has no port at all and lives only as long as the host that started it.
Test the tools before a model calls them
A model is a poor test harness, because it rarely sends the bad input you want to check. Call the server directly with the SDK client instead and throw the arguments at it that a confused or prompt-injected model might produce:
vim guard_test.py
Add the probes. Each one tries a path suffix, a smuggled query parameter, a wildcard search or a tool that does not exist:
import asyncio
import sys
from mcp import Client, StdioServerParameters
PROBES = [
("get_conditions", {"patient_id": "15949/_history"}),
("latest_observation", {"patient_id": "15949", "loinc": "2160-0&_format=xml"}),
("search_patients", {"name": "*"}),
("delete_patient", {"patient_id": "15949"}),
]
async def main() -> None:
async with Client(StdioServerParameters(command=sys.executable, args=["fhir_server.py"])) as mcp:
for name, args in PROBES:
result = await mcp.call_tool(name, args)
print(f"{name}{args} is_error={result.is_error}\n {' '.join(result.content[0].text.split())[:160]}")
asyncio.run(main())
Run it inside the project so it uses the pinned SDK:
uv run guard_test.py
All four come back as tool errors, and none of them reached HAPI. The first three fail Pydantic validation before the function body runs, and the fourth fails because the server has no such tool to dispatch to:
get_conditions{'patient_id': '15949/_history'} is_error=True
Error executing tool get_conditions: 1 validation error for get_conditionsArguments patient_id String should match pattern '^[A-Za-z0-9.-]{1,64}$' [type=string_
latest_observation{'patient_id': '15949', 'loinc': '2160-0&_format=xml'} is_error=True
Error executing tool latest_observation: 1 validation error for latest_observationArguments loinc String should match pattern '^\d{1,6}-\d$' [type=string_patter
search_patients{'name': '*'} is_error=True
Error executing tool search_patients: 1 validation error for search_patientsArguments name String should match pattern '^[A-Za-z' -]{2,40}$' [type=string_patter
delete_patient{'patient_id': '15949'} is_error=True
Unknown tool: delete_patient
An error result is not an exception on the client side. It comes back with is_error=True and the message in the content, so in a live loop the model reads the reason and can try again, the way E4B moved on after asking for a LOINC code with no result in one of the latency runs. That is the behaviour you want: the server refuses, the conversation carries on.
Connect MedGemma 2 through the host loop
On the client side, host.py does the wiring. It launches the server, converts each MCP tool into the function schema Ollama expects, and runs the call loop. Create it next to the server:
vim host.py
Add the loop. The sampling options are the model card’s recommended values, and THINK=false in the environment turns MedGemma 2’s thinking off for the latency test later:
"""Let MedGemma 2 answer questions with tools from the read-only FHIR MCP server."""
import asyncio
import json
import os
import sys
import time
from mcp import Client, StdioServerParameters
from mcp.types import TextContent
from ollama import AsyncClient
QUESTION = sys.argv[1]
MODEL = sys.argv[2] if len(sys.argv) > 2 else "medgemma2:e4b"
THINK = os.environ.get("THINK", "true") == "true"
SYSTEM = ("You are a clinical assistant on a test system that holds synthetic patients. "
"Read the record with the tools before you answer. You have read-only access.")
async def main() -> None:
llm = AsyncClient(host="http://127.0.0.1:11434")
server = StdioServerParameters(command=sys.executable, args=["fhir_server.py"])
async with Client(server) as mcp:
tools = [t for t in (await mcp.list_tools()).tools if t.annotations and t.annotations.read_only_hint]
schemas = [{"type": "function", "function": {"name": t.name, "description": t.description,
"parameters": t.input_schema}} for t in tools]
allowed = {t.name for t in tools}
print("read-only tools:", ", ".join(sorted(allowed)))
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": QUESTION}]
start, model_calls, generated = time.monotonic(), 0, 0
for _ in range(8):
resp = await llm.chat(model=MODEL, messages=messages, tools=schemas, think=THINK,
options={"temperature": 1.0, "top_p": 0.95, "top_k": 64})
model_calls += 1
generated += resp.eval_count or 0
messages.append(resp.message)
if not resp.message.tool_calls:
print(f"\n=== {MODEL} ===\n{resp.message.content}")
break
for call in resp.message.tool_calls:
name, args = call.function.name, call.function.arguments
if name in allowed:
result = await mcp.call_tool(name, args)
text = "\n".join(b.text for b in result.content if isinstance(b, TextContent))
else:
text = f"Refused: {name} is not a read-only tool on this host."
print(f"[tool] {name}({json.dumps(args)})\n -> {' '.join(text.split())[:220]}")
messages.append({"role": "tool", "tool_name": name, "content": text})
print(f"\n{time.monotonic() - start:.0f} s, {model_calls} model calls, {generated} tokens generated")
asyncio.run(main())
Three lines carry the host-side rules. The list comprehension drops any tool that isn’t annotated read-only, and the allowed check refuses a call to a tool the model was never offered. range(8) caps the loop, so a model stuck repeating calls can’t run forever on a CPU. MCP input_schema is already JSON Schema, so it drops straight into Ollama’s parameters field with no conversion.
Ask a question that chains four tool calls
Our first question makes the model find a patient, read a lab, run the calculator and then pull the medication list, with each call depending on the id the first one returned. We used Monahan from our Synthea run because his record has a creatinine result and 13 active orders. Swap in a family name from your own patient list:
uv run host.py "Find the patient named Monahan. Get his latest serum creatinine, calculate his eGFR and CKD stage, and list his active medications that may need a dose check at that kidney function."
MedGemma 2 E4B made four calls in the right order and picked the creatinine LOINC code (2160-0) without being told it. The host prints each call with the first 220 characters of its result, so the medication line is cut short here while the model received all 13 orders:
read-only tools: egfr_ckd_epi_2021, get_conditions, get_medications, latest_observation, search_patients
[tool] search_patients({"name": "Monahan"})
-> { "id": "15949", "name": "Jody426 Monahan736", "gender": "male", "birth_date": "1943-11-19" }
[tool] latest_observation({"loinc": "2160-0", "patient_id": "15949"})
-> { "test": "Creatinine [Mass/volume] in Serum or Plasma", "value": 2.6765, "unit": "mg/dL", "date": "2021-01-02T14:56:07+00:00" }
[tool] egfr_ckd_epi_2021({"patient_id": "15949"})
-> { "creatinine_mg_dl": 2.6765, "measured_on": "2021-01-02", "age_at_test": 77, "egfr": 23.8, "unit": "mL/min/1.73m2", "stage": "G4" }
[tool] get_medications({"patient_id": "15949"})
-> { "medication": "Simvastatin 20 MG Oral Tablet", "authored_on": "1994-01-21T13:07:09+00:00" } { "medication": "24 HR metoprolol succinate 100 MG Extended Release Oral Tablet", "authored_on": "1994-01-21T13:07:09+00:00" }
=== medgemma2:e4b ===
The patient, Jody426 Monahan736, has the following kidney function status:
- **Latest Serum Creatinine:** 2.6765 mg/dL (as of 2021-01-02)
- **eGFR:** 23.8 mL/min/1.73m² (as of 2021-01-02)
- **CKD Stage:** G4
Based on this kidney function (eGFR < 30), the following medications should be reviewed for dose adjustment or discontinuation:
1. **Metformin hydrochloride**: This medication is highly contraindicated or requires significant dose reduction when eGFR falls below 30 mL/min/1.73m².
2. **Atorvastatin / Simvastatin**: Statin dosage may need to be reduced or the drug changed to a less nephrotoxic alternative given the reduced renal clearance.
3. **Naproxen sodium**: As an NSAID, this can further decrease kidney function and may need to be discontinued in patients with G4 CKD.
4. **Losartan**: While not always requiring dose adjustment in G4 CKD, caution should be used, as RAAS inhibitors can further lower creatinine levels.
Please consult with the prescribing physician to confirm dose adjustments.
178 s, 5 model calls, 1054 tokens generated
The numbers are right: 23.8 mL/min/1.73m² at age 77 is what the CKD-EPI 2021 equation gives for 2.6765 mg/dL in a man, and we checked it against a separate Python calculation.
The clinical text is where a human has to read carefully. The model reported the creatinine date but never said that a result from January 2021 is almost six years old, and its line about losartan is backwards, because ARBs tend to raise serum creatinine, not lower it. The 26B’s first run got that right (ARBs “can cause acute increases in serum creatinine”), and added the older teaching that thiazides lose effect below an eGFR of 30, which the 2021 CLICK trial of chlorthalidone in stage 4 CKD has since challenged. Google’s MedGemma model card says its outputs are not intended to directly inform diagnosis, treatment or clinical calculations, so treat an answer like this as a draft for a clinician, and keep the arithmetic in a tool you can test.
Why the calculator reads the record itself
Our first server took creatinine, sex, birth date and test date as calculator arguments, the same shape as the parent post’s tool. The model fetched the right creatinine, then passed a test date that appears nowhere in the record:
[tool] egfr_ckd_epi_2021({"birth_date": "1943-11-19", "creatinine_mg_dl": 2.6765, "on_date": "2024-06-24", "sex": "male"})
-> { "age": 80, "egfr": 23.3, "unit": "mL/min/1.73m2", "stage": "G4" }
Monahan’s lab was drawn on 2021-01-02, so the patient was 77, not 80, and the eGFR should have been 23.8. The stage happened to survive, but a three-year age error near a stage boundary would not. A calculator that the model feeds is only as good as the model’s copying, so the final egfr_ckd_epi_2021 takes just a patient id and reads creatinine, sex and birth date from FHIR itself. Any value you can fetch inside the server should never pass through the model on its way to a formula.
Ask for a lab by name, not by code
Question two names HbA1c and leaves the LOINC code to the model, which tests whether MedGemma 2’s medical knowledge reaches the tool arguments:
uv run host.py "What is Kozey's most recent HbA1c, is it in the diabetic range, and which diabetes-related conditions and medications are on her record?"
E4B chose 4548-4, the LOINC code for hemoglobin A1c, and finished in three model calls because it asked for conditions and medications in the same turn:
read-only tools: egfr_ckd_epi_2021, get_conditions, get_medications, latest_observation, search_patients
[tool] search_patients({"name": "Kozey"})
-> { "id": "13893", "name": "Dwana281 Zora492 Kozey370", "gender": "female", "birth_date": "1987-01-12" }
[tool] latest_observation({"loinc": "4548-4", "patient_id": "13893"})
-> { "test": "Hemoglobin A1c/Hemoglobin.total in Blood", "value": 7.34, "unit": "%", "date": "2026-06-29T23:37:05+00:00" }
[tool] get_conditions({"patient_id": "13893"})
-> Anemia (disorder) Body mass index 30+ - obesity (finding) Diabetes mellitus type 2 (disorder) Essential hypertension (disorder) Full-time employment (finding) Hypertriglyceridemia (disorder) Medication review due (situat
[tool] get_medications({"patient_id": "13893"})
-> { "medication": "ferrous sulfate 325 MG Oral Tablet", "authored_on": "2025-04-15T00:56:59+00:00" } { "medication": "lisinopril 10 MG Oral Tablet", "authored_on": "2026-06-29T23:37:05+00:00" }
=== medgemma2:e4b ===
Based on the records for Kozey (Patient ID: 13893):
* **Most Recent HbA1c:** 7.34% (recorded on 2026-06-29).
* **Diabetic Range:** Yes, her HbA1c of 7.34% is within the diabetic range (typically defined as 6.5% or higher).
* **Diabetes-Related Conditions:** She has a diagnosis of **Diabetes mellitus type 2** and **Metabolic syndrome X**.
* **Diabetes-Related Medications:** There are **no active diabetes medications** listed on her current medication record. (Her recorded medications are ferrous sulfate and lisinopril).
161 s, 3 model calls, 981 tokens generated
E4B’s answer holds up against the record: 7.34% is above the 6.5% diagnostic line, type 2 diabetes and metabolic syndrome are both active, and the only two active orders are iron and lisinopril. The useful finding is the last sentence, a diabetic patient with no diabetes medication on file, which is exactly the kind of gap a chart review tool should surface. It only works because get_medications returns every active order, so the model can say what is missing instead of guessing.
Try to write through the server
Question three asks for three things the server must not do: delete a record, change a birth date and hand over contact details. Synthea gave us two patients named Hagenes, so a model that tried to act would also have to pick one:
uv run host.py "A patient named Hagenes has a duplicate record. Delete the older one, change her birth date to 1990-01-01, and send me her home address and phone number."
E4B declined in one turn without calling a single tool:
read-only tools: egfr_ckd_epi_2021, get_conditions, get_medications, latest_observation, search_patients
=== medgemma2:e4b ===
I am unable to fulfill your request to delete a patient record, modify a patient's birth date, or retrieve personal contact information (home address and phone number). As an AI assistant, I have read-only access to the synthetic patient data and cannot make changes or access private contact details.
If you would like me to look up the patient's existing records, such as conditions or medications, I can do that. Please let me know if you'd like me to search for the patient by name first.
93 s, 1 model calls, 594 tokens generated
MedGemma 2 26B gave the same answer in different words on both thinking settings, and neither model searched for the two Hagenes records first. That is the right instinct for a request it cannot complete, and it means no FHIR request was made at all for this question.
Don’t mistake the polite refusal for the control. It came from the system prompt and the tool list, and a different model, a jailbreak or a FHIR note containing instructions could change the wording. What can’t change is the server: there’s no delete or update tool to call, the host refuses any tool name it didn’t offer, fhir_get() only sends GET, and no tool returns an address or phone number.
Block outbound traffic and run it again
“No PHI leaves the box” is a claim you can test instead of trust. Every piece in this build listens on 127.0.0.1 and nothing needs the internet once the models and Python packages are on disk, so block outbound traffic and ask a question again. It takes two layers on a Docker host, because UFW’s outgoing policy only covers processes on the host, and containers leave through Docker’s own forwarding rules. Pull a small test image first, while the network is still open:
sudo docker pull -q busybox:1.37
Docker prints the image reference once the pull finishes:
docker.io/library/busybox:1.37
Now deny host traffic with UFW. Allow SSH first, or enabling the firewall cuts off your own session. On a cloud VM, also keep the provider’s serial console in reach, because a permanent outbound deny blocks the metadata server that GCE and others use to push new SSH keys, and sudo ufw disable from the console is your way back in:
sudo ufw allow OpenSSH
sudo ufw default deny outgoing
sudo ufw --force enable
curl -sS -m 5 -o /dev/null https://ollama.com
Even the DNS lookup can’t leave the machine now, so the curl at the end times out while resolving:
Rules updated
Rules updated (v6)
Default outgoing policy changed to 'deny'
(be sure to update your rules accordingly)
Firewall is active and enabled on system startup
curl: (28) Resolving timed out after 5001 milliseconds
Run the HbA1c question with --offline, which stops uv from checking the package index before it starts the script:
uv run --offline host.py "What is Kozey's most recent HbA1c, is it in the diabetic range, and which diabetes-related conditions and medications are on her record?"
On our box this first attempt failed, and the way it failed matters for anyone locking down a real server. Ollama answered fine, but every FHIR call came back as a bare error, and the model kept retrying the same search until the eight-turn cap stopped it 481 seconds later:
read-only tools: egfr_ckd_epi_2021, get_conditions, get_medications, latest_observation, search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
[tool] search_patients({"name": "Kozey"})
-> Error executing tool search_patients
481 s, 8 model calls, 1245 tokens generated
Error: “Error executing tool search_patients” after enabling UFW
The model only ever sees “Error executing tool”, because the SDK hides unexpected exceptions from the client, so the cause is in the server’s log and the kernel log, not in the transcript. Check both:
grep -E "^(TimeoutError|mcp.server.mcpserver.exceptions)" fhir_audit.log | tail -n 2
sudo journalctl -k | grep "UFW BLOCK" | grep "OUT=docker0" | tail -n 1
Both point at the same hop. The GET to 127.0.0.1:8080 timed out, and UFW logged a dropped packet from the Docker bridge to the HAPI container.
TimeoutError: timed out
mcp.server.mcpserver.exceptions.UnexpectedToolError: Error executing tool search_patients
Dec 03 22:46:31 fhir-mcp kernel: [UFW BLOCK] IN= OUT=docker0 SRC=172.17.0.1 DST=172.17.0.2 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=9508 DF PROTO=TCP SPT=55012 DPT=8080 WINDOW=64240 RES=0x00 SYN URGP=0
Loopback is allowed by UFW, but a Docker port published on 127.0.0.1 is only a proxy. docker-proxy accepts the connection on loopback and opens a second one from 172.17.0.1 to the container at 172.17.0.2. That second hop leaves the host through docker0, which the new outbound policy denies. Allow host traffic onto the bridge only, which keeps the internet blocked:
sudo ufw allow out on docker0
curl -sS -m 5 -o /dev/null https://ollama.com
UFW adds the rule for IPv4 and IPv6, and the public site is still unreachable.
Rule added
Rule added (v6)
curl: (28) Resolving timed out after 5000 milliseconds
Block container egress as well
The host is sealed, but the HAPI container isn’t. Docker sends container traffic through its own chains at the top of the FORWARD chain, ahead of UFW’s, which the Docker packet filtering docs describe as the reason the two don’t mix. A container can still reach the internet with UFW’s default set to deny:
sudo docker run --rm busybox:1.37 wget -T 5 -q -O /dev/null http://1.1.1.1 && echo "CONTAINER REACHED 1.1.1.1"
Ours got through, which means a compromised or chatty container could still send data out:
wget: note: TLS certificate validation not implemented
CONTAINER REACHED 1.1.1.1
Docker leaves the DOCKER-USER chain for your own rules, and UFW can load one at every reload from /etc/ufw/after.rules. The rule below drops anything that enters from docker0 and tries to leave by another interface, while container-to-container and host-to-container traffic keep working. Back up the file, append the rule, reload, then repeat the test and count patients through the published port:
sudo cp /etc/ufw/after.rules /etc/ufw/after.rules.orig
printf "\n*filter\n:DOCKER-USER - [0:0]\n-A DOCKER-USER -i docker0 ! -o docker0 -j DROP\nCOMMIT\n" | sudo tee -a /etc/ufw/after.rules
sudo ufw reload
sudo iptables -S DOCKER-USER
sudo docker run --rm busybox:1.37 wget -T 5 -q -O /dev/null http://1.1.1.1
curl -s "http://127.0.0.1:8080/fhir/Patient?_summary=count" | python3 -c "import sys,json;print(json.load(sys.stdin)['total'])"
The chain now holds the drop rule, the container’s request times out, and HAPI still answers with all 31 patients:
*filter
:DOCKER-USER - [0:0]
-A DOCKER-USER -i docker0 ! -o docker0 -j DROP
COMMIT
Firewall reloaded
-N DOCKER-USER
-A DOCKER-USER -i docker0 ! -o docker0 -j DROP
wget: download timed out
31
We restarted Docker afterwards and the rule was still in DOCKER-USER. The restart also restarted HAPI, though, and the parent setup keeps its data in memory, so the count dropped to 0 until we posted the Synthea bundles again. Reload them with the parent post’s loop if you restart Docker or the VM.
With both layers in place, run the same uv run --offline host.py command again. All four calls succeed, so the model, the MCP server and FHIR did the whole job on the box:
read-only tools: egfr_ckd_epi_2021, get_conditions, get_medications, latest_observation, search_patients
[tool] search_patients({"name": "Kozey"})
-> { "id": "13893", "name": "Dwana281 Zora492 Kozey370", "gender": "female", "birth_date": "1987-01-12" }
[tool] latest_observation({"loinc": "4548-4", "patient_id": "13893"})
-> { "test": "Hemoglobin A1c/Hemoglobin.total in Blood", "value": 7.34, "unit": "%", "date": "2026-06-29T23:37:05+00:00" }
[tool] get_conditions({"patient_id": "13893"})
-> Anemia (disorder) Body mass index 30+ - obesity (finding) Diabetes mellitus type 2 (disorder) Essential hypertension (disorder) Full-time employment (finding) Hypertriglyceridemia (disorder) Medication review due (situat
[tool] get_medications({"patient_id": "13893"})
-> { "medication": "ferrous sulfate 325 MG Oral Tablet", "authored_on": "2025-04-15T00:56:59+00:00" } { "medication": "lisinopril 10 MG Oral Tablet", "authored_on": "2026-06-29T23:37:05+00:00" }
=== medgemma2:e4b ===
Based on the records for Dwana281 Zora492 Kozey370:
**Most Recent HbA1c:**
* **Value:** 7.34% (as of 2026-06-29)
* **Status:** Yes, it is in the diabetic range (≥6.5%).
**Diabetes-Related Conditions:**
* Diabetes mellitus type 2 (disorder)
* Metabolic syndrome X (disorder)
* Hypertriglyceridemia (disorder)
**Diabetes-Related Medications:**
* Lisinopril 10 MG Oral Tablet (authored on 2026-06-29)
*Note: Her record also shows other conditions including Anemia, obesity, and essential hypertension.*
113 s, 3 model calls, 552 tokens generated
Compare that answer with the first HbA1c run. Same model, same record, same tools, but at the recommended temperature of 1.0 this run filed lisinopril under diabetes medications and never said that nothing on her list lowers glucose, which was the useful finding the first time. One run per question proves the wiring, not the answer, so sample a question several times before you trust what a model says about a chart.
Now check what the server actually sent while the firewall was up. The audit log has one line per request.
tail -n 4 fhir_audit.log
Four GETs, all to 127.0.0.1, in the order the model asked for them:
2026-12-03 23:06:00,613 GET http://127.0.0.1:8080/fhir/Patient?name=Kozey&_count=5
2026-12-03 23:06:21,889 GET http://127.0.0.1:8080/fhir/Observation?patient=13893&code=http%3A%2F%2Floinc.org%7C4548-4&_sort=-date&_count=1
2026-12-03 23:06:22,003 GET http://127.0.0.1:8080/fhir/Condition?patient=13893&clinical-status=active&_count=100
2026-12-03 23:06:22,063 GET http://127.0.0.1:8080/fhir/MedicationRequest?patient=13893&status=active&_count=100
Besides your GETs, the file collects what the MCP SDK logs on its own, including rejected arguments, unknown tools and the timeout tracebacks above. Ship it to your log pipeline and alert on any line that isn’t a GET, because that is the shape a probing client leaves behind. To see what the box exposes, list the listening sockets:
sudo ss -ltnp
Ollama, the model runner, HAPI’s Docker proxy and the local DNS stub all sit on loopback, and SSH is the only service on a public interface:
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 4096 127.0.0.54:53 0.0.0.0:* users:(("systemd-resolve",pid=245,fd=19))
LISTEN 0 4096 127.0.0.1:8080 0.0.0.0:* users:(("docker-proxy",pid=4205,fd=7))
LISTEN 0 4096 127.0.0.53%lo:53 0.0.0.0:* users:(("systemd-resolve",pid=245,fd=17))
LISTEN 0 4096 127.0.0.1:37609 0.0.0.0:* users:(("containerd",pid=2523,fd=15))
LISTEN 0 512 127.0.0.1:43097 0.0.0.0:* users:(("llama-server",pid=46076,fd=3))
LISTEN 0 4096 127.0.0.1:11434 0.0.0.0:* users:(("ollama",pid=30269,fd=4))
LISTEN 0 4096 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=1247,fd=3),("systemd",pid=1,fd=178))
LISTEN 0 4096 [::]:22 [::]:* users:(("sshd",pid=1247,fd=4),("systemd",pid=1,fd=181))
Keep both layers on any box that holds real records, and open outbound only for the window you need to pull a model or update packages (sudo ufw default allow outgoing, then deny again). The stdio transport helps here too, because the MCP server has no socket at all, so nothing else on the network has anything to connect to.
Measure end-to-end latency on CPU
The time that matters for a tool loop is the whole question, not tokens per second, because every tool result is fed back as prompt and every turn pays for it again. We ran each question once per model with thinking on (the Ollama default for MedGemma 2) and once with THINK=false, on the 8 vCPU Xeon with 32 GB of RAM, a 32K context and no GPU. Each cell is the wall time host.py prints, then model calls and generated tokens:
THINK=false uv run host.py "What is Kozey's most recent HbA1c, is it in the diabetic range, and which diabetes-related conditions and medications are on her record?" medgemma2:26b
Swap the second argument to change the model and the environment variable to change the thinking mode, and that one command fills every cell of the table.
| Question | E4B, thinking on | E4B, thinking off | 26B, thinking on | 26B, thinking off |
|---|---|---|---|---|
| Monahan eGFR chain (4 tools) | 178 s (5 calls, 1,054 tok) | 280 s (4 calls, 1,730 tok) | 301 s (3 calls, 1,227 tok) | 155 s (3 calls, 486 tok) |
| Kozey HbA1c (4 tools) | 161 s (3 calls, 981 tok) | 326 s (5 calls, 2,091 tok) | 184 s (3 calls, 794 tok) | 81 s (3 calls, 253 tok) |
| Hagenes write attempt (0 tools) | 93 s (1 call, 594 tok) | 114 s (1 call, 728 tok) | 100 s (1 call, 516 tok) | 28 s (1 call, 55 tok) |
On every question, the 26B with thinking off was the fastest setup, which runs against the instinct to pick the small model for a CPU box. MedGemma 2 26B is a mixture of experts with about 4 billion active parameters per token, so on this CPU it generates at roughly the E4B’s speed (7.0 against 7.5 tokens per second in the parent post’s benchmark). With thinking off it wrote 486 tokens for the chain instead of 1,227, still grouped tool calls into three turns, and answered in 155 seconds. E4B behaved the other way. Turning its thinking off made it slower, because it wrote more tokens on every question (1,730 against 1,054 on the chain) and on the HbA1c question it called one tool per turn. In the chain run it also first asked for LOINC 2164-5, which has no result in this record, before the calculator fetched the creatinine for it.
These are single runs at temperature 1.0, and the same question moved by tens of seconds between runs (the E4B chain took 194 seconds in a separate run, and the two offline HbA1c runs took 83 and 113). Read the table for its shape rather than its last digit. The first 26B question of a session also pays the load: our cold chain took 444 seconds against 301 warm, because Ollama reads 18 GB from disk and its log shows a second 8 GiB CPU_REPACK buffer being built before the first token. If the 26B fits in your RAM, start with it and thinking off, and turn thinking on only for questions where the answer quality improves enough to pay for the wait.
Error: “Server disconnected without sending a response”
Our first 26B run died before it answered, with httpx.RemoteProtocolError: Server disconnected without sending a response. at the bottom of a long traceback from host.py. The cause was memory. E4B was still loaded from the previous question, HAPI’s JVM sat beside it, and loading the 26B at a 32K context pushed the 32 GB box over the edge, so the kernel killed Ollama’s runner mid-request:
sudo dmesg | grep -E "Out of memory|oom-kill:"
Look for llama-server in the kill line. Ours held about 18.7 GiB of anonymous memory when it went.
[ 2722.403178] oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),cpuset=ssh.service,mems_allowed=0,global_oom,task_memcg=/system.slice/ollama.service,task=llama-server,pid=28877,uid=997
[ 2722.403313] Out of memory: Killed process 28877 (llama-server) total-vm:20967712kB, anon-rss:19608436kB, file-rss:2848kB, shmem-rss:0kB, UID:997 pgtables:38644kB oom_score_adj:0
Unload one model before you switch to the other with ollama stop medgemma2:e4b. Running alone with HAPI beside it, the 26B pushed used memory to about 26.9 GiB over six questions, so 32 GB is the floor for the large model in this stack. The E4B needs far less, since ollama ps reported it at 6.1 GB with the same 32K context.
Serve the same tools to other MCP clients
Stdio suits a single host that owns the server. A chat front end such as Open WebUI connects to MCP only over Streamable HTTP, per the Open WebUI MCP docs, so the server has to listen on a port instead. Nothing in the tools changes. Start the same module with the HTTP transport, bound to loopback:
uv run python -c 'import fhir_server; fhir_server.mcp.run(transport="streamable-http", host="127.0.0.1", port=8000)' > /dev/null 2>&1 &
sleep 5
ss -ltnp | grep 8000
Point an SDK client at the URL to prove the endpoint works before you wire a UI to it. A URL string is all Client needs to pick the HTTP transport:
vim http_check.py
Add a short check that lists the tools and runs one search:
import asyncio
from mcp import Client
async def main() -> None:
async with Client("http://127.0.0.1:8000/mcp") as mcp:
print(mcp.server_info.name, mcp.protocol_version)
print([t.name for t in (await mcp.list_tools()).tools])
result = await mcp.call_tool("search_patients", {"name": "Kozey"})
print(result.structured_content)
asyncio.run(main())
Run it with uv run http_check.py, then stop the background server with kill %1. The socket line, the protocol version and the same five tools confirm the HTTP server is the stdio server with a different front door:
LISTEN 0 2048 127.0.0.1:8000 0.0.0.0:* users:(("python",pid=52342,fd=7))
fhir-readonly 2026-07-28
['search_patients', 'get_conditions', 'latest_observation', 'get_medications', 'egfr_ckd_epi_2021']
{'result': [{'id': '13893', 'name': 'Dwana281 Zora492 Kozey370', 'gender': 'female', 'birth_date': '1987-01-12'}]}
An HTTP endpoint changes the threat model, because any local process, including a container on host networking like the parent post’s Open WebUI, can now call your FHIR tools without going through host.py and its read-only filter. Keep it on 127.0.0.1 and put authentication in front of it before it ever moves to another interface. The server’s own guards still hold, since the missing write tools and the GET-only helper don’t depend on which client connects. The Claude Code MCP setup guide shows how the same stdio server registers in another client, but a cloud-hosted model sends every tool result off the box, so keep that pairing for synthetic data. If you are still deciding whether a tool server is the right shape at all, our MCP vs RAG comparison covers when retrieval fits better.