jodipatton/FHIR
If you are the rightful owner of FHIR and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
MCP Server and Client for Healthcare is a demonstration of using Model Context Protocol (MCP) to improve healthcare data integration and AI application efficiency.
MCP Server and Client for Healthcare
Expanded Overview & Features
Introduction
MCP Server and Client for Healthcare is a demonstration of how to use Model Context Protocol (MCP), an open protocol that standardizes how applications provide context to LLMs, to improve healthcare by achieving a step improvement in prior authorization efficiency and efficacy. Other use cases may follow, but I hoped to provide a practical example.
Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.
This demo includes secure, standardized, and scalable access to healthcare data, empowering a new generation of digital health tools, AI models, and clinical applications. MCP servers are created for each repository sourced from an open source project (https://github.com/smart-on-fhir/sample-bulk-fhir-datasets). Access to the MCP servers requires authorization. In this demonstration, Google Firebase Authorization is used. The MCP client is a React Chatbot powered by a fine-tuned OpenAI 4.1 model. The entire project is available here on Github.
I created this demonstration using ChatGPT, Cursor AI, and an afternoon on a warm summer weekend. I look forward to the feedback and future contributions.
Overview
By leveraging the Model Context Protocol (MCP), the demonstration hopes to provide a sample for seamless integration with diverse healthcare systems. The MCP server serves as a unified gateway, exposing specialized tools and services that facilitate interoperability, efficient data processing, and advanced analytics for healthcare stakeholders. Whether integrating with AI models, third-party applications, or MCP-compatible clients, this platform accelerates the adoption of intelligent healthcare solutions while adhering to industry standards.
Key Features
- FHIR R4 Resource Support: Natively supports 10 essential FHIR R4 resource types, including Patient, Observation, Procedure, and more—enabling standardized healthcare data exchange and processing.
- Multi-Format Data Ingestion: Accepts a wide array of healthcare data formats, such as NDJSON, CSV, PDF, and TXT, making it easy to onboard legacy records and support various EHR export standards.
- Semantic Search Powered by Pinecone: Delivers fast, vector-based semantic search across structured and unstructured clinical data, accelerating insights and clinical decision support.
- AI-Powered Natural Language Queries: Integrates OpenAI's natural language capabilities, allowing users to interact with clinical data using plain-language queries for greater accessibility and productivity.
- Standardized MCP Server Interface: Implements a robust, well-documented MCP server interface for interoperability with external systems, applications, and AI agents.
- Real-Time Conversation History: Maintains real-time logs and history of user interactions, supporting context-aware workflows, auditing, and regulatory compliance.
- Secure Authentication with Firebase: Leverages Firebase authentication to ensure user data security, granular access controls, and seamless integration with enterprise identity systems.
Benefits
- Interoperability: Bridges disparate data silos by supporting industry-standard formats and protocols.
- Scalability: Designed for high-throughput processing and growth as data volumes increase.
- Security & Compliance: Built with healthcare-grade security and privacy best practices, supporting regulatory compliance such as HIPAA.
- AI Readiness: Natively supports AI and analytics workflows, unlocking advanced clinical and operational insights.
This demonstration is ideal for those working on utilization management systems, prior authorization, digital health and researchers seeking to modernize healthcare data infrastructure, deploy intelligent applications, and accelerate innovation in efficient workflows.
Supported FHIR Resources
The platform supports the following FHIR R4 resource types:
- Patient - Demographics and patient information
- Observation - Lab results, vital signs, and clinical observations
- Procedure - Medical procedures and interventions
- MedicationRequest - Medication prescriptions and requests
- Immunization - Vaccination records
- Encounter - Healthcare visits and encounters
- DocumentReference - Clinical documents and reports
- Device - Medical devices and equipment
- Condition - Diagnoses and health conditions
- AllergyIntolerance - Allergies and adverse reactions
All FHIR resources are processed and stored as healthcare observations with semantic search capabilities via Pinecone vector embeddings.
Data Flow Architecture
The platform follows a three-tier architecture:
- Data Ingestion: FHIR resources from various sources (NDJSON, CSV, PDF, TXT) are parsed and normalized into healthcare observations
- Storage: Data is stored in both Firebase Firestore (full records) and Pinecone (vector embeddings for semantic search)
- Query Processing: MCP client queries are processed using:
- Pinecone vector search for semantic similarity
- OpenAI LLM for natural language understanding and response generation
- Firestore fallback for complete record retrieval
MCP Client Integration
The system serves as both:
- MCP Server: Exposes healthcare tools via the
/api/mcpendpoint - MCP Client: Internal chat interface that uses Pinecone + OpenAI for conversational queries
MCP Server Endpoint
Base URL: https://your-domain.com/api/mcp
Authentication
All MCP tool calls require authentication via Firebase ID tokens:
Authorization: Bearer <firebase_id_token>
Available Tools
(For full tool documentation, see the file in this repository.)
- get_patient_observations
- search_observations
- analyze_patient_data
- get_lab_results
- get_vital_signs
- get_medications
- get_procedures
- get_conditions
- get_allergies
- get_immunizations
- get_encounters
- get_documents
- get_devices
- get_patient_summary
Using with OpenAI Responses API
Basic Integration
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const response = await openai.responses.create({
model: "gpt-4.1",
tools: [{
type: "mcp",
server_label: "healthcare",
server_url: "https://your-domain.com/api/mcp",
require_approval: "never"
}],
input: "What are my recent lab results showing glucose levels?"
});
console.log(response.output_text);
Advanced Usage with Tool Filtering
const response = await openai.responses.create({
model: "gpt-4.1",
tools: [{
type: "mcp",
server_label: "healthcare",
server_url: "https://your-domain.com/api/mcp",
require_approval: "never",
allowed_tools: ["get_lab_results", "analyze_patient_data"]
}],
input: "Analyze my glucose trends over the past 3 months"
});
Error Handling
The MCP server returns standard HTTP status codes:
200: Success400: Bad Request (invalid parameters)401: Unauthorized (missing or invalid token)404: Not Found (unknown tool)500: Internal Server Error
Error responses include details:
{
"error": "Tool name is required",
"details": ["Missing required parameter: name"]
}
Data Format
All healthcare observations follow this schema:
interface HealthcareObservation {
id?: string;
patient_id: string;
source_file: string;
timestamp: string; // ISO 8601 format
data_type: string; // lab_result, vital_sign, medication, procedure, condition, allergy_intolerance, immunization, encounter, document_reference, device, patient
value: string | number;
units?: string;
notes?: string;
provenance: string; // data source description
created_at?: string;
updated_at?: string;
}
Security Considerations
- Authentication: All requests must include a valid Firebase ID token
- Authorization: Users can only access their own data
- Data Privacy: No PHI is logged or cached
- Rate Limiting: Consider implementing rate limiting for production use
Testing the MCP Server
List Available Tools
curl -X GET https://your-domain.com/api/mcp
Call a Tool
curl -X POST https://your-domain.com/api/mcp \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_FIREBASE_TOKEN" \
-d '{
"method": "tools/call",
"params": {
"name": "get_patient_observations",
"arguments": {"patient_id": "your_patient_id"}
}
}'
Integration Examples
Python Client
import requests
import json
def call_mcp_tool(token, tool_name, arguments):
url = "https://your-domain.com/api/mcp"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
data = {
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments
}
}
response = requests.post(url, headers=headers, json=data)
return response.json()
# Example usage
result = call_mcp_tool(
token="your_firebase_token",
tool_name="get_lab_results",
arguments={"patient_id": "patient_123", "test_type": "glucose"}
)
Node.js Client
async function callMCPTool(token, toolName, arguments) {
const response = await fetch('https://your-domain.com/api/mcp', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
method: 'tools/call',
params: {
name: toolName,
arguments
}
})
});
return response.json();
}
// Example usage
const result = await callMCPTool(
'your_firebase_token',
'analyze_patient_data',
{ patient_id: 'patient_123', analysis_type: 'trends' }
);
Extending the MCP Server
To add new tools:
- Define the tool in
src/lib/mcp-server.ts - Add the tool to the
healthcareToolsarray - Implement the tool handler in the
HealthcareMCPServerclass - Update this documentation
Troubleshooting
Common Issues
- Authentication Errors: Ensure Firebase ID token is valid and not expired
- Tool Not Found: Check tool name spelling and availability
- Permission Denied: Verify user has access to the requested patient data
- Timeout: Large queries may timeout; consider pagination
Debug Mode
Enable debug logging by setting NODE_ENV=development to see detailed logs.
Production Deployment
For production use:
- Set up proper Firebase security rules
- Implement rate limiting
- Add monitoring and logging
- Consider caching for frequently accessed data
- Set up proper error tracking
This MCP integration enables seamless access to healthcare data through standardized tools, making it easy to build AI-powered healthcare applications.
Getting Started
Prerequisites Setup
Good news! All the required services offer free tiers that are perfect for getting started with this project.
1. Node.js and npm
What it does: Node.js is the JavaScript runtime that powers our backend, and npm is the package manager that installs all the code libraries we need.
- Go to nodejs.org
- Download the LTS (Long Term Support) version for your operating system
- Run the installer and follow the setup wizard
- Open your terminal/command prompt and verify installation:
node --version
npm --version
2. Firebase Setup
What it does: Firebase provides user authentication (login/logout) and Firestore database for storing chat history and user data securely.
- Go to firebase.google.com
- Click "Get started" and sign in with your Google account
- Click "Create a project" and give it a name (e.g., "healthcare-mcp-demo")
- Disable Google Analytics (not needed for this demo)
- Once created, click "Authentication" in the left sidebar
- Click "Get started", then go to "Sign-in method" tab
- Enable "Google" sign-in provider
- Click "Firestore Database" in the left sidebar
- Click "Create database" and choose "Start in test mode"
- Go to "Project settings" (gear icon) → "General" tab
- Scroll down to "Your apps" and click the web icon "</>"
- Register your app with a nickname and copy the config object - you'll need this later!
3. OpenAI API Setup
What it does: OpenAI provides the AI language model that powers our intelligent healthcare queries and responses.
- Go to platform.openai.com/login
- Sign up for an account or log in if you already have one
- Once logged in, click on your profile in the top right
- Select "API keys" from the dropdown menu
- Click "Create new secret key"
- Give it a name (e.g., "Healthcare MCP Demo") and click "Create secret key"
- Important: Copy and save this key immediately - you won't be able to see it again!
Free Tier: OpenAI gives new users $5 in free credits, which is plenty for testing this demo.
4. Pinecone Setup
What it does: Pinecone is a vector database that enables fast semantic search through healthcare data using AI embeddings.
- Go to app.pinecone.io/?sessionType=signup
- Sign up for a free account (no credit card required)
- Once logged in, you'll see the dashboard
- Click "Create Index" to create your first database
- Name it "healthcare-observations" (or any name you prefer)
- Set dimensions to 1024 (important for compatibility)
- Leave metric as "cosine" and click "Create Index"
- Go to "API Keys" in the left sidebar
- Copy your API key and environment name - you'll need both!
Free Tier: Pinecone's free tier includes 1 index with 100,000 vectors - perfect for this demo!
Installation
- Clone the repository
git clone https://github.com/jodipatton/FHIR.git
cd FHIR/web
- Install dependencies
npm install
- Configure environment variables
cp .env.example .env.local
Fill in your Firebase, Pinecone, and OpenAI configuration in .env.local.
- Start the development server
npm run dev
Data Flow Architecture
The platform follows a three-tier architecture:
- Data Ingestion: FHIR resources from various sources (NDJSON, CSV, PDF, TXT) are parsed and normalized into healthcare observations
- Storage: Data is stored in Pinecone with vector embeddings for semantic search
- Query Processing: MCP client queries are processed using Pinecone vector search and OpenAI LLM for natural language understanding