dicom-mcp
Health Uyari
- License — License: MIT
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 5 GitHub stars
Code Gecti
- Code scan — Scanned 12 files during light audit, no dangerous patterns found
Permissions Gecti
- Permissions — No dangerous permissions requested
Bu listing icin henuz AI raporu yok.
Devlopment Environment for MCP integration with DICOM (Orthanc), FHIR, RIS
DICOM MCP Server - Medical Imaging AI Integration 🏥
Test the server locally with the official MCP Inspector. No account is required. Cursor and other MCP clients can also attach to it through ~/.cursor/mcp.json. See https://cursor.com/docs/context/mcp#what-is-mcp.
Enables AI assistants to query, read, and move data on PACS using the standard Model Context Protocol (MCP), with Orthanc as the reference implementation. You can use your own APIKEY (e.g. for ChatGPT) and run it locally for development using ChatGPT as the LLM. Also integrated with FHIR and a mini-RIS DB.
✨ Core Capabilities
dicom-mcp provides tools to:
- 🔍 Query DICOM: Search for patients, studies, series, and instances using various criteria
- 📄 Read DICOM Reports (PDF): Retrieve DICOM instances containing encapsulated PDFs (e.g., clinical reports) and extract the text content
- 📄 Create Radiology Reports: Generate radiology reports in PDF format and attach to PACS
- ➡️ Send DICOM Images: Send series or studies to other DICOM destinations, e.g. AI endpoints for image segmentation, classification, etc.
- ⚙️ FHIR Integration: Query and manage FHIR resources (Patient, ImagingStudy, ServiceRequest, etc.)
- ⚙️ Mini-RIS: Manage radiology orders, worklists, and reporting workflows
- ⚙️ MWL/MPPS: Modality Worklist and Modality Performed Procedure Step services
- ⚙️ Utilities: Manage connections, switch servers, and understand query options
🚀 Quick Start
📥 Installation
Install using pip by cloning the repository:
# Clone and set up development environment. Python 3.12 or newer.
gh repo clone sscotti/dicom-mcp
cd dicom-mcp
cp .env.example .env
python3 -m venv venv
source venv/bin/activate
pip install -e ".[dev]"
⚙️ Configuration
dicom-mcp requires a YAML configuration file (configuration.yaml or similar) defining DICOM nodes and calling AE titles. Adapt the configuration or keep as is for compatibility with the sample Orthanc server.
# DICOM nodes configuration
nodes:
main:
host: "localhost"
port: 4242
ae_title: "ORTHANC"
description: "Local Orthanc DICOM server (Primary)"
secondary:
host: "localhost"
port: 4243
ae_title: "ORTHANC2"
description: "Local Orthanc DICOM server (Secondary)"
current_node: "main"
calling_aet: "MCPSCU"
# FHIR server configuration (optional)
# You can configure multiple FHIR servers and switch between them
fhir_servers:
firely:
base_url: "https://server.fire.ly"
description: "Firely FHIR Test Server (public, no API key needed)"
siim:
base_url: "https://hackathon.siim.org/fhir"
api_key: "${SIIM_API_KEY}" # Set in .env file
description: "SIIM Hackathon FHIR server"
# Uncomment to use a local HAPI FHIR server
hapi_local:
base_url: "http://localhost:8080/fhir"
description: "Local HAPI FHIR server"
current_fhir: "hapi_local" # Active FHIR server: firely, siim, or hapi_local, make sure to start the local hapi fhir server before starting the MCP server
# The server will expose all DICOM tools and FHIR tools via standard MCP protocol
# Mini-RIS MySQL database configuration (optional)
mini_ris:
host: "localhost"
port: 3306
user: "orthanc_ris_app"
password: "${MINI_RIS_DB_PASSWORD}"
database: "orthanc_ris"
pool_size: 5
[!WARNING]
DICOM-MCP is not meant for clinical use, and should not be connected with live hospital databases or databases with patient-sensitive data. Doing so could lead to both loss of patient data, and leakage of patient data onto the internet. DICOM-MCP can be used with locally hosted open-weight LLMs for complete data privacy.[!NOTE]
Use the official MCP Inspector to call tools against a local server.mcp-config.example.jsonis a template for Cursor and other MCP clients. Replace the placeholder paths before use.
Docker Container Setup (Orthancs, FHIR, PostGres and MySQL)
docker compose up -d
pytest
Orthanc uses the TLS certificates in this repo, so the web UIs are https://localhost:8042 and https://localhost:8043. The whole-slide imaging plugin is disabled in both Orthanc configs because it fails its startup check on orthancteam/orthanc:25.10.5-full.
HAPI FHIR is at http://localhost:8080/fhir. Copy .env.example to .env before pytest so the tests use HTTPS and the DICOM TLS mode in that file.
See FHIR Servers Guide for detailed configuration options including Firely test server and SIIM integration.
🔌 Using the MCP Inspector
The official MCP Inspector (@modelcontextprotocol/inspector) lists and calls this server's tools in the browser. It does not require an account. From the project root, with the virtualenv already created:
PYTHONPATH=src npx @modelcontextprotocol/inspector@latest \
venv/bin/python -m dicom_mcp configuration.yaml --transport stdio
The command prints a localhost URL and opens it. Use the Tools, Prompts, and Resources tabs. Saved references are also available through the list_saved_resources and get_saved_resource tools.
To list tools from the shell:
PYTHONPATH=src npx @modelcontextprotocol/inspector@latest --cli \
venv/bin/python -m dicom_mcp configuration.yaml --transport stdio \
--method tools/list
Using Your OpenAI API Key in Cursor IDE:
Note: Use the MCP Inspector to exercise tools. Use Cursor when you want those tools available while editing this repo.
If you want to use Cursor IDE with ChatGPT for coding tasks:
Get your API key from
.env(if stored there):grep OPENAI_API_KEY .envConfigure in Cursor:
- Open Cursor Settings (Cmd+Shift+J / Ctrl+Shift+J)
- Navigate to Models section
- Paste your OpenAI API key and verify
- Select your preferred GPT model (GPT-4, GPT-4 Turbo, etc.)
Note: Cursor requires the API key to be entered in its settings UI - it doesn't automatically read from
.envfiles. Copy the value from your.envfile and paste it into Cursor's settings.
This gives you ChatGPT-powered AI in Cursor with persistent system prompts and full codebase integration. See CURSOR_SETUP.md for complete setup instructions.
System Prompt:
For better LLM interactions, you can configure a system prompt:
- In Cursor IDE: Set the system prompt in Cursor's settings (persists between sessions). See CURSOR_SETUP.md.
- Via Tool: Call
get_system_promptand copy the returned text into the client you are using.
The Inspector is for calling tools. Cursor keeps the system prompt between sessions.
Available DICOM Tools:
verify_connection- Test DICOM connectivitylist_dicom_nodes- Show configured serversquery_patients- Search for patientsquery_studies- Find studies. On Orthanc, each study includes its seriesextract_pdf_text_from_dicom- Extract text from DICOM PDFsmove_study- Transfer a study to another DICOM nodeswitch_dicom_node- Change active serverget_attribute_presets- Show query detail levels
Series and instance queries, and a series move, are methods on DicomClient (query_series, query_instance, move_series). Pytest calls those methods directly. They are not separate MCP tools.
Available FHIR Tools (when FHIR is configured):
verify_fhir_connection- Test FHIR server connectivitylist_fhir_servers- List configured FHIR serversswitch_fhir_server- Switch to a different FHIR server without restartingfhir_search_resource- List or search resources. A blank call returns a short page of Patient, ImagingStudy, ServiceRequest, and DiagnosticReport. Setresource_typefor one type, including Observation.queryis optional, for examplename=Smith. Each match is an id and a short summary; usefhir_read_resourcefor the full resourcefhir_get_capabilities- Summarize what the server supports. The full statement is omitted because it stalls the browserfhir_read_resource- Read any FHIR resource by type and IDfhir_create_resource- Create new FHIR resourcesfhir_update_resource- Update existing FHIR resourcesfhir_delete_resource- Delete a FHIR resource by type and ID
See FHIR_SERVERS.md for configuration details.
Mini-RIS Tools (when MySQL is configured):
list_mini_ris_patients- Browse patient demographics stored in the mini-RIS schema (filter by MRN or name)list_mini_ris_orders- Browse orders, optionally by MRN, status, or accession numbercreate_mwl_from_order- Create a DICOM Modality Worklist entry from an existing mini-RIS ordercreate_synthetic_cr_study- Generate synthetic CR DICOM images and send to PACS (virtual modality)
Radiology Reporting Tools (when MySQL is configured):
get_study_for_report- Retrieve complete study information for radiology reportinglist_radiologists- List available radiologists with credentialscreate_radiology_report- Create structured radiology report with findings and impressiongenerate_report_pdf- Generate professional PDF from report (base64 encoded)attach_report_to_pacs- Upload report PDF to PACS as DICOM Encapsulated PDF
Mini-RIS Database Schema:
The mini_ris.sql schema provides a complete radiology information system with:
- Core Entities: Patients, Providers, Encounters, Orders, Imaging Studies, Reports
- Reference Tables:
dicom_tags- 50 essential DICOM tag definitions for MWL/MPPS validationprocedures- 14 CR/XR procedure codes with typical views and image countsmodalities- Standard DICOM modality codesbody_parts- Anatomical regions for imaging
- MWL/MPPS Support: Tables for Modality Worklist and Modality Performed Procedure Step tracking
MCP Naming Scheme:
All data in the mini-RIS uses a consistent "MCP-" prefix/suffix naming scheme to clearly mark it as development/synthetic data:
- MRNs:
MCP-MRN-0001 - Accession Numbers:
MCP-ACC-2025-0001 - Patient Names:
Johnson-MCP^Alex(DICOM format) - Physician Names:
MCP-Emily^Chen(DICOM format)
See MCP_NAMING_SCHEME.md for complete details.
Setup:
Launch the MySQL service:
docker compose up -d mysqlInitialize the database (automatic on first start, or manually):
docker exec -i dicom-mcp-mysql-1 mysql -uorthanc_ris_app -porthanc_ris_app orthanc_ris < mysql/mini_ris.sqlConfigure environment variables in
.env:MINI_RIS_DB_PASSWORD=orthanc_ris_appVerify
configuration.yamlcontains themini_risblock.
Included CR Procedures:
The database includes 14 common Computed Radiography (CR) procedures optimized for single-image study workflows:
- Chest (1 or 2 views)
- Abdomen (1 or 2 views)
- Pelvis, Cervical/Lumbar Spine
- Upper Extremity: Hand, Wrist, Shoulder
- Lower Extremity: Knee, Ankle, Foot
- Skull
Each procedure includes typical view projections (AP, PA, Lateral, Oblique) and expected image counts for realistic test data generation.
MWL/MPPS Services:
Modality Worklist (MWL) and Modality Performed Procedure Step (MPPS) live in dicom-mwl-mpps/ in this repo. That tree is the ris-integration-baseline snapshot from dicom-mwl-mpps. Start it from this repo with the commands below. make dev-setup inside dicom-mwl-mpps/ starts that package's own Compose file, including a second MySQL on port 3306, and collides with this stack.
- mwl-mpps (port 4104) - DICOM SCP for MWL queries and MPPS N-CREATE/N-SET operations
- mwl-api (port 8000) - FastAPI REST interface for creating and managing MWL entries from mini-RIS orders
Environment Variables:
Both services share the same MySQL database configuration via:
MINI_RIS_DB_PASSWORD=orthanc_ris_app # Default password for orthanc_ris_app user
Usage:
Start the MWL/MPPS services:
docker compose up -d mwl-mpps mwl-apiQuery worklist via DICOM C-FIND:
# Use -W for Modality Worklist queries (not -P for Patient Root) findscu -v -W -k 0008,0050="" -k 0010,0020="" localhost 4104 # Or query by specific accession number: findscu -v -W -k 0008,0050="ACC-2025-0001" localhost 4104Create MWL entries via REST API:
curl -X POST http://localhost:8000/mwl/create_from_json \ -H "Content-Type: application/json" \ -d @mwl_payload.jsonView MWL records in web dashboard:
open http://localhost:8000/mwl # Or visit http://localhost:8000 for the main dashboard
The MWL/MPPS tables (mwl, mpps, mwl_tasks) in the mini-RIS database store all worklist items and procedure step statuses, enabling full traceability from order to completed exam.
Creating MWLs from Orders (via MCP Tool):
The create_mwl_from_order tool automates MWL creation from mini-RIS orders:
# Example: Patient arrives, technician creates MWL from order
# In the MCP Inspector or via an LLM:
create_mwl_from_order(
order_id=1,
scheduled_station_aet="ORTHANC"
)
# Returns:
{
"success": true,
"message": "MWL created successfully for order 1",
"accession_number": "ACC-2025-0001",
"patient_name": "Alex Johnson",
"patient_id": "MRN1001",
"procedure": "Chest X-Ray 2 Views",
"modality": "CR",
"scheduled_time": "2025-06-01 09:15:00",
"mwl_id": 42
}
This enables LLM-driven workflows like:
- "Create a worklist entry for order 1"
- "Patient MRN1001 has arrived, set up their chest x-ray"
- "List all scheduled orders and create MWLs for today's patients"
Virtual CR Device 🆕
The project includes a virtual CR (Computed Radiography) device that generates synthetic DICOM images for complete workflow demonstrations:
# Example: Complete imaging workflow
# 1. Create MWL from order
create_mwl_from_order(order_id=1)
# 2. Simulate CR device acquiring images
create_synthetic_cr_study(
accession_number="ACC-2025-0001",
image_mode="simple", # or "ai" with OpenAI key
send_to_pacs=True
)
# Result: 2 CR images created and sent to Orthanc!
Image Generation Modes:
simple(No API key required) - Basic synthetic images with anatomical outlinesai(RequiresOPENAI_API_KEY) - Realistic AI-generated images via OpenAIgpt-image-1modelauto(Default) - Uses AI if key available, falls back to simplesample- Uses pre-made sample images from library
⚠️ IMPORTANT:
- Synthetic images are for development/testing/training only. NOT for clinical use.
- AI mode uses OpenAI's
gpt-image-1model (~30-40 seconds per image) - Multi-view studies (2+ images) may timeout in MCP clients but still complete successfully
- Images are created and sent to PACS even if you see a timeout error
- Check Orthanc to verify the images arrived
- For faster generation or reliable testing, use
image_mode="simple"instead of "auto"
Configuration:
Add to .env (optional for AI mode):
OPENAI_API_KEY=sk-proj-xxxxx # Optional - enables AI-generated images
LLM-Driven Workflow Examples:
User: "Patient Johnson completed their chest x-ray, create the study"
LLM: Calls create_synthetic_cr_study(accession_number="MCP-ACC-2025-0001", image_mode="simple")
Result: 2-view chest study appears in Orthanc instantly!
User: "Generate a realistic chest x-ray showing pneumonia in the right lung"
LLM: Calls with image_mode="ai", image_description="pneumonia right lower lobe"
Result: gpt-image-1 generates photorealistic pneumonia appearance (~40 seconds)
Note: May show timeout error but images still arrive in PACS
Workflow Consistency with Order-Based Prompts 🆕
Orders can now include prompts for both image generation and report creation, creating a closed-loop workflow:
- Image Generation Prompt (
image_generation_prompt): Describes what the images should show - Report Findings Description (
report_findings_description): Describes expected findings for reports
This enables consistent workflows where:
- Images are generated based on the order's
image_generation_prompt - Reports can use the order's
report_findings_descriptionas a starting point - The entire workflow (Order → Images → Report) is internally consistent
# Example: Order with prompts
# Order MCP-ORD-2025-0001 has:
# image_generation_prompt: "Chest X-ray showing subtle patchy opacity in right lower lobe"
# report_findings_description: "Subtle patchy opacity in right lower lobe consistent with early pneumonia"
# 1. Generate images using order prompt (automatically used if available)
create_synthetic_cr_study(
accession_number="MCP-ACC-2025-0001",
image_mode="ai" # Will use order's image_generation_prompt
)
# 2. Create report using order findings (optional)
create_radiology_report(
accession_number="MCP-ACC-2025-0001",
findings="", # Empty - will use order's report_findings_description
impression="Early pneumonia",
use_order_findings=True # Use order's report_findings_description
)
Benefits:
- Consistency: Images and reports match the original order intent
- Automation: Prompts stored in orders enable fully automated workflows
- Testing: Easy to test how well AI-generated images match expected findings
- Traceability: Complete audit trail from order → images → report
This completes the full RIS/PACS workflow:
Order → MWL → Virtual Device → DICOM Images → PACS Storage → Viewing → Reporting
Radiology Reporting 🆕
Create professional radiology reports and attach them as DICOM Encapsulated PDFs to studies in your PACS:
# Complete reporting workflow
# 1. Get study information for reporting
study_info = get_study_for_report(accession_number="MCP-ACC-2025-0001")
# 2. List available radiologists
radiologists = list_radiologists()
# 3. Create a radiology report
# Option A: Manual findings
report = create_radiology_report(
accession_number="MCP-ACC-2025-0001",
findings="""
The heart is normal in size. The mediastinum is unremarkable.
Both lungs are clear without focal consolidation, pleural effusion, or pneumothorax.
No acute bony abnormality is identified.
""",
impression="Normal chest radiograph. No acute cardiopulmonary process.",
author_provider_id=3, # Dr. MCP-Casey Wells (from list_radiologists)
report_status="Final"
)
# Option B: Use order's report_findings_description (if available)
report = create_radiology_report(
accession_number="MCP-ACC-2025-0001",
findings="", # Empty - will use order's report_findings_description
impression="Early pneumonia",
author_provider_id=3,
report_status="Final",
use_order_findings=True # Use order's report_findings_description
)
# 4. Generate PDF preview (optional)
pdf_data = generate_report_pdf(report_id=report['report_id'])
# Returns base64 encoded PDF for preview/download
# 5. Attach report to PACS as DICOM Encapsulated PDF
result = attach_report_to_pacs(report_id=report['report_id'])
# Report PDF now appears as a DOC series in Orthanc!
Report Workflow Features:
- Database Storage: Reports saved in mini-RIS
reportstable with full audit trail - Professional PDF: Generated with ReportLab (default) - institutional header, demographics, findings, impression, signature
- Alternative PDF Library: WeasyPrint is also installed as an option for HTML/CSS-based PDF generation (useful for web-based report templates)
- DICOM Standard: Encapsulated PDF (SOP Class:
1.2.840.10008.5.1.4.1.1.104.1) - PACS Integration: PDF attached to original study as new series (Modality: DOC, Series #9999)
- Status Tracking: Preliminary → Final → Amended → Cancelled
- Provider Attribution: Links to radiologist in mini-RIS providers table
LLM-Driven Reporting Examples:
User: "Create a final report for accession ACC-2025-0001. Normal chest x-ray."
LLM: → get_study_for_report() to fetch patient/study data
→ list_radiologists() to get available radiologists
→ create_radiology_report() with structured findings/impression
→ attach_report_to_pacs() to send PDF to PACS
Result: Complete report in database + PDF in PACS!
User: "Generate a preliminary report for the knee study showing a tibial fracture"
LLM: → Creates report with report_status="Preliminary"
→ Structures findings describing the fracture
→ Generates and attaches PDF to PACS
Result: Preliminary report available for review
User: "Show me the PDF for report ID 5"
LLM: → generate_report_pdf(report_id=5)
→ Returns base64 PDF for display/download
Report Status Workflow:
Preliminary → Final → [Amended] → [Cancelled]
Each status change creates a new audit trail entry with timestamp.
Database Schema:
reports:
- report_id (PK)
- imaging_study_id (FK to imaging_studies)
- report_number (unique, e.g., "RPT-ACC-2025-0001-20250601120000")
- author_provider_id (FK to providers - radiologist)
- report_status (enum: Preliminary, Final, Amended, Cancelled)
- report_datetime (timestamp)
- report_text (LONGTEXT - findings)
- impression (TEXT - clinical impression)
- dicom_sop_instance_uid (populated after PACS attachment)
- dicom_series_instance_uid (populated after PACS attachment)
Complete Imaging + Reporting Workflow:
┌─────────────────────────────────────────────────────────┐
│ 1. Order Management (Mini-RIS) │
│ create_mwl_from_order(order_id=1) │
└────────────────┬────────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────────┐
│ 2. Image Acquisition (Virtual CR Device) │
│ create_synthetic_cr_study(accession="ACC-2025-0001") │
└────────────────┬────────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────────┐
│ 3. PACS Storage (Orthanc) │
│ Images viewable at https://localhost:8042 │
└────────────────┬────────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────────┐
│ 4. Radiology Reporting │
│ create_radiology_report(...) │
│ attach_report_to_pacs(report_id=1) │
└────────────────┬────────────────────────────────────────┘
│
┌────────────────▼────────────────────────────────────────┐
│ 5. Complete Study in PACS │
│ - CR Images (Series 1, 2) │
│ - Report PDF (Series 9999, Modality DOC) │
└─────────────────────────────────────────────────────────┘
🧪 Synthetic Data for Testing
To test orchestration workflows, populate your local HAPI FHIR server with synthetic data:
docker compose up -d hapi-fhir
python tests/populate_synthetic_fhir_data.py
This creates five patients (Smith, Johnson, Williams, Brown, and Davis), an order and an imaging study for each, and a diagnostic report for the studies that are not in the future. List them with fhir_search_resource and resource_type set to Patient.
🔄 Orchestration Workflows
The MCP server enables end-to-end radiology workflows combining FHIR and DICOM:
- Order Entry: Create ServiceRequest in FHIR
- Study Acquisition: Link DICOM studies to FHIR ImagingStudies
- Reporting: Generate DiagnosticReports from DICOM PDFs
- Workflow Management: Track orders through completion
🔧 Development & Debugging
The official MCP Inspector is the tool for development, testing, and debugging this server. It runs locally and does not require an account.
Development Workflow:
- Start Docker:
docker compose up -d - Load test data:
pytestafter copying.env.exampleto.env - Start the Inspector with the command in Using the MCP Inspector
- Call tools from the Tools tab and read the message log beside it
🎨 Custom Web UI
This repo also includes a small web UI for chat and tool browsing. HAPI FHIR already uses port 8080, so run the UI on 8081:
source venv/bin/activate
PYTHONPATH=src uvicorn dicom_mcp.web_ui:app --host 127.0.0.1 --port 8081
Open http://127.0.0.1:8081. Chat calls the tools only when OPENAI_API_KEY is set. The tool list works without it.
Features:
- ✅ LLM-Powered Chat - Intelligent chat with OpenAI integration for natural language queries
- ✅ Tool Browser - Browse and explore the DICOM, FHIR, and mini-RIS tools
- ✅ Prompt Management - Edit and save system prompts optimized for medical imaging
- ✅ Tool Execution - Execute tools directly from chat or UI
- ✅ Medical Imaging Focus - Customized for DICOM and FHIR workflows
- ✅ Self-Contained - Everything in your repo, no external services needed
- ✅ Dark Theme - Beautiful, modern dark UI
- ✅ Saved Resources - Curated reference files (e.g., Orthanc OpenAPI) live in
resources/manifest.yaml, accessible via the Resources panel or newlist_saved_resources/get_saved_resourceMCP tools.
LLM Integration:
Enable OpenAI-powered chat by setting your API key:
export OPENAI_API_KEY="your-api-key-here"
The LLM will:
- Understand natural language queries about medical imaging
- Automatically select and execute appropriate DICOM/FHIR tools
- Format results in a clinical, readable format
- Use the medical imaging system prompt for context-aware responses
Example Queries:
- "List all available DICOM nodes"
- "Find patients with last name Smith"
- "Show me studies from last week"
- "Verify connection to PACS"
- "What tools are available for FHIR?"
🙏 Acknowledgments
- Built using FastMCP - The fast, Pythonic way to build MCP servers
- Built using pynetdicom for DICOM network communication
- Uses pypdf for PDF text extraction
Yorumlar (0)
Yorum birakmak icin giris yap.
Yorum birakSonuc bulunamadi