FHIR

jodipatton/FHIR

3.1

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.

Tools
5
Resources
0
Prompts
0

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:

  1. Data Ingestion: FHIR resources from various sources (NDJSON, CSV, PDF, TXT) are parsed and normalized into healthcare observations
  2. Storage: Data is stored in both Firebase Firestore (full records) and Pinecone (vector embeddings for semantic search)
  3. 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/mcp endpoint
  • 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: Success
  • 400: 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

  1. Authentication: All requests must include a valid Firebase ID token
  2. Authorization: Users can only access their own data
  3. Data Privacy: No PHI is logged or cached
  4. 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:

  1. Define the tool in src/lib/mcp-server.ts
  2. Add the tool to the healthcareTools array
  3. Implement the tool handler in the HealthcareMCPServer class
  4. Update this documentation

Troubleshooting

Common Issues

  1. Authentication Errors: Ensure Firebase ID token is valid and not expired
  2. Tool Not Found: Check tool name spelling and availability
  3. Permission Denied: Verify user has access to the requested patient data
  4. 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:

  1. Set up proper Firebase security rules
  2. Implement rate limiting
  3. Add monitoring and logging
  4. Consider caching for frequently accessed data
  5. 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.

  1. Go to nodejs.org
  2. Download the LTS (Long Term Support) version for your operating system
  3. Run the installer and follow the setup wizard
  4. 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.

  1. Go to firebase.google.com
  2. Click "Get started" and sign in with your Google account
  3. Click "Create a project" and give it a name (e.g., "healthcare-mcp-demo")
  4. Disable Google Analytics (not needed for this demo)
  5. Once created, click "Authentication" in the left sidebar
  6. Click "Get started", then go to "Sign-in method" tab
  7. Enable "Google" sign-in provider
  8. Click "Firestore Database" in the left sidebar
  9. Click "Create database" and choose "Start in test mode"
  10. Go to "Project settings" (gear icon) → "General" tab
  11. Scroll down to "Your apps" and click the web icon "</>"
  12. 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.

  1. Go to platform.openai.com/login
  2. Sign up for an account or log in if you already have one
  3. Once logged in, click on your profile in the top right
  4. Select "API keys" from the dropdown menu
  5. Click "Create new secret key"
  6. Give it a name (e.g., "Healthcare MCP Demo") and click "Create secret key"
  7. 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.

  1. Go to app.pinecone.io/?sessionType=signup
  2. Sign up for a free account (no credit card required)
  3. Once logged in, you'll see the dashboard
  4. Click "Create Index" to create your first database
  5. Name it "healthcare-observations" (or any name you prefer)
  6. Set dimensions to 1024 (important for compatibility)
  7. Leave metric as "cosine" and click "Create Index"
  8. Go to "API Keys" in the left sidebar
  9. 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

  1. Clone the repository
git clone https://github.com/jodipatton/FHIR.git
cd FHIR/web
  1. Install dependencies
npm install
  1. Configure environment variables
cp .env.example .env.local

Fill in your Firebase, Pinecone, and OpenAI configuration in .env.local.

  1. Start the development server
npm run dev

Data Flow Architecture

The platform follows a three-tier architecture:

  1. Data Ingestion: FHIR resources from various sources (NDJSON, CSV, PDF, TXT) are parsed and normalized into healthcare observations
  2. Storage: Data is stored in Pinecone with vector embeddings for semantic search
  3. Query Processing: MCP client queries are processed using Pinecone vector search and OpenAI LLM for natural language understanding