FHIR MCP Server
Bridges MCP clients and AI/LLM tools to FHIR APIs for healthcare data discovery and management.
Discover FHIR resource capabilities, valid search parameters, and custom operations with
get_capabilities.Search FHIR resources by type and search parameters, with optional FHIRPath response filtering.
Read a single FHIR resource by type and ID, including custom operations and filtered responses.
Create new FHIR resources.
Update existing FHIR resources by replacing their full content.
Delete FHIR resources, including conditional deletes or custom delete operations.
Retrieve the authenticated user's FHIR profile with
get_user.Connect via stdio, SSE, or streamable HTTP and support SMART-on-FHIR/OAuth2 authentication.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@FHIR MCP Server search for patients with diabetes born after 1980"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Model Context Protocol (MCP) Server for Fast Healthcare Interoperability Resources (FHIR) APIs
Table of Contents
Related MCP server: FHIR MCP Server
Overview
The FHIR MCP Server is a Model Context Protocol (MCP) server that provides seamless integration with FHIR APIs. Designed for developers, integrators, and healthcare innovators, this server acts as a bridge between modern AI/LLM tools and healthcare data, making it easy to search, retrieve, and analyze clinical information.
Demo
Demo with HAPI FHIR server
This video showcases the MCP server's functionality when connected to a public HAPI FHIR server. This example showcases direct interaction with an open FHIR server that does not require an authorization flow.
https://github.com/user-attachments/assets/cc6ac87e-8329-4da4-a090-2d76564a3abf
Demo with EPIC Sandbox
This video showcases the MCP server's capabilities within the Epic EHR ecosystem. It demonstrates the complete OAuth 2.0 Authorization Code Grant flow.
https://github.com/user-attachments/assets/96b433f1-3e53-4564-8466-65ab48d521de
Core Features
MCP-compatible transport: Serves FHIR via stdio, SSE, or streamable HTTP
SMART-on-FHIR based authentication support: Securely authenticate with FHIR servers and clients
Response Filtering using FHIRPath: Filter resources and bundles returned by
readandsearchoperations using custom FHIRPath expressions to retrieve only the fields needed for the task, reducing payload sizes.Tool integration: Integratable with any MCP client such as VS Code, Claude Desktop, and MCP Inspector
Prerequisites
Python 3.8+
uv (for dependency management)
An accessible FHIR API server.
Installation
You can use the FHIR MCP Server by installing our Python package, or by cloning this repository.
Installing using PyPI Package
Configure Environment Variables:
To run the server, you must set
FHIR_SERVER_BASE_URL.To enable authorization: Set
FHIR_SERVER_BASE_URL,FHIR_SERVER_CLIENT_ID,FHIR_SERVER_CLIENT_SECRET, andFHIR_SERVER_SCOPES. Authorization is enabled by default.To disable authorization: Set
FHIR_SERVER_DISABLE_AUTHORIZATIONtoTrue.
By default, the MCP server runs on http://localhost:8000, and you can customize the host and port using
FHIR_MCP_HOSTandFHIR_MCP_PORT.You can set these by exporting them as environment variables like below or by creating a
.envfile (referencing.env.example).export FHIR_SERVER_BASE_URL="" export FHIR_SERVER_CLIENT_ID="" export FHIR_SERVER_CLIENT_SECRET="" export FHIR_SERVER_SCOPES="" export FHIR_MCP_HOST="localhost" export FHIR_MCP_PORT="8000"Install the PyPI package and run the server
uvx fhir-mcp-server
Installing from Source
Clone the repository:
git clone <repository_url> cd <repository_directory>Create a virtual environment and install dependencies:
uv venv source .venv/bin/activate uv pip sync requirements.txtOr with pip:
python -m venv .venv source .venv/bin/activate pip install -r requirements.txtConfigure Environment Variables: Copy the example file and customize if needed:
cp .env.example .envRun the server:
uv run fhir-mcp-server
Installing using Docker
Running the MCP Server with Docker
You can run the MCP server using Docker for a consistent, isolated environment.
Note on Authorization: When running the MCP server locally via Docker or Docker Compose, authorization should be disabled by setting the environment variable,
FHIR_SERVER_DISABLE_AUTHORIZATION=True. This would be fixed in the future releases.
Build the Docker Image or pull the docker image from the container registry:
Build from source:
docker build -t fhir-mcp-server .Pull from GitHub Container Registry:
docker pull ghcr.io/wso2/fhir-mcp-server:latestlatestis built from themainbranch. To use a release, pull its version tag instead, for exampleghcr.io/wso2/fhir-mcp-server:0.11.0.
Configure Environment Variables
Copy the example environment file and edit as needed:
cp .env.example .env # Edit .env to set your FHIR server, client credentials, etc.Alternatively, you can pass environment variables directly with
-eflags or use Docker secrets for sensitive values. See the Configuration section for details on available environment variables.Run the Container
docker run --env-file .env -p 8000:8000 ghcr.io/wso2/fhir-mcp-server:latestThis will start the server and expose it on port 8000. Adjust the port mapping as needed.
Using Docker Compose with WSO2 FHIR Server
For a quick setup that includes both the FHIR MCP server and the WSO2 FHIR Server (with PostgreSQL), use the provided docker-compose.yml. This sets up an instant development environment for testing FHIR operations.
Prerequisites:
Docker and Docker Compose installed.
Set the Database Credentials:
Copy the example environment file and set
DB_PASSWORDin.env. If you already have a.env, add theDB_USER,DB_PASSWORDandDB_NAMElines from.env.exampleto it instead.cp .env.example .envDocker Compose reads
.envautomatically.DB_USERandDB_NAMEdefault topostgresif not set..envis excluded from Git; use a secrets manager for production deployments.Run the Stack:
docker compose up -dThis command will:
Start a PostgreSQL database container.
Launch the FHIR Server (connected to PostgreSQL) listening on http://localhost:8080/fhir/r4.
Build and run the FHIR MCP server container listening on http://localhost:8000, with
FHIR_SERVER_BASE_URLset to http://wso2-fhir-server:8080/fhir/r4.
Access the Services:
FHIR MCP Server: http://localhost:8000
FHIR Server: http://localhost:8080/fhir/r4
To stop run
docker compose down.
docker compose downremoves the database data; usedocker compose stopto keep it between runs.Configure Additional Environment Variables:
If you need to customize OAuth or other settings, adjust the env variables in the
docker-compose.yml. The compose file sets basic configuration; refer to the Configuration section for full options.
Configuring any FHIR Server
To use a different FHIR server, run the FHIR MCP server container with FHIR_SERVER_BASE_URL pointing to that server. The example below uses the HAPI FHIR server. Stop the default stack first if it's already running (docker compose down), as both use ports 8000 and 8080.
Create a network and start the HAPI FHIR server:
docker network create fhir-network docker run -d --name hapi-fhir-server --network fhir-network -p 127.0.0.1:8080:8080 docker.io/hapiproject/hapi:v8.4.0-2HAPI FHIR listens on http://localhost:8080/fhir. This uses its built-in database, so data is lost when the container is removed.
Build and run the FHIR MCP server container:
docker build -t fhir-mcp-server . docker run -d --name fhir-mcp-server-hapi --network fhir-network -p 127.0.0.1:8000:8000 -e FHIR_SERVER_BASE_URL=http://hapi-fhir-server:8080/fhir -e FHIR_MCP_HOST=0.0.0.0 -e FHIR_SERVER_DISABLE_AUTHORIZATION=True fhir-mcp-serverThe FHIR MCP server listens on http://localhost:8000.
Stop and clean up:
docker rm -f fhir-mcp-server-hapi hapi-fhir-server docker network rm fhir-network
For any other FHIR server, set FHIR_SERVER_BASE_URL to its base URL. If the FHIR server runs on your host rather than in Docker, use http://host.docker.internal:<port>/... instead of localhost.
On Linux, also add --add-host=host.docker.internal:host-gateway to the docker run command, and make sure the FHIR server listens on an address reachable from containers (for example 0.0.0.0, not only 127.0.0.1).
Integration with MCP Clients
The FHIR MCP Server is designed for seamless integration with various MCP clients.
VS Code
Add the following JSON block to your MCP configuration file in VS Code (> V1.104). You can do this by pressing Ctrl + Shift + P and typing MCP: Open User Configuration.
"servers": {
"fhir": {
"type": "http",
"url": "http://localhost:8000/mcp",
}
}"servers": {
"fhir": {
"command": "uv",
"args": [
"--directory",
"/path/to/fhir-mcp-server",
"run",
"fhir-mcp-server",
"--transport",
"stdio"
],
"env": {
"FHIR_SERVER_ACCESS_TOKEN": "Your FHIR Access Token"
}
}
}"servers": {
"fhir": {
"type": "sse",
"url": "http://localhost:8000/sse",
}
}Claude Desktop
Add the following JSON block to your Claude Desktop settings to connect to your local MCP server.
Launch the Claude Desktop app, click on the Claude menu in the top bar, and select "Settings…".
In the Settings pane, click “Developer” in the left sidebar. Then click "Edit Config". This will open your configuration file in your file system. If it doesn’t exist yet, Claude will create one automatically at:
macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
Open the claude_desktop_config.json file in any text editor. Replace its contents with the following JSON block to register the MCP server:
{
"mcpServers": {
"fhir": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"http://localhost:8000/mcp"
]
}
}
}{
"mcpServers": {
"fhir": {
"command": "uv",
"args": [
"--directory",
"/path/to/fhir-mcp-server",
"run",
"fhir-mcp-server",
"--transport",
"stdio"
],
"env": {
"FHIR_SERVER_ACCESS_TOKEN": "Your FHIR Access Token"
}
}
}
}{
"mcpServers": {
"fhir": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"http://localhost:8000/sse"
]
}
}
}MCP Inspector
Follow these steps to get the MCP Inspector up and running:
Open a terminal and run the following command:
npx -y @modelcontextprotocol/inspectorIn the MCP Inspector interface:
Transport Type:
Streamable HTTPURL:
http://localhost:8000/mcp
Transport Type:
STDIOCommand:
uvArguments:
--directory /path/to/fhir-mcp-server run fhir-mcp-server --transport stdio
Transport Type:
SSEURL:
http://localhost:8000/sse
Make sure your MCP server is already running and listening on the above endpoint.
Once connected, MCP Inspector will allow you to visualize tool invocations, inspect request/response payloads, and debug your tool implementations easily.
Configuration
CLI Options
You can customize the behavior of the MCP server using the following command-line flags:
--transport
Description: Specifies the transport protocol used by the MCP server to communicate with clients.
Accepted values: stdio, sse, streamable-http
Default: streamable-http
--log-level
Description: Sets the logging verbosity level for the server.
Accepted values: DEBUG, INFO, WARN, ERROR (case-insensitive)
Default: INFO
--help
Description: Displays a help message with available server options and exits.
Usage: Automatically provided by the command-line interface.
Sample Usages:
uv run fhir-mcp-server --transport streamable-http --log-level DEBUG
uv run fhir-mcp-server --helpEnvironment Variables
MCP Server Configurations:
FHIR_MCP_HOST: The hostname or IP address the MCP server should bind to (e.g.,localhostfor local-only access, or0.0.0.0for all interfaces).FHIR_MCP_PORT: The port on which the MCP server will listen for incoming client requests (e.g.,8000).FHIR_MCP_SERVER_URL: If set, this value will be used as the server's base URL instead of generating it from host and port. Useful for custom URL configurations or when behind a proxy.FHIR_MCP_REQUEST_TIMEOUT: Timeout duration in seconds for requests from the MCP server to the FHIR server (default:30).
MCP Server OAuth2 with FHIR server Configuration (MCP Client ↔ MCP Server): These variables configure the MCP client's secure connection to the MCP server, using the OAuth2 authorization code grant flow with a FHIR server.
FHIR_SERVER_CLIENT_ID: The OAuth2 client ID used to authorize MCP clients with the FHIR server.FHIR_SERVER_DISABLE_AUTHORIZATION: If set toTrue, disables authorization checks on the MCP server, allowing connections to publicly accessible FHIR servers.FHIR_SERVER_CLIENT_SECRET: The client secret corresponding to the FHIR client ID. Used during token exchange.FHIR_SERVER_BASE_URL: The base URL of the FHIR server (e.g.,https://hapi.fhir.org/baseR4). This is used to generate tool URIs and to route FHIR requests.FHIR_SERVER_SCOPES: A space-separated list of OAuth2 scopes to request from the FHIR authorization server (e.g.,user/Patient.read user/Observation.read). AddfhirUser openidto enable retrieval of user context for theget_usertool. If these two scopes are not configured, theget_usertool returns an empty result because the ID token lacks the user's FHIR resource reference.FHIR_SERVER_ACCESS_TOKEN: The access token to use for authenticating requests to the FHIR server. If this variable is set, the server will bypass the OAuth2 authorization flow and use this token directly for all requests.
FHIR_SERVER_ACCESS_TOKEN is intended for local stdio mode deployments only, as a convenience to bypass interactive OAuth authentication. Do not use this variable when the MCP server is exposed over a network or the public internet.
Tools
get_capabilities: Retrieves metadata about a specified FHIR resource type, including its supported search parameters and custom operations.type: The FHIR resource type name (e.g., "Patient", "Observation", "Encounter")
search: Executes a standard FHIR search interaction on a given resource type, returning a bundle or list of matching resources.type: The FHIR resource type name (e.g., "MedicationRequest", "Condition", "Procedure").searchParam: A mapping of FHIR search parameter names to their desired values (e.g., {"family":"Simpson","birthdate":"1956-05-12"}).response_filter_fhirpaths: (Optional) An array of FHIRPath expressions (e.g.,["Patient.name", "Patient.birthDate", "Bundle.link.where(relation='next').url"]) to apply to the resources in the response bundle.
read: Performs a FHIR "read" interaction to retrieve a single resource instance by its type and resource ID, optionally refining the response with search parameters or custom operations.type: The FHIR resource type name (e.g., "DiagnosticReport", "AllergyIntolerance", "Immunization").id: The logical ID of a specific FHIR resource instance.searchParam: A mapping of FHIR search parameter names to their desired values (e.g., {"device-name":"glucometer"}).operation: The name of a custom FHIR operation or extended query defined for the resource (e.g., "$everything").response_filter_fhirpaths: (Optional) An array of FHIRPath expressions (e.g.,["Patient.name", "Observation.valueQuantity"]) to filter the returned single resource (or entries when using custom operations like$everything).
create: Executes a FHIR "create" interaction to persist a new resource of the specified type.type: The FHIR resource type name (e.g., "Device", "CarePlan", "Goal").payload: A JSON object representing the full FHIR resource body to be created.searchParam: A mapping of FHIR search parameter names to their desired values (e.g., {"address-city":"Boston"}).operation: The name of a custom FHIR operation or extended query defined for the resource (e.g., "$evaluate").
update: Performs a FHIR "update" interaction by replacing an existing resource instance's content with the provided payload.type: The FHIR resource type name (e.g., "Location", "Organization", "Coverage").id: The logical ID of a specific FHIR resource instance.payload: The complete JSON representation of the FHIR resource, containing all required elements and any optional data.searchParam: A mapping of FHIR search parameter names to their desired values (e.g., {"patient":"Patient/54321","relationship":"father"}).operation: The name of a custom FHIR operation or extended query defined for the resource (e.g., "$lastn").
delete: Execute a FHIR "delete" interaction on a specific resource instance.type: The FHIR resource type name (e.g., "ServiceRequest", "Appointment", "HealthcareService").id: The logical ID of a specific FHIR resource instance.searchParam: A mapping of FHIR search parameter names to their desired values (e.g., {"category":"laboratory","issued:"2025-05-01"}).operation: The name of a custom FHIR operation or extended query defined for the resource (e.g., "$expand").
get_user: Retrieves the currently authenticated user's FHIR resource (for example the linkedPatientresource) and returns a concise profile containing available demographic fields such asid,name, andbirthDate.
Development & Testing
Installing Development Dependencies
To run tests and contribute to development, install the test dependencies:
Using pip:
# Install project in development mode with test dependencies
pip install -e '.[test]'
# Or install from requirements file
pip install -r requirements-dev.txtUsing uv:
# Install development dependencies
uv sync --devRunning Tests
The project includes a comprehensive test suite covering all major functionality:
# Simple test runner
python run_tests.py
# Or direct pytest usage
PYTHONPATH=src python -m pytest tests/ -v --cov=src/fhir_mcp_serverUsing pytest:
pytest tests/This will discover and run all tests in the tests/ directory.
Test Features:
100+ tests with comprehensive coverage
Full async/await support using pytest-asyncio
Complete mocking of HTTP requests and external dependencies
Coverage reporting with terminal and HTML output
Fast execution with no real network calls
The test suite includes:
Unit tests: Core functionality testing
Integration tests: Component interaction validation
Edge case coverage: Error handling and validation scenarios
Mocked OAuth flows: Realistic authentication testing
Coverage reports are generated in htmlcov/index.html for detailed analysis.
Available Tools
7 toolscreateA
Creates a new FHIR resource on the server (FHIR create interaction: POST [base]/{type}). Use it to add a record that does not exist yet, such as a new Patient, Observation or Appointment. Do not use it to change an existing resource; use update for that. The server assigns a new id on every call, so repeating a call creates duplicates; use search first if the record may already exist. On success it returns the resource as stored, including the server-assigned id and meta. On failure it returns OperationOutcome issues whose diagnostics explain what to fix, such as a missing required element or an invalid code.
Inputs: type (required), payload (required), operation, searchParam. Returns: result
deleteA
Execute a FHIR delete interaction on a specific resource instance. Use this tool when you need to remove a single resource identified by its logical ID or optionally filtered by search parameters. The optional id parameter must match an existing resource instance when present. If you include searchParam, the server will perform a conditional delete, deleting the resource only if it matches the given criteria. If you supply operation, it will execute the named FHIR operation (e.g., $expunge) on the resource. This tool returns a FHIR OperationOutcome describing success or failure of the deletion.
Inputs: type (required), id, operation, searchParam. Returns: result
get_capabilitiesA
Retrieves metadata about a specified FHIR resource type, including its supported search parameters and custom operations. This tool MUST always be invoked before performing any resource operation (such as search, read, create, update, or delete) to discover the valid searchParams and operations permitted for that resource type. Do not use this tool to fetch actual resources.
Inputs: type (required). Returns: result
get_userA
Retrieves the authenticated user's FHIR profile. Use this tool when you need to access the current user's demographic and contact details.
Inputs: no named parameters. Returns: result
readA
Performs a FHIR read interaction to retrieve a single resource instance by its type and resource ID, optionally refining the response with search parameters or custom operations. Use it when you know the exact resource ID and require that one resource; do not use it for bulk queries. If additional query-level parameters or operations are needed (e.g., _elements or $validate), include them in searchParam or operation. Optionally specify fields to filter the response to only the data your task needs (e.g., Patient.birthDate, Observation.valueQuantity).
Inputs: id (required), type (required), operation, searchParam, +1 more. Returns: result
searchA
Executes a standard FHIR search interaction on a given resource type, returning a bundle or list of matching resources. Use this when you need to query for multiple resources based on one or more search-parameters. Do not use this tool for create, update, or delete operations, and be aware that large result sets may be paginated by the FHIR server. Optionally specify fields to filter the response to only the data your task needs (e.g., Patient.birthDate, Observation.valueQuantity).
Inputs: type (required), searchParam (required), response_filter_fhirpaths. Returns: result
updateA
Replaces the full content of an existing FHIR resource (FHIR update interaction: PUT [base]/{type}/{id}). Use it to correct or complete a record whose logical id you already know. Elements left out of the payload are removed from the stored resource, not kept, so first get the current version with read, change what you need, and send the whole resource back. Do not use it to add new records; use create for that. On success it returns the resource as stored, with an updated meta.versionId and meta.lastUpdated. On failure it returns OperationOutcome issues whose diagnostics explain what to fix.
Inputs: id (required), type (required), payload (required), operation, +1 more. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool maps to a distinct FHIR interaction (capabilities, search, read, create, update, delete) with clear boundaries called out in the descriptions. Minor blur: `read` accepts searchParam/operation refinements and `get_user` overlaps conceptually with reading the current user's Patient/Practitioner resource, so an agent could occasionally hesitate between read/search and get_user/read.
Two conventions coexist: get_-prefixed helpers (`get_capabilities`, `get_user`) alongside bare FHIR interaction names (`search`, `read`, `create`, `update`, `delete`). The split has a semantic rationale (get_* for non-resource metadata), but it is still an inconsistent verb pattern rather than a single predictable scheme.
Seven tools is well-scoped for a generic FHIR client: exactly the CRUD interactions plus search, capability discovery, and current-user lookup. Nothing feels redundant or missing at the count level.
Core lifecycle is fully covered: create/read/update/delete plus search and capability discovery, which is strong for a generic FHIR server. Gaps remain for advanced interactions such as patch, versioned read/history, and batch/transaction bundles, but agents can work around most of these.
Maintenance
Related MCP Connectors
Privacy-preserving synthetic health data generation. FHIR R4/R5 compliant.
Guardrailed FHIR access for AI agents: PHI redaction, audit trail, step-up auth, tenant isolation
Securely access and manage FHIR healthcare data stored in Medplum.
FHIR R4 health records for AI: people connect their own record with consent; free FHIR sandbox.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables LLM-based agents to interact with FHIR healthcare data through natural language prompts, providing full CRUD operations on FHIR resources, document processing, and semantic search capabilities.13102MIT
- AlicenseNot gradedqualityNot gradedmaintenanceEnables seamless integration with FHIR APIs for healthcare applications, allowing users to search, retrieve, create, update, and analyze clinical information through natural language interactions. Supports SMART-on-FHIR authentication and works with various healthcare systems like EPIC and HAPI FHIR servers.Apache 2.0
- AlicenseNot gradedqualityBmaintenanceEnables LLMs to securely interact with FHIR healthcare servers and HL7 terminology services. Provides comprehensive healthcare data operations with built-in PHI protection, audit logging, and SMART on FHIR authentication.MIT
- FlicenseAqualityDmaintenanceProvides read/write access to any FHIR-compliant healthcare API with built-in validation, supporting resource management, search operations, and granular permissions through natural language.51-