医疗文档处理服务器

一个全面的医疗文档处理服务器,提供文档上传、OCR处理、医疗命名实体识别、本地嵌入生成和基于向量的语义搜索功能。

  • by KalyankumarKonduru
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 kalyankumarkonduru/mcp-server

使用说明

医疗MCP服务器

一个全面的模型上下文协议(MCP)服务器,用于具有高级AI功能的医疗文档处理。该服务器为医疗保健应用程序提供文档上传、OCR处理、医疗命名实体识别(NER)、本地嵌入生成和基于向量的语义搜索。

🏥 特性

  • 文档处理:通过自动文本提取上传和处理医疗文档(PDF、图像)
  • 医疗NER:从文本中提取医疗实体(药物、条件、程序、实验室值)
  • 本地嵌入:使用本地HuggingFace模型生成嵌入,以保护隐私和控制
  • 矢量搜索:跨医疗文档和患者数据的语义相似性搜索
  • OCR处理:从医学图像和扫描文档中提取文本
  • PDF支持:通过文本提取和分析处理医学PDF
  • MongoDB集成:使用优化的索引存储文档、嵌入和医疗实体
  • 多种运输方式:HTTP和STDIO传输支持
  • 健康监测:内置健康检查端点和服务监控
  • 文档管理:完成医疗文件的CRUD操作

📋 可用工具

文档管理

  • uploadDocument -通过自动文本提取、NER和嵌入生成上传和处理医疗文档
  • searchDocuments -使用向量相似度和混合排名的文本搜索搜索文档
  • listDocuments -按患者、文档类型或日期范围筛选列出文档

医学分析

  • extractMedicalEntities -从文本中提取医疗实体(药物、条件、程序等)
  • findSimilarCases -根据症状、病情或药物查找类似的医疗病例
  • analyzePatientHistory -使用时间线、摘要或趋势分析分析患者病史
  • getMedicalInsights -根据查询和上下文获取医学见解和建议

嵌入和搜索

  • generateEmbeddingLocal -使用HuggingFace变压器在本地生成嵌入
  • chunkAndEmbedDocument -将大型文档分割成块,并为每个块生成嵌入
  • semanticSearchLocal -使用本地嵌入执行语义搜索

🚀 快速开始

先决条件

  • Node.js 18.0.0或更高版本
  • TypeScript 5.0.0或更高版本
  • MongoDB 4.4或更高版本
  • Python 3.8+(用于本地嵌入模型)
  • Tesseract OCR(用于图像文本提取)

美人鱼图:-

graph TB
    subgraph "MCP Server (mcp-server)"
        subgraph "MCP Protocol Layer"
            Transport[Transport<br/>- Stdio mode<br/>- HTTP mode :3001]
            Protocol[MCP Protocol Handler<br/>- Initialize<br/>- List tools<br/>- Call tools]
        end

        subgraph "Tool Registry (What Makes it MCP)"
            Registry[Tool Registry<br/>THE MCP SERVER CORE]
            
            DocTools[ Document Tools<br/>- uploadDocument<br/>- searchDocuments<br/>- listDocuments]
            
            MedTools[ Medical Tools<br/>- extractMedicalEntities<br/>- findSimilarCases<br/>- analyzePatientHistory<br/>- getMedicalInsights]
            
            EmbedTools[ Embedding Tools<br/>- generateEmbeddingLocal<br/>- chunkAndEmbedDocument<br/>- semanticSearchLocal]
        end

        subgraph "Service Layer (Tool Implementations)"
            PDF[PDF Service]
            OCR[OCR Service]
            NER[Medical NER]
            Embed[Local Embeddings]
        end

        subgraph "Storage"
            Mongo[(MongoDB<br/>Documents & Vectors)]
        end
    end

    %% MCP Protocol Flow
    Transport -->|MCP Messages| Protocol
    Protocol -->|"tools/list"| Registry
    Protocol -->|"tools/call"| Registry

    %% Tool Registration
    Registry --> DocTools
    Registry --> MedTools
    Registry --> EmbedTools

    %% Tool Implementation
    DocTools --> PDF
    DocTools --> OCR
    DocTools --> NER
    DocTools --> Embed
    MedTools --> NER
    MedTools --> Embed
    EmbedTools --> Embed

    %% Storage
    DocTools --> Mongo
    MedTools --> Mongo
    EmbedTools --> Mongo

    %% Styling
    classDef protocol fill:#e1f5fe,stroke:#0277bd
    classDef core fill:#f3e5f5,stroke:#7b1fa2,stroke-width:3px
    classDef tools fill:#c8e6c9,stroke:#2e7d32
    classDef service fill:#fce4ec,stroke:#c2185b
    classDef storage fill:#fff9c4,stroke:#f57f17

    class Transport,Protocol protocol
    class Registry core
    class DocTools,MedTools,EmbedTools tools
    class PDF,OCR,NER,Embed service
    class Mongo storage

安装

# Clone the repository
git clone https://github.com/your-username/medical-mcp-server.git
cd medical-mcp-server

# Install dependencies
npm install

# Install Python dependencies for embeddings
pip install torch transformers sentence-transformers

# Install Tesseract OCR
# On Ubuntu/Debian:
sudo apt-get install tesseract-ocr

# On macOS:
brew install tesseract

# On Windows:
# Download from: https://github.com/UB-Mannheim/tesseract/wiki

# Build the project
npm run build

环境配置

创建一个 .env 根目录中的文件:

# MongoDB Configuration (Required)
MONGODB_CONNECTION_STRING=mongodb://localhost:27017/medical_mcp
MONGODB_DATABASE_NAME=MCP

# Server Configuration
MCP_HTTP_PORT=3001
MCP_HTTP_MODE=true

# OCR Configuration
TESSERACT_PATH=/usr/bin/tesseract
OCR_LANGUAGE=eng

# Embedding Model Configuration
EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
EMBEDDING_DEVICE=cpu
EMBEDDING_CACHE_DIR=./models

# Document Storage
DOCUMENT_UPLOAD_PATH=./uploads
MAX_DOCUMENT_SIZE=10485760

# Logging
LOG_LEVEL=info
LOG_FILE=./logs/medical-mcp.log

MongoDB设置

# Start MongoDB
mongod --dbpath ./data/db

# Create indexes (run once)
npm run setup-indexes

运行服务器

HTTP模式(推荐)

npm run start:http

STDIO模式

npm run start:stdio

开发模式

npm run dev:http

📊 健康监测

检查服务器运行状况:

curl http://localhost:3001/health

答复:

{
  "status": "healthy",
  "server": "medical-mcp-server-with-epic",
  "version": "1.0.0",
  "features": [
    "document-processing",
    "medical-ner", 
    "vector-search",
    "epic-fhir"
  ],
  "services": {
    "mongodb": true,
    "localEmbedding": true,
    "ner": true,
    "ocr": true,
    "pdf": true
  },
  "statistics": {
    "documentsCount": 150,
    "embeddingModel": "sentence-transformers/all-MiniLM-L6-v2",
    "uptime": 3600
  },
  "timestamp": "2025-01-23T10:30:00.000Z"
}

🔧 工具使用示例

上传医疗文件

{
  "tool": "uploadDocument",
  "arguments": {
    "title": "Patient Lab Results - John Doe",
    "filePath": "/path/to/lab-results.pdf",
    "metadata": {
      "fileType": "pdf",
      "patientId": "patient-123",
      "documentType": "lab_report",
      "tags": ["blood-work", "lipid-panel"]
    }
  }
}

搜索文档

{
  "tool": "searchDocuments",
  "arguments": {
    "query": "high cholesterol treatment recommendations",
    "limit": 10,
    "searchType": "hybrid",
    "filter": {
      "documentType": "clinical_note",
      "patientId": "patient-123"
    }
  }
}

提取医疗实体

{
  "tool": "extractMedicalEntities",
  "arguments": {
    "text": "Patient presents with hypertension and diabetes. Prescribed metformin 500mg twice daily and lisinopril 10mg once daily.",
    "entityTypes": ["MEDICATION", "CONDITION", "DOSAGE"]
  }
}

查找类似案例

{
  "tool": "findSimilarCases",
  "arguments": {
    "symptoms": ["chest pain", "shortness of breath"],
    "conditions": ["hypertension"],
    "patientId": "patient-123",
    "limit": 5
  }
}

生成本地嵌入

{
  "tool": "generateEmbeddingLocal",
  "arguments": {
    "text": "Patient has a history of coronary artery disease and recent myocardial infarction",
    "metadata": {
      "patientId": "patient-123",
      "documentType": "clinical_note"
    }
  }
}

📚 api参考

MCP端点

  • 统一资源定位符: http://localhost:3001/mcp
  • 方法:POST
  • 内容类型:应用程序/json
  • 格式:JSON-RPC 2.0

健康检查

  • 统一资源定位符: http://localhost:3001/health
  • 方法:获取

🛠 发展

脚本

# Build TypeScript
npm run build

# Start in HTTP mode
npm run start:http

# Start in STDIO mode
npm run start:stdio

# Development with hot reload
npm run dev:http

# Clean build artifacts
npm run clean

# Setup MongoDB indexes
npm run setup-indexes

# Run tests
npm test

# Lint code
npm run lint

项目结构

medical-mcp-server/
├── src/
│   ├── server.ts              # Main server implementation
│   ├── db/
│   │   ├── mongodb-client.ts  # MongoDB connection and operations
│   │   └── setup-vector-indexes.ts # Database index setup
│   ├── services/
│   │   ├── local-embedding-service.ts # HuggingFace embedding service
│   │   ├── medical-ner-service.ts     # Medical NER processing
│   │   ├── ocr-service.ts            # OCR text extraction
│   │   └── pdf-service.ts            # PDF processing
│   └── tools/
│       ├── document-tools.ts         # Document management tools
│       ├── medical-tools.ts          # Medical analysis tools
│       └── local-embedding-tools.ts  # Embedding and search tools
├── dist/                      # Compiled JavaScript
├── uploads/                   # Document upload directory
├── models/                    # Local AI model cache
├── logs/                      # Server logs
├── package.json
├── tsconfig.json
└── .env                       # Environment configuration

🤖 人工智能模型和服务

局部嵌入模型

  • 默认: sentence-transformers/all-MiniLM-L6-v2
  • 医学专业: clinical-ai/ClinicalBERT
  • 大型模型: sentence-transformers/all-mpnet-base-v2

医疗NER模型

  • BioBERT:用于生物医学文本处理
  • 临床BERT:专门用于临床记录
  • SciSpaCy:医疗实体认定

OCR引擎

  • 立方体:多语言OCR支持
  • 医疗增强:处方、实验室报告、临床记录优化

🔍 故障排除

常见问题

  1. MongoDB连接失败

    • 验证MongoDB是否正在运行且可访问
    • 检查连接字符串格式
    • 确保数据库权限
  2. OCR处理错误

    • 安装Tesseract OCR引擎
    • 验证TESSERACT_PATH环境变量
    • 检查图像文件格式(支持PNG、JPG、PDF)
  3. 嵌入模型问题

    • 确保有足够的磁盘空间用于模型下载
    • 检查Python依赖关系(torch、transformers)
    • 验证初始模型下载的互联网连接
  4. 内存问题

    • 调整大型文档的嵌入批量大小
    • 考虑使用较小的嵌入模型
    • 监控MongoDB内存使用情况
  5. 文档上传失败

    • 检查文件大小限制(默认10MB)
    • 验证上传目录权限
    • 确保支持的文件格式

调试

启用详细日志记录:

# Set log level to debug
export LOG_LEVEL=debug
npm run dev:http

检查MongoDB索引:

# Connect to MongoDB and list indexes
mongo medical_mcp
db.documents.getIndexes()
db.embeddings.getIndexes()

监视器嵌入服务:

# Check embedding model status
curl http://localhost:3001/health | jq '.services.localEmbedding'

📄 Package.json

{
  "name": "medical-mcp-server",
  "version": "1.0.0",
  "description": "Medical MCP Server with document processing, NER, and vector search capabilities",
  "type": "module",
  "main": "dist/server.js",
  "bin": {
    "medical-mcp-server": "./dist/server.js"
  },
  "scripts": {
    "build": "tsc",
    "start": "node dist/server.js",
    "start:http": "MCP_HTTP_MODE=true node dist/server.js",
    "start:stdio": "node dist/server.js",
    "dev": "tsc --watch & nodemon dist/server.js",
    "dev:http": "MCP_HTTP_MODE=true tsc --watch & nodemon dist/server.js",
    "clean": "rm -rf dist",
    "setup-indexes": "node dist/db/setup-vector-indexes.js",
    "test": "jest",
    "lint": "eslint src/**/*.ts",
    "lint:fix": "eslint src/**/*.ts --fix"
  },
  "keywords": [
    "medical",
    "healthcare",
    "mcp",
    "ner",
    "ocr",
    "embeddings",
    "vector-search",
    "document-processing",
    "mongodb",
    "huggingface"
  ],
  "author": "Your Name",
  "license": "MIT",
  "dependencies": {
    "@modelcontextprotocol/sdk": "^0.5.0",
    "cors": "^2.8.5",
    "dotenv": "^17.2.0",
    "express": "^4.18.2",
    "mongodb": "^6.3.0",
    "multer": "^1.4.5",
    "pdf-parse": "^1.1.1",
    "tesseract.js": "^5.0.0",
    "uuid": "^9.0.1"
  },
  "devDependencies": {
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.17",
    "@types/multer": "^1.4.11",
    "@types/node": "^20.0.0",
    "@types/uuid": "^9.0.8",
    "eslint": "^8.57.0",
    "@typescript-eslint/eslint-plugin": "^7.0.0",
    "@typescript-eslint/parser": "^7.0.0",
    "jest": "^29.7.0",
    "@types/jest": "^29.5.0",
    "nodemon": "^3.0.0",
    "typescript": "^5.0.0"
  },
  "engines": {
    "node": ">=18.0.0"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/your-username/medical-mcp-server.git"
  },
  "bugs": {
    "url": "https://github.com/your-username/medical-mcp-server/issues"
  },
  "homepage": "https://github.com/your-username/medical-mcp-server#readme"
}

🐳 Docker支持

Dockerfile

FROM node:18-alpine

# Install system dependencies
RUN apk add --no-cache \
    tesseract-ocr \
    tesseract-ocr-data-eng \
    python3 \
    py3-pip \
    build-base

# Install Python dependencies
RUN pip3 install torch transformers sentence-transformers

WORKDIR /app

# Copy package files
COPY package*.json ./
RUN npm ci --only=production

# Copy source code
COPY dist/ ./dist/
COPY uploads/ ./uploads/
COPY models/ ./models/

EXPOSE 3001

CMD ["npm", "start"]

Docker Compose

version: '3.8'

services:
  medical-mcp-server:
    build: .
    ports:
      - "3001:3001"
    environment:
      - MONGODB_CONNECTION_STRING=mongodb://mongo:27017/medical_mcp
      - MCP_HTTP_MODE=true
    depends_on:
      - mongo
    volumes:
      - ./uploads:/app/uploads
      - ./models:/app/models

  mongo:
    image: mongo:7
    ports:
      - "27017:27017"
    volumes:
      - mongo-data:/data/db

volumes:
  mongo-data:

📄 许可证

MIT许可证-请参阅 许可证 文件以获取详细信息。

🤝 贡献

  1. 分叉存储库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add amazing feature')
  4. 推到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

📞 支持


备注:此服务器处理医疗文档,并要求为生产部署采取适当的安全措施。在处理真实的患者数据时,确保遵守HIPAA和其他医疗保健法规。