Skip to main content
Glama
CaseMark

FHIR Progressive Discovery MCP Server

by CaseMark
README.md
# FHIR Progressive Discovery MCP Server

A sophisticated FastMCP-based server that provides **progressive discovery** of FHIR (Fast Healthcare Interoperability Resources) operations, inspired by [Klavis AI](https://github.com/Klavis-AI/klavis) architecture patterns.

## 🎯 Key Features

- **Progressive Discovery**: Resources are discovered based on user intent, not loaded all at once
- **11 Resource Groups**: Clinical, Administrative, Workflow, Financial, and more
- **Native PDF Conversion**: Convert medical PDFs directly to FHIR DocumentReference resources
- **Format Conversion**: Transform between JSON, XML, and YAML formats
- **Built on FastMCP**: Modern, type-safe Python MCP server framework
- **Pydantic v2 Validation**: Robust FHIR resource validation using fhir.resources

## 🏗️ Architecture

### Progressive Discovery Model

Instead of exposing 100+ FHIR resources at once, this server organizes resources into **logical groups** and progressively discovers them based on context:

```
User Intent → Discover Groups → Explore Group → Use Specific Resources
```

**Discovery Flow:**
1. `discover_resource_groups(intent="patient care")` → Returns relevant groups
2. `explore_resource_group(group_id="clinical")` → Shows resources in that group
3. `get_resource_schema(resource_type="Patient")` → Get specific resource structure
4. `create_resource(...)` → Work with the resource

### Resource Groups

| Group | Resources | Priority |
|-------|-----------|----------|
| **Clinical** | Condition, Observation, Procedure, Medication, Immunization, AllergyIntolerance, DiagnosticReport | 1 |
| **Administrative** | Patient, Practitioner, Organization, Location, HealthcareService | 1 |
| **Workflow** | Encounter, Appointment, EpisodeOfCare, Task, ServiceRequest, CarePlan | 2 |
| **Financial** | Coverage, Claim, Invoice, PaymentNotice, Account, ExplanationOfBenefit | 3 |
| **Diagnostics** | ImagingStudy, Media, BodyStructure, MolecularSequence | 2 |
| **Medications** | Medication, MedicationAdministration, MedicationDispense, MedicationRequest | 2 |
| **Documents** | DocumentReference, DocumentManifest, Composition | 2 |
| **Clinical Reasoning** | PlanDefinition, ActivityDefinition, Questionnaire, RiskAssessment | 3 |
| **Research** | ResearchStudy, ResearchSubject, Evidence, Citation | 4 |
| **Terminology** | CodeSystem, ValueSet, ConceptMap, NamingSystem | 4 |
| **Security** | AuditEvent, Provenance, Consent, Permission | 3 |

## 🚀 Installation

```bash
# Clone or download the repository
cd "FHIR MCP"

# Install dependencies
pip install -r requirements.txt

# Or use the project config
pip install -e .
```

## 📖 Usage

### Starting the Server

```bash
python fhir_mcp_server.py
```

### MCP Tools Available

#### 1. Discovery Tools

**`discover_resource_groups(intent: str)`**
- Entry point for progressive discovery
- Returns resource groups ranked by relevance to your intent

```python
# Example intents:
"patient care"      # → Clinical, Administrative groups
"billing"           # → Financial, Administrative groups
"scheduling"        # → Workflow, Administrative groups
"research study"    # → Research, Clinical groups
```

**`explore_resource_group(group_id: str)`**
- Deep dive into a specific group
- Shows all resources and available operations

**`list_all_resource_groups()`**
- Complete overview of all groups

#### 2. Resource Operations

**`get_resource_schema(resource_type: str)`**
- Get Pydantic schema for any FHIR resource
- Shows required fields, types, and structure

**`create_resource(resource_type: str, resource_data: dict)`**
- Create and validate FHIR resources
- Returns validated FHIR JSON

**`validate_resource(resource_json: str)`**
- Validate existing FHIR JSON against schema

**`convert_between_formats(resource_data: str, input_format: str, output_format: str)`**
- Convert between JSON, XML, YAML formats
- Formats: `"json"`, `"xml"`, `"yaml"`

**`search_resources(resource_type: str, search_params: dict)`**
- Validate search parameters against schema
- Prepares queries for FHIR server execution

#### 3. PDF Conversion Tools

**`convert_pdf_to_fhir(pdf_path: str, document_type: str, patient_reference: str)`**
- Convert medical PDFs to FHIR DocumentReference
- Extract text and metadata
- Basic clinical data extraction

**Document Types:**
- `clinical_note` - Outpatient notes
- `lab_report` - Laboratory results
- `discharge_summary` - Hospital discharge docs
- `prescription` - Medication prescriptions

**`batch_convert_pdfs_to_fhir(pdf_directory: str, document_type: str, patient_reference: str)`**
- Batch process entire directories of PDFs

#### 4. Utility Tools

**`get_fhir_version_info()`**
- Check supported FHIR versions and features

## 💡 Example Workflows

### Workflow 1: Create a Patient Resource

```python
# 1. Discover what's available for patient management
discover_resource_groups(intent="patient management")
# → Returns: Administrative, Clinical groups

# 2. Explore the administrative group
explore_resource_group(group_id="administrative")
# → Shows: Patient, Practitioner, Organization...

# 3. Get Patient schema
get_resource_schema(resource_type="Patient")
# → Returns: Full Patient schema with required fields

# 4. Create a patient
create_resource(
    resource_type="Patient",
    resource_data={
        "resourceType": "Patient",
        "active": True,
        "name": [{
            "use": "official",
            "family": "Doe",
            "given": ["John"]
        }],
        "gender": "male",
        "birthDate": "1990-01-01"
    }
)
# → Returns: Validated Patient FHIR resource
```

### Workflow 2: Convert Lab Report PDF to FHIR

```python
# Convert a single lab report
convert_pdf_to_fhir(
    pdf_path="/path/to/lab_report.pdf",
    document_type="lab_report",
    patient_reference="Patient/12345"
)
# → Returns: DocumentReference resource with extracted text

# Batch convert all PDFs in a folder
batch_convert_pdfs_to_fhir(
    pdf_directory="/path/to/medical_records/",
    document_type="clinical_note",
    patient_reference="Patient/12345"
)
# → Processes all PDFs and returns results
```

### Workflow 3: Create and Convert Observation

```python
# 1. Discover clinical resources
discover_resource_groups(intent="patient vitals")
# → Returns: Clinical group

# 2. Create an Observation
create_resource(
    resource_type="Observation",
    resource_data={
        "resourceType": "Observation",
        "status": "final",
        "code": {
            "coding": [{
                "system": "http://loinc.org",
                "code": "85354-9",
                "display": "Blood pressure"
            }]
        },
        "subject": {"reference": "Patient/123"},
        "valueQuantity": {
            "value": 120,
            "unit": "mmHg"
        }
    }
)
# → Returns: Validated Observation in JSON

# 3. Convert to XML
convert_between_formats(
    resource_data='{"resourceType": "Observation", ...}',
    input_format="json",
    output_format="xml"
)
# → Returns: XML representation
```

## 🧠 Progressive Discovery Benefits

1. **Reduced Context Window Usage**: Load only what you need, when you need it
2. **Intent-Based Discovery**: Find resources based on your use case, not alphabetically
3. **Scalable**: Works with 100+ FHIR resources without overwhelming the agent
4. **Grouped Operations**: Related resources are discovered together
5. **Lazy Loading**: Resources are only instantiated when accessed

## 🔧 Technical Details

### FHIR Versions Supported
- **R5** (default) - FHIR version 5.0.0
- **R4B** - FHIR version 4.3.0
- **STU3** - FHIR version 3.0.2

### Dependencies
- **FastMCP**: Modern MCP server framework
- **fhir.resources**: Official Python FHIR resources with Pydantic v2
- **PyPDF2**: PDF text extraction
- **Pydantic**: Data validation and serialization

### Resource Validation
All resources are validated using:
- Pydantic v2 models from fhir.resources
- FHIR specification compliance
- Required field checking
- Type validation
- Cardinality constraints

## 📚 FHIR Resources

This server supports **all standard FHIR R5 resources** including:

**Clinical**: AllergyIntolerance, CarePlan, CareTeam, ClinicalImpression, Condition, DetectedIssue, DiagnosticReport, FamilyMemberHistory, Goal, Immunization, MedicationAdministration, MedicationDispense, MedicationRequest, MedicationStatement, Observation, Procedure, RiskAssessment, Specimen

**Administrative**: Patient, Practitioner, PractitionerRole, Organization, Location, HealthcareService, Endpoint, Person, Group, RelatedPerson

**Workflow**: Appointment, AppointmentResponse, Schedule, Slot, Encounter, EpisodeOfCare, Flag, ServiceRequest, Task, Communication, CommunicationRequest

**Financial**: Account, ChargeItem, Claim, ClaimResponse, Coverage, CoverageEligibilityRequest, CoverageEligibilityResponse, EnrollmentRequest, ExplanationOfBenefit, Invoice, PaymentNotice, PaymentReconciliation

**And many more...**

## 🎨 Design Philosophy

This server follows the **Klavis progressive discovery pattern**:
- **Intent-driven**: Start with user intent, not resource lists
- **Layered discovery**: Groups → Resources → Operations
- **Context-aware**: Relevance scoring based on use case
- **Scalable architecture**: Handles large resource sets efficiently

## 🤝 Contributing

Contributions welcome! Areas for enhancement:
- Advanced NLP for PDF extraction
- FHIR server connectivity (HAPI, Azure FHIR)
- HL7 v2 message conversion
- CDA document parsing
- SMART on FHIR integration

## 📄 License

MIT License

## 🔗 References

- [fhir.resources](https://github.com/nazrulworld/fhir.resources) - Python FHIR resources library
- [Klavis AI](https://github.com/Klavis-AI/klavis) - Progressive discovery inspiration
- [FastMCP](https://github.com/jlowin/fastmcp) - MCP server framework
- [FHIR Specification](https://hl7.org/fhir/) - Official FHIR documentation

---

**Built with surgical precision for the gods of programming** ⚡️