Commit Β·
71cadf5
1
Parent(s): aa855d9
Add new version
Browse filesFiles changed (31)
- .gitignoreAdded+1
- README.mdDeleted-14
- app.py β gradio_server.pyRenamed+3-1
- requirements.txt+11-1
- src/__pycache__/dependencies.cpython-310.pycAdded
- src/__pycache__/gradio_server.cpython-310.pycAdded
- src/__pycache__/main.cpython-310.pycAdded
- src/__pycache__/server.cpython-310.pycAdded
- src/dependencies.pyAdded+162
- src/main.pyAdded+136
- src/server.pyAdded+564
- src/services/__init__.pyAdded+1
- src/services/__pycache__/__init__.cpython-310.pycAdded
- src/services/__pycache__/cache_service.cpython-310.pycAdded
- src/services/__pycache__/usage_service.cpython-310.pycAdded
- src/services/cache_service.pyAdded+299
- src/services/usage_service.pyAdded+318
- src/tools/__init__.pyAdded+69
- src/tools/__pycache__/__init__.cpython-310.pycAdded
- src/tools/__pycache__/base_tool.cpython-310.pycAdded
- src/tools/__pycache__/clinical_trials_tool.cpython-310.pycAdded
- src/tools/__pycache__/fda_tool.cpython-310.pycAdded
- src/tools/__pycache__/healthfinder_tool.cpython-310.pycAdded
- src/tools/__pycache__/medical_terminology_tool.cpython-310.pycAdded
- src/tools/__pycache__/pubmed_tool.cpython-310.pycAdded
- base_tool.py β src/tools/base_tool.pyRenamed
- clinical_trials_tool.py β src/tools/clinical_trials_tool.pyRenamed
- fda_tool.py β src/tools/fda_tool.pyRenamed
- healthfinder_tool.py β src/tools/healthfinder_tool.pyRenamed
- medical_terminology_tool.py β src/tools/medical_terminology_tool.pyRenamed
- pubmed_tool.py β src/tools/pubmed_tool.pyRenamed
1.DS_Store1234567891011121314---title: Healthcare Mcp Publicemoji: π¬colorFrom: yellowcolorTo: purplesdk: gradiosdk_version: 5.0.1app_file: app.pypinned: falselicense: apache-2.0short_description: MCP server providing access to medical data APIs---
An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).250 unmodified lines251252253254255256257255250 unmodified lines# ---------------------------------------------------------------------------
if __name__ == "__main__": # Launch the Gradio UI **and** expose an MCP server via FastAPI # Setting "mcp_server=True" means gradio will attach the FastMCP instance # found in the global namespace (named `mcp`). demo.launch(mcp_server=True, show_error=True)
11234567891011huggingface_hub==0.25.2fastapi==0.115.12mcp==1.6.0pydantic==2.11.3pytest==8.3.5python-dotenv==1.1.0Requests==2.32.3slowapi==0.1.9structlog==25.2.0uvicorn==0.34.2pytest-asynciogradio123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162"""Dependency injection module for FastAPI"""import loggingfrom typing import AsyncGenerator, Optionalfrom fastapi import Depends
from src.services.cache_service import CacheServicefrom src.services.usage_service import UsageServicefrom src.tools.fda_tool import FDAToolfrom src.tools.pubmed_tool import PubMedToolfrom src.tools.healthfinder_tool import HealthFinderToolfrom src.tools.clinical_trials_tool import ClinicalTrialsToolfrom src.tools.medical_terminology_tool import MedicalTerminologyTool
logger = logging.getLogger("healthcare-mcp")
# Singleton instances_cache_service: Optional[CacheService] = None_usage_service: Optional[UsageService] = None
# Tool instances_fda_tool: Optional[FDATool] = None_pubmed_tool: Optional[PubMedTool] = None_healthfinder_tool: Optional[HealthFinderTool] = None_clinical_trials_tool: Optional[ClinicalTrialsTool] = None_medical_terminology_tool: Optional[MedicalTerminologyTool] = None
async def get_cache_service() -> AsyncGenerator[CacheService, None]: """ Get or create the cache service instance Returns: CacheService: The cache service instance """ global _cache_service if _cache_service is None: logger.info("Initializing cache service") _cache_service = CacheService() await _cache_service.init() try: yield _cache_service except Exception as e: logger.error(f"Error with cache service: {str(e)}") raise
async def get_usage_service() -> AsyncGenerator[UsageService, None]: """ Get or create the usage service instance Returns: UsageService: The usage service instance """ global _usage_service if _usage_service is None: logger.info("Initializing usage service") _usage_service = UsageService() await _usage_service.init() try: yield _usage_service except Exception as e: logger.error(f"Error with usage service: {str(e)}") raise
async def get_fda_tool() -> AsyncGenerator[FDATool, None]: """ Get or create the FDA tool instance Returns: FDATool: The FDA tool instance """ global _fda_tool if _fda_tool is None: logger.info("Initializing FDA tool") _fda_tool = FDATool() try: yield _fda_tool except Exception as e: logger.error(f"Error with FDA tool: {str(e)}") raise
async def get_pubmed_tool() -> AsyncGenerator[PubMedTool, None]: """ Get or create the PubMed tool instance Returns: PubMedTool: The PubMed tool instance """ global _pubmed_tool if _pubmed_tool is None: logger.info("Initializing PubMed tool") _pubmed_tool = PubMedTool() try: yield _pubmed_tool except Exception as e: logger.error(f"Error with PubMed tool: {str(e)}") raise
async def get_healthfinder_tool() -> AsyncGenerator[HealthFinderTool, None]: """ Get or create the HealthFinder tool instance Returns: HealthFinderTool: The HealthFinder tool instance """ global _healthfinder_tool if _healthfinder_tool is None: logger.info("Initializing HealthFinder tool") _healthfinder_tool = HealthFinderTool() try: yield _healthfinder_tool except Exception as e: logger.error(f"Error with HealthFinder tool: {str(e)}") raise
async def get_clinical_trials_tool() -> AsyncGenerator[ClinicalTrialsTool, None]: """ Get or create the ClinicalTrials tool instance Returns: ClinicalTrialsTool: The ClinicalTrials tool instance """ global _clinical_trials_tool if _clinical_trials_tool is None: logger.info("Initializing ClinicalTrials tool") _clinical_trials_tool = ClinicalTrialsTool() try: yield _clinical_trials_tool except Exception as e: logger.error(f"Error with ClinicalTrials tool: {str(e)}") raise
async def get_medical_terminology_tool() -> AsyncGenerator[MedicalTerminologyTool, None]: """ Get or create the MedicalTerminology tool instance Returns: MedicalTerminologyTool: The MedicalTerminology tool instance """ global _medical_terminology_tool if _medical_terminology_tool is None: logger.info("Initializing MedicalTerminology tool") _medical_terminology_tool = MedicalTerminologyTool() try: yield _medical_terminology_tool except Exception as e: logger.error(f"Error with MedicalTerminology tool: {str(e)}") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import osimport uuidfrom dotenv import load_dotenvfrom mcp.server.fastmcp import FastMCP, Context
# Load environment variablesload_dotenv()
# Create MCP servermcp = FastMCP( name="healthcare-mcp", version="1.0.0", description="Healthcare MCP server for medical information access")
# Import tools and servicesfrom src.tools.fda_tool import FDAToolfrom src.tools.pubmed_tool import PubMedToolfrom src.tools.healthfinder_tool import HealthFinderToolfrom src.tools.clinical_trials_tool import ClinicalTrialsToolfrom src.tools.medical_terminology_tool import MedicalTerminologyToolfrom src.services.usage_service import UsageService
# Initialize tool instances and servicesfda_tool = FDATool()pubmed_tool = PubMedTool()healthfinder_tool = HealthFinderTool()clinical_trials_tool = ClinicalTrialsTool()medical_terminology_tool = MedicalTerminologyTool()usage_service = UsageService(db_path="healthcare_usage.db")
# Generate a unique session ID for this connectionsession_id = str(uuid.uuid4())
@mcp.tool()async def fda_drug_lookup(ctx: Context, drug_name: str, search_type: str = "general"): """ Look up drug information from the FDA database Args: drug_name: Name of the drug to search for search_type: Type of information to retrieve: 'label', 'adverse_events', or 'general' """ # Record usage usage_service.record_usage(session_id, "fda_drug_lookup") # Call the tool return await fda_tool.lookup_drug(drug_name, search_type)
@mcp.tool()async def pubmed_search(ctx: Context, query: str, max_results: int = 5, date_range: str = ""): """ Search for medical literature in PubMed database Args: query: Search query for medical literature max_results: Maximum number of results to return date_range: Limit to articles published within years (e.g. '5' for last 5 years) """ # Record usage usage_service.record_usage(session_id, "pubmed_search") # Call the tool return await pubmed_tool.search_literature(query, max_results, date_range)
@mcp.tool()async def health_topics(ctx: Context, topic: str, language: str = "en"): """ Get evidence-based health information on various topics Args: topic: Health topic to search for information language: Language for content (en or es) """ # Record usage usage_service.record_usage(session_id, "health_topics") # Call the tool return await healthfinder_tool.get_health_topics(topic, language)
@mcp.tool()async def clinical_trials_search(ctx: Context, condition: str, status: str = "recruiting", max_results: int = 10): """ Search for clinical trials by condition, status, and other parameters Args: condition: Medical condition or disease to search for status: Trial status (recruiting, completed, active, not_recruiting, or all) max_results: Maximum number of results to return """ # Record usage usage_service.record_usage(session_id, "clinical_trials_search") # Call the tool return await clinical_trials_tool.search_trials(condition, status, max_results)
@mcp.tool()async def lookup_icd_code(ctx: Context, code: str = None, description: str = None, max_results: int = 10): """ Look up ICD-10 codes by code or description Args: code: ICD-10 code to look up (optional if description is provided) description: Medical condition description to search for (optional if code is provided) max_results: Maximum number of results to return """ # Record usage usage_service.record_usage(session_id, "lookup_icd_code") # Call the tool return await medical_terminology_tool.lookup_icd_code(code, description, max_results)
@mcp.tool()async def get_usage_stats(ctx: Context): """ Get usage statistics for the current session Returns: A summary of API usage for the current session """ return usage_service.get_monthly_usage(session_id)
@mcp.tool()async def get_all_usage_stats(ctx: Context): """ Get overall usage statistics for all sessions Returns: A summary of API usage across all sessions """ return usage_service.get_usage_stats()
if __name__ == "__main__": # Using FastMCP's CLI import sys sys.exit(mcp.run())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564import osimport loggingimport structlogfrom contextlib import asynccontextmanagerfrom typing import Optional, Union, Dict, Any, List, Annotatedfrom fastapi import FastAPI, Request, Depends, HTTPException, Header, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponsefrom pydantic import BaseModel, Fieldfrom dotenv import load_dotenvfrom slowapi import Limiter, _rate_limit_exceeded_handlerfrom slowapi.errors import RateLimitExceededfrom slowapi.util import get_remote_addressfrom src.main import mcpfrom src.tools.base_tool import BaseToolfrom src.dependencies import ( get_cache_service, get_usage_service, get_fda_tool, get_pubmed_tool, get_healthfinder_tool, get_clinical_trials_tool, get_medical_terminology_tool)
# Set up structured logginglogging.basicConfig(level=logging.DEBUG)structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.TimeStamper(fmt="iso"), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.processors.JSONRenderer() ], context_class=dict, logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True,)logger = structlog.get_logger("healthcare-mcp")
# Load environment variablesload_dotenv()
# Add lifespan event handlers@asynccontextmanagerasync def lifespan(app: FastAPI): """Lifespan context manager for startup and shutdown events""" # Startup: Initialize services logger.info("Starting Healthcare MCP Server") # Initialize services if needed try: from src.services.cache_service import CacheService cache = CacheService() await cache.init() logger.info("Cache service initialized") except Exception as e: logger.error("Failed to initialize cache service", error=str(e)) try: from src.services.usage_service import UsageService usage = UsageService() await usage.init() logger.info("Usage service initialized") except Exception as e: logger.error("Failed to initialize usage service", error=str(e)) yield # Server is running # Shutdown: Clean up resources logger.info("Shutting down Healthcare MCP Server") # Close the shared HTTP client try: from src.tools.base_tool import BaseTool await BaseTool.close_http_client() logger.info("HTTP client closed") except Exception as e: logger.error("Failed to close HTTP client", error=str(e)) # Close services try: from src.services.cache_service import CacheService cache = CacheService() await cache.close() logger.info("Cache service closed") except Exception as e: logger.error("Failed to close cache service", error=str(e)) try: from src.services.usage_service import UsageService usage = UsageService() await usage.close() logger.info("Usage service closed") except Exception as e: logger.error("Failed to close usage service", error=str(e))
# Set up rate limiterlimiter = Limiter(key_func=get_remote_address)
# Create FastAPI app with lifespanapp = FastAPI( title="Healthcare MCP API", description="Healthcare MCP server for medical information access", version="1.0.0", docs_url="/docs", redoc_url="/redoc", lifespan=lifespan)
# Add rate limiter to appapp.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Add CORS middlewareapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
# Add OpenTelemetry instrumentation if enabledif os.getenv("ENABLE_TELEMETRY", "false").lower() == "true": try: from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor FastAPIInstrumentor.instrument_app(app) logger.info("OpenTelemetry instrumentation enabled") except ImportError: logger.warning("OpenTelemetry packages not installed, skipping instrumentation")
# Import necessary components for request handlingfrom fastapi import Body, Query, Path, BackgroundTasksfrom pydantic import BaseModel, Field, ConfigDictfrom typing import Dict, Any, Optional, List, Union, Annotated
# Define tool request modelclass ToolRequest(BaseModel): """Request model for tool execution""" model_config = ConfigDict(extra="forbid") name: str = Field(..., description="Name of the tool to execute") arguments: Dict[str, Any] = Field(..., description="Arguments to pass to the tool") session_id: Optional[str] = Field(None, description="Session ID for tracking usage")
# Define error response modelclass ErrorResponse(BaseModel): """Standard error response""" model_config = ConfigDict(frozen=True) status: str = Field("error", description="Status of the response") error_message: str = Field(..., description="Error message") error_code: Optional[str] = Field(None, description="Error code for categorization") # Define success response modelclass SuccessResponse(BaseModel): """Base success response""" model_config = ConfigDict(extra="allow") status: str = Field("success", description="Status of the response")
# Mount SSE endpoint (but don't mount it at the same path as other APIs)app.mount("/mcp/sse", mcp.sse_app())
# Define API endpoints for each tool@app.get("/api/fda", summary="Look up drug information from the FDA database", description="Search for drug information in the FDA database by drug name and search type", response_model=Union[SuccessResponse, ErrorResponse], tags=["Drug Information"])@limiter.limit("60/minute")async def api_fda_drug_lookup( request: Request, drug_name: Annotated[str, Query(description="Name of the drug to search for")], search_type: Annotated[str, Query(description="Type of information to retrieve: 'label', 'adverse_events', or 'general'")] = "general", session_id: Annotated[Optional[str], Header(description="Session ID for tracking usage")] = None): """ Look up drug information from the FDA database - **drug_name**: Name of the drug to search for - **search_type**: Type of information to retrieve: 'label', 'adverse_events', or 'general' - **session_id**: Optional session ID for tracking usage """ try: from src.main import fda_drug_lookup logger.info("FDA drug lookup request", drug_name=drug_name, search_type=search_type, session_id=session_id) return await fda_drug_lookup(session_id, drug_name, search_type) except Exception as e: logger.error("Error in FDA drug lookup", error=str(e), drug_name=drug_name) return ErrorResponse(error_message=f"Error looking up drug information: {str(e)}")
@app.get("/api/pubmed", summary="Search for medical literature in PubMed database", description="Search for medical literature in PubMed database by query, with options for max results and date range", response_model=Union[SuccessResponse, ErrorResponse], tags=["Medical Literature"])@limiter.limit("30/minute")async def api_pubmed_search( request: Request, query: Annotated[str, Query(description="Search query for medical literature")], max_results: Annotated[int, Query(description="Maximum number of results to return", ge=1, le=50)] = 5, date_range: Annotated[str, Query(description="Limit to articles published within years (e.g. '5' for last 5 years)")] = "", session_id: Annotated[Optional[str], Header(description="Session ID for tracking usage")] = None): """ Search for medical literature in PubMed database - **query**: Search query for medical literature - **max_results**: Maximum number of results to return (1-50) - **date_range**: Limit to articles published within years (e.g. '5' for last 5 years) - **session_id**: Optional session ID for tracking usage """ try: from src.main import pubmed_search logger.info("PubMed search request", query=query, max_results=max_results, date_range=date_range, session_id=session_id) return await pubmed_search(session_id, query, max_results, date_range) except Exception as e: logger.error("Error in PubMed search", error=str(e), query=query) return ErrorResponse(error_message=f"Error searching PubMed: {str(e)}")
@app.get("/api/health_finder", summary="Get evidence-based health information on various topics", description="Access evidence-based health information from Health.gov", response_model=Union[SuccessResponse, ErrorResponse], tags=["Health Information"])@limiter.limit("60/minute")async def api_health_topics( request: Request, topic: Annotated[str, Query(description="Health topic to search for information")], language: Annotated[str, Query(description="Language for content (en or es)")] = "en", session_id: Annotated[Optional[str], Header(description="Session ID for tracking usage")] = None): """ Get evidence-based health information on various topics - **topic**: Health topic to search for information - **language**: Language for content (en or es) - **session_id**: Optional session ID for tracking usage """ try: from src.main import health_topics logger.info("Health topics request", topic=topic, language=language, session_id=session_id) return await health_topics(session_id, topic, language) except Exception as e: logger.error("Error in health topics", error=str(e), topic=topic) return ErrorResponse(error_message=f"Error fetching health information: {str(e)}")
@app.get("/api/clinical_trials", summary="Search for clinical trials by condition and status", description="Search for clinical trials by medical condition, status, and other parameters", response_model=Union[SuccessResponse, ErrorResponse], tags=["Clinical Trials"])@limiter.limit("30/minute")async def api_clinical_trials( request: Request, condition: Annotated[str, Query(description="Medical condition or disease to search for")], status: Annotated[str, Query(description="Trial status (recruiting, completed, active, not_recruiting, or all)")] = "recruiting", max_results: Annotated[int, Query(description="Maximum number of results to return", ge=1, le=100)] = 10, session_id: Annotated[Optional[str], Header(description="Session ID for tracking usage")] = None, clinical_trials_tool = Depends(get_clinical_trials_tool), usage_service = Depends(get_usage_service)): """ Search for clinical trials by condition, status, and other parameters - **condition**: Medical condition or disease to search for - **status**: Trial status (recruiting, completed, active, not_recruiting, or all) - **max_results**: Maximum number of results to return (1-100) - **session_id**: Optional session ID for tracking usage """ try: logger.info("Clinical trials search request", condition=condition, status=status, max_results=max_results, session_id=session_id) # Track usage if session_id: await usage_service.track_usage(session_id, "clinical_trials_search", { "condition": condition, "status": status, "max_results": max_results }) # Call the tool directly result = await clinical_trials_tool.search_trials(condition, status, max_results) return result except Exception as e: logger.error("Error in clinical trials search", error=str(e), condition=condition) return ErrorResponse(error_message=f"Error searching clinical trials: {str(e)}")
@app.get("/api/medical_terminology", summary="Look up ICD-10 codes by code or description", description="Look up ICD-10 codes and medical terminology definitions", response_model=Union[SuccessResponse, ErrorResponse], tags=["Medical Terminology"])@limiter.limit("60/minute")async def api_lookup_icd_code( request: Request, code: Annotated[Optional[str], Query(description="ICD-10 code to look up (optional if description is provided)")] = None, description: Annotated[Optional[str], Query(description="Medical condition description to search for (optional if code is provided)")] = None, max_results: Annotated[int, Query(description="Maximum number of results to return", ge=1, le=50)] = 10, session_id: Annotated[Optional[str], Header(description="Session ID for tracking usage")] = None): """ Look up ICD-10 codes by code or description - **code**: ICD-10 code to look up (optional if description is provided) - **description**: Medical condition description to search for (optional if code is provided) - **max_results**: Maximum number of results to return (1-50) - **session_id**: Optional session ID for tracking usage """ try: from src.main import lookup_icd_code logger.info("ICD code lookup request", code=code, description=description, max_results=max_results, session_id=session_id) return await lookup_icd_code(session_id, code, description, max_results) except Exception as e: logger.error("Error in ICD code lookup", error=str(e), code=code, description=description) return ErrorResponse(error_message=f"Error looking up ICD-10 code: {str(e)}")
@app.get("/api/usage_stats", summary="Get usage statistics for the current session", description="Get a summary of API usage for the current session", response_model=Union[SuccessResponse, ErrorResponse], tags=["Monitoring"])@limiter.limit("120/minute")async def api_usage_stats( request: Request, session_id: Annotated[Optional[str], Query(description="Session ID to get usage statistics for")] = None): """ Get usage statistics for the current session - **session_id**: Session ID to get usage statistics for (optional) Returns a summary of API usage for the specified session or all sessions if no session ID is provided """ try: from src.main import get_usage_stats logger.info("Usage stats request", session_id=session_id) return await get_usage_stats(session_id) except Exception as e: logger.error("Error in usage stats", error=str(e), session_id=session_id) return ErrorResponse(error_message=f"Error getting usage statistics: {str(e)}")
@app.get("/api/all_usage_stats", summary="Get overall usage statistics", description="Get a summary of API usage across all sessions", response_model=Union[SuccessResponse, ErrorResponse], tags=["Monitoring"])@limiter.limit("30/minute")async def api_all_usage_stats( request: Request, days: Annotated[int, Query(description="Number of days to include in the statistics", ge=1, le=365)] = 30): """ Get overall usage statistics - **days**: Number of days to include in the statistics (1-365, default: 30) Returns a summary of API usage across all sessions for the specified time period """ try: from src.main import get_all_usage_stats logger.info("All usage stats request", days=days) return await get_all_usage_stats(None, days=days) except Exception as e: logger.error("Error in all usage stats", error=str(e)) return ErrorResponse(error_message=f"Error getting all usage statistics: {str(e)}")
# Add the specific call-tool endpoint@app.post("/mcp/call-tool", summary="Call a specific tool by name", description="Generic endpoint to call any tool by name with arguments", response_model=Union[SuccessResponse, ErrorResponse], tags=["Tool Execution"])@limiter.limit("60/minute")async def call_tool( request: Request, tool_request: ToolRequest = Body(...),): """ Call a specific tool by name - **name**: Name of the tool to call - **arguments**: Arguments to pass to the tool - **session_id**: Optional session ID for tracking usage """ try: from src.main import fda_drug_lookup, pubmed_search, health_topics, clinical_trials_search, lookup_icd_code, get_usage_stats, get_all_usage_stats tool_name = tool_request.name arguments = tool_request.arguments session_id = tool_request.session_id logger.info("Tool call request", tool_name=tool_name, session_id=session_id) # Map tool names to their corresponding functions tool_mapping = { "fda_drug_lookup": lambda args: fda_drug_lookup(session_id, **args), "pubmed_search": lambda args: pubmed_search(session_id, **args), "health_topics": lambda args: health_topics(session_id, **args), "clinical_trials_search": lambda args: clinical_trials_search(session_id, **args), "lookup_icd_code": lambda args: lookup_icd_code(session_id, **args), "get_usage_stats": lambda _: get_usage_stats(session_id), "get_all_usage_stats": lambda args: get_all_usage_stats(session_id, **args) } if tool_name not in tool_mapping: logger.warning("Tool not found", tool_name=tool_name) return ErrorResponse( error_message=f"Tool '{tool_name}' not found", error_code="TOOL_NOT_FOUND" ) # Call the appropriate tool function result = await tool_mapping[tool_name](arguments) return result except Exception as e: logger.error("Error in tool call", error=str(e), tool_name=tool_request.name) return ErrorResponse( error_message=f"Error calling tool: {str(e)}", error_code="TOOL_EXECUTION_ERROR" )
# Health check endpoint@app.get("/health", summary="Health check endpoint", description="Check if the server is running properly", tags=["Monitoring"])@limiter.limit("300/minute")async def health_check(request: Request): """ Health check endpoint Returns the status and version of the server along with service health information """ logger.info("Health check request") # Check if cache service is available cache_status = "ok" try: from src.services.cache_service import CacheService cache = CacheService() await cache.init() # Just check if we can access the cache cache_stats = await cache.get_stats() await cache.close() if isinstance(cache_stats, dict) and "error" in cache_stats: cache_status = f"error: {cache_stats['error']}" except Exception as e: cache_status = f"error: {str(e)}" # Check if usage service is available usage_status = "ok" try: from src.services.usage_service import UsageService usage = UsageService() await usage.init() # Just check if we can access the usage stats usage_stats = await usage.get_usage_stats() await usage.close() if isinstance(usage_stats, dict) and "error" in usage_stats: usage_status = f"error: {usage_stats['error']}" except Exception as e: usage_status = f"error: {str(e)}" # Get current timestamp in ISO format from datetime import datetime, timezone timestamp = datetime.now(timezone.utc).isoformat() return { "status": "healthy", "version": "1.0.0", "timestamp": timestamp, "services": { "cache": cache_status, "usage": usage_status } }
# Redirect root to docs@app.get("/", summary="Redirect to API documentation", description="Redirects to the Swagger UI documentation", tags=["Documentation"])@limiter.limit("300/minute")async def redirect_to_docs(request: Request): """ Redirect to API documentation Redirects to the Swagger UI documentation """ from fastapi.responses import RedirectResponse logger.info("Root request, redirecting to docs") return RedirectResponse(url="/docs")
# Information about premium version@app.get("/premium-info", summary="Get information about the premium version", description="Get information about the premium version of the Healthcare MCP Server", response_model=SuccessResponse, tags=["Documentation"])@limiter.limit("120/minute")async def premium_info(request: Request): """ Get information about the premium version Returns information about the premium version of the Healthcare MCP Server including features, pricing, and contact information """ logger.info("Premium info request") return { "status": "success", "message": "This is the free version of Healthcare MCP Server.", "premium_url": "https://healthcaremcp.com", "features": [ "Unlimited API calls (500 requests per minute)", "Advanced healthcare data tools (SNOMED CT, RxNorm, LOINC)", "Custom integrations with EHR systems", "Priority support with 24/7 availability", "Advanced analytics and usage reporting", "Private deployment options" ], "pricing": { "basic": "$99/month", "professional": "$299/month", "enterprise": "Contact for pricing" }, "contact": "premium@healthcaremcp.com" }
# End of API endpoints
if __name__ == "__main__": import uvicorn import argparse parser = argparse.ArgumentParser(description='Healthcare MCP Server') parser.add_argument('--port', type=int, default=int(os.getenv("PORT", "8000")), help='Port to run the server on') parser.add_argument('--host', type=str, default="0.0.0.0", help='Host to run the server on') args = parser.parse_args() port = args.port logger.info("Starting server", port=port) uvicorn.run(app, host=args.host, port=port, log_level="info", access_log=True, workers=int(os.getenv("WORKERS", "1")))1# Services initialization123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299import jsonimport timeimport osimport sqlite3import loggingimport threadingfrom pathlib import Pathfrom typing import Any, Dict, Optional, Union
logger = logging.getLogger("healthcare-mcp")
class CacheService: """ Cache service with SQLite backend and connection pooling This service provides caching functionality with automatic expiration and connection pooling for better performance. """ # Class-level connection pool _connection_pools: Dict[str, sqlite3.Connection] = {} _connection_locks: Dict[str, threading.Lock] = {} def __init__(self, db_path: str = "cache.db", ttl: int = 3600): # Default TTL: 1 hour """ Initialize cache service with SQLite backend Args: db_path: Path to the SQLite database file ttl: Default time-to-live for cache entries in seconds """ self.db_path = os.getenv("CACHE_DB_PATH", db_path) self.default_ttl = ttl # Initialize connection lock for this database if self.db_path not in self._connection_locks: self._connection_locks[self.db_path] = threading.Lock() # Initialize the database self._init_db() # Schedule periodic cleanup of expired entries self._schedule_cleanup() async def init(self) -> None: """ Initialize the cache service asynchronously This method is called during application startup """ # Ensure database directory exists os.makedirs(os.path.dirname(os.path.abspath(self.db_path)), exist_ok=True) # Clear expired entries on startup self.clear_expired() logger.info(f"Cache service initialized with database at {self.db_path}") def _get_connection(self) -> sqlite3.Connection: """ Get a connection from the pool or create a new one Returns: SQLite connection """ # Create a lock for this database path if it doesn't exist if self.db_path not in self._connection_locks: self._connection_locks[self.db_path] = threading.RLock() with self._connection_locks[self.db_path]: if self.db_path not in self._connection_pools: logger.debug(f"Creating new database connection for {self.db_path}") conn = sqlite3.connect(self.db_path, check_same_thread=False) # Enable WAL mode for better concurrency conn.execute("PRAGMA journal_mode=WAL") # Enable foreign keys conn.execute("PRAGMA foreign_keys=ON") self._connection_pools[self.db_path] = conn return self._connection_pools[self.db_path] def _init_db(self) -> None: """Initialize the SQLite database if it doesn't exist""" conn = self._get_connection() cursor = conn.cursor() # Create cache table if it doesn't exist cursor.execute(''' CREATE TABLE IF NOT EXISTS cache ( key TEXT PRIMARY KEY, data TEXT NOT NULL, expires_at REAL NOT NULL, created_at REAL NOT NULL ) ''') # Create index on expires_at for faster cleanup cursor.execute(''' CREATE INDEX IF NOT EXISTS idx_expires_at ON cache(expires_at) ''') conn.commit() def get(self, key: str) -> Optional[Any]: """ Get value from cache if it exists and is not expired Args: key: Cache key Returns: Cached value or None if not found or expired """ conn = self._get_connection() cursor = conn.cursor() try: # Get cache entry cursor.execute("SELECT data, expires_at FROM cache WHERE key = ?", (key,)) result = cursor.fetchone() if not result: return None data, expires_at = result # Check if expired if expires_at < time.time(): # Delete expired entry asynchronously threading.Thread(target=self._delete_expired, args=(key,)).start() return None # Parse JSON data try: return json.loads(data) except json.JSONDecodeError: logger.error(f"Failed to decode JSON data for key: {key}") return None except sqlite3.Error as e: logger.error(f"Database error in get(): {str(e)}") return None def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool: """ Set value in cache with optional TTL Args: key: Cache key value: Value to cache ttl: Time-to-live in seconds (optional) Returns: True if successful, False otherwise """ ttl = ttl or self.default_ttl expires_at = time.time() + ttl created_at = time.time() conn = self._get_connection() cursor = conn.cursor() try: # Serialize value to JSON serialized_value = json.dumps(value) # Insert or replace cache entry cursor.execute( "INSERT OR REPLACE INTO cache (key, data, expires_at, created_at) VALUES (?, ?, ?, ?)", (key, serialized_value, expires_at, created_at) ) conn.commit() return True except (sqlite3.Error, json.JSONEncodeError) as e: logger.error(f"Error in set(): {str(e)}") return False def delete(self, key: str) -> bool: """ Delete value from cache Args: key: Cache key Returns: True if deleted, False otherwise """ conn = self._get_connection() cursor = conn.cursor() try: cursor.execute("DELETE FROM cache WHERE key = ?", (key,)) deleted = cursor.rowcount > 0 conn.commit() return deleted except sqlite3.Error as e: logger.error(f"Error in delete(): {str(e)}") return False def _delete_expired(self, key: str) -> None: """ Delete an expired cache entry Args: key: Cache key """ conn = self._get_connection() cursor = conn.cursor() try: cursor.execute("DELETE FROM cache WHERE key = ?", (key,)) conn.commit() except sqlite3.Error as e: logger.error(f"Error in _delete_expired(): {str(e)}") def clear_expired(self) -> int: """ Clear all expired cache entries Returns: Number of deleted entries """ conn = self._get_connection() cursor = conn.cursor() try: cursor.execute("DELETE FROM cache WHERE expires_at < ?", (time.time(),)) deleted = cursor.rowcount conn.commit() logger.info(f"Cleared {deleted} expired cache entries") return deleted except sqlite3.Error as e: logger.error(f"Error in clear_expired(): {str(e)}") return 0 def _schedule_cleanup(self) -> None: """Schedule periodic cleanup of expired entries""" # This would normally use a background task scheduler # For simplicity, we'll just log a message logger.info("Cache cleanup would be scheduled here in a production environment") def get_stats(self) -> Dict[str, Any]: """ Get cache statistics Returns: Dictionary with cache statistics """ conn = self._get_connection() cursor = conn.cursor() try: # Get total entries cursor.execute("SELECT COUNT(*) FROM cache") total_entries = cursor.fetchone()[0] # Get expired entries cursor.execute("SELECT COUNT(*) FROM cache WHERE expires_at < ?", (time.time(),)) expired_entries = cursor.fetchone()[0] # Get average TTL cursor.execute("SELECT AVG(expires_at - created_at) FROM cache") avg_ttl = cursor.fetchone()[0] or 0 return { "total_entries": total_entries, "expired_entries": expired_entries, "valid_entries": total_entries - expired_entries, "average_ttl_seconds": round(avg_ttl, 2) } except sqlite3.Error as e: logger.error(f"Error in get_stats(): {str(e)}") return { "error": str(e) } async def close(self) -> None: """ Close the cache service and clean up resources This method is called during application shutdown """ try: # Close database connection if it exists if self.db_path in self._connection_pools: with self._connection_locks[self.db_path]: conn = self._connection_pools[self.db_path] conn.close() del self._connection_pools[self.db_path] logger.info(f"Closed database connection for {self.db_path}") except Exception as e: logger.error(f"Error closing cache service: {str(e)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318import sqlite3import timeimport osimport loggingimport threadingfrom datetime import datetimefrom typing import Dict, Any, Optional, List, Union
logger = logging.getLogger("healthcare-mcp")
class UsageService: """ Service for tracking API usage with SQLite backend This service provides anonymous usage tracking functionality with connection pooling for better performance. """ # Class-level connection pool _connection_pools: Dict[str, sqlite3.Connection] = {} _connection_locks: Dict[str, threading.Lock] = {} def __init__(self, db_path: str = "usage.db"): """ Initialize usage tracking service with anonymous tracking only Args: db_path: Path to the SQLite database file """ self.db_path = os.getenv("USAGE_DB_PATH", db_path) # Initialize connection lock for this database if self.db_path not in self._connection_locks: self._connection_locks[self.db_path] = threading.Lock() # Initialize the database self._init_db() async def init(self) -> None: """ Initialize the usage service asynchronously This method is called during application startup """ # Ensure database directory exists os.makedirs(os.path.dirname(os.path.abspath(self.db_path)), exist_ok=True) logger.info(f"Usage service initialized with database at {self.db_path}") def _get_connection(self) -> sqlite3.Connection: """ Get a connection from the pool or create a new one Returns: SQLite connection """ with self._connection_locks[self.db_path]: if self.db_path not in self._connection_pools: logger.debug(f"Creating new database connection for {self.db_path}") conn = sqlite3.connect(self.db_path, check_same_thread=False) # Enable WAL mode for better concurrency conn.execute("PRAGMA journal_mode=WAL") # Enable foreign keys conn.execute("PRAGMA foreign_keys=ON") self._connection_pools[self.db_path] = conn return self._connection_pools[self.db_path] def _init_db(self) -> None: """Initialize the SQLite database if it doesn't exist""" conn = self._get_connection() cursor = conn.cursor() # Create usage table for anonymous session tracking only cursor.execute(''' CREATE TABLE IF NOT EXISTS usage ( id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool TEXT NOT NULL, timestamp REAL NOT NULL, api_calls INTEGER NOT NULL DEFAULT 1 ) ''') # Create indexes for faster queries cursor.execute(''' CREATE INDEX IF NOT EXISTS idx_session_timestamp ON usage(session_id, timestamp) ''') cursor.execute(''' CREATE INDEX IF NOT EXISTS idx_tool ON usage(tool) ''') conn.commit() def record_usage(self, session_id: str, tool: str, api_calls: int = 1) -> bool: """ Record API usage for a session anonymously Args: session_id: Anonymous session identifier tool: Name of the tool used api_calls: Number of API calls made Returns: True if successful, False otherwise """ if not session_id or not tool: logger.warning("Missing session_id or tool in record_usage") return False conn = self._get_connection() cursor = conn.cursor() try: cursor.execute( "INSERT INTO usage (session_id, tool, timestamp, api_calls) VALUES (?, ?, ?, ?)", (session_id, tool, time.time(), api_calls) ) conn.commit() return True except sqlite3.Error as e: logger.error(f"Error in record_usage(): {str(e)}") return False def get_monthly_usage(self, session_id: str, month: Optional[int] = None, year: Optional[int] = None) -> Dict[str, Any]: """ Get current month's usage for a session Args: session_id: Anonymous session identifier month: Month number (1-12) year: Year (e.g., 2023) Returns: Dictionary with usage statistics """ # Use current month/year if not specified current_date = datetime.now() if month is None: month = current_date.month if year is None: year = current_date.year # Validate month and year try: month = int(month) year = int(year) if month < 1 or month > 12: month = current_date.month if year < 2000 or year > 2100: # Reasonable range year = current_date.year except (ValueError, TypeError): month = current_date.month year = current_date.year # Calculate start and end timestamps for the month start_date = datetime(year, month, 1).timestamp() if month == 12: end_date = datetime(year + 1, 1, 1).timestamp() else: end_date = datetime(year, month + 1, 1).timestamp() conn = self._get_connection() cursor = conn.cursor() try: # Get total API calls for the month cursor.execute( "SELECT SUM(api_calls) FROM usage WHERE session_id = ? AND timestamp >= ? AND timestamp < ?", (session_id, start_date, end_date) ) total_calls = cursor.fetchone()[0] or 0 # Get tool-specific usage cursor.execute( "SELECT tool, SUM(api_calls) FROM usage WHERE session_id = ? AND timestamp >= ? AND timestamp < ? GROUP BY tool", (session_id, start_date, end_date) ) tool_usage = {tool: count for tool, count in cursor.fetchall()} # Get daily usage cursor.execute( """ SELECT strftime('%Y-%m-%d', datetime(timestamp, 'unixepoch')) as date, SUM(api_calls) as calls FROM usage WHERE session_id = ? AND timestamp >= ? AND timestamp < ? GROUP BY date ORDER BY date """, (session_id, start_date, end_date) ) daily_usage = {date: calls for date, calls in cursor.fetchall()} return { "session_id": session_id, "month": month, "year": year, "total_api_calls": total_calls, "tool_usage": tool_usage, "daily_usage": daily_usage } except sqlite3.Error as e: logger.error(f"Error in get_monthly_usage(): {str(e)}") return { "session_id": session_id, "month": month, "year": year, "total_api_calls": 0, "tool_usage": {}, "daily_usage": {}, "error": str(e) } def get_usage_stats(self) -> Dict[str, Any]: """ Get overall usage statistics Returns: Dictionary with overall usage statistics """ conn = self._get_connection() cursor = conn.cursor() try: # Get total API calls cursor.execute("SELECT SUM(api_calls) FROM usage") total_calls = cursor.fetchone()[0] or 0 # Get total unique sessions cursor.execute("SELECT COUNT(DISTINCT session_id) FROM usage") total_sessions = cursor.fetchone()[0] or 0 # Get tool-specific usage cursor.execute( "SELECT tool, SUM(api_calls) FROM usage GROUP BY tool ORDER BY SUM(api_calls) DESC" ) tool_usage = {tool: count for tool, count in cursor.fetchall()} # Get usage by month cursor.execute( """ SELECT strftime('%Y-%m', datetime(timestamp, 'unixepoch')) as month, SUM(api_calls) as calls FROM usage GROUP BY month ORDER BY month DESC LIMIT 12 """ ) monthly_usage = {month: calls for month, calls in cursor.fetchall()} return { "total_api_calls": total_calls, "total_unique_sessions": total_sessions, "tool_usage": tool_usage, "monthly_usage": monthly_usage } except sqlite3.Error as e: logger.error(f"Error in get_usage_stats(): {str(e)}") return { "error": str(e) } def cleanup_old_data(self, days: int = 365) -> int: """ Clean up usage data older than specified days Args: days: Number of days to keep Returns: Number of deleted records """ if days < 30: # Safety check days = 30 # Calculate cutoff timestamp cutoff_timestamp = time.time() - (days * 86400) # 86400 seconds in a day conn = self._get_connection() cursor = conn.cursor() try: cursor.execute("DELETE FROM usage WHERE timestamp < ?", (cutoff_timestamp,)) deleted = cursor.rowcount conn.commit() logger.info(f"Cleaned up {deleted} old usage records") return deleted except sqlite3.Error as e: logger.error(f"Error in cleanup_old_data(): {str(e)}") return 0 async def close(self) -> None: """ Close the usage service and clean up resources This method is called during application shutdown """ try: # Close database connection if it exists if self.db_path in self._connection_pools: with self._connection_locks[self.db_path]: conn = self._connection_pools[self.db_path] conn.close() del self._connection_pools[self.db_path] logger.info(f"Closed database connection for {self.db_path}") except Exception as e: logger.error(f"Error closing usage service: {str(e)}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# Import toolsimport osfrom src.tools.fda_tool import FDAToolfrom src.tools.pubmed_tool import PubMedTool
# Set up data directorydata_dir = os.environ.get('DATA_DIR', os.path.join(os.getcwd(), 'data'))os.makedirs(data_dir, exist_ok=True)cache_db_path = os.path.join(data_dir, 'healthcare_cache.db')
# Initialize toolsfda_tool = FDATool(cache_db_path=cache_db_path)pubmed_tool = PubMedTool(cache_db_path=cache_db_path)
# Define tool actions for registrationfda_drug_lookup = { "name": "fda_drug_lookup", "description": "Look up drug information from the FDA database", "parameters": [ { "name": "drug_name", "description": "Name of the drug to search for", "required": True, "type": "string" }, { "name": "search_type", "description": "Type of information to retrieve: 'label', 'adverse_events', or 'general'", "required": False, "type": "string", "default": "general" } ], "handler": fda_tool.lookup_drug}
pubmed_search = { "name": "pubmed_search", "description": "Search for medical literature in PubMed database", "parameters": [ { "name": "query", "description": "Search query for medical literature", "required": True, "type": "string" }, { "name": "max_results", "description": "Maximum number of results to return", "required": False, "type": "integer", "default": 5 }, { "name": "date_range", "description": "Limit to articles published within years (e.g. '5' for last 5 years)", "required": False, "type": "string", "default": "" } ], "handler": pubmed_tool.search_literature}
# List of all tools for registrationall_tools = [ fda_drug_lookup, pubmed_search].gitignoreAdded+1
README.mdDeleted-14
app.py β gradio_server.pyRenamed+3-1
requirements.txt+11-1
src/__pycache__/dependencies.cpython-310.pycAdded
src/__pycache__/gradio_server.cpython-310.pycAdded
src/__pycache__/main.cpython-310.pycAdded
src/__pycache__/server.cpython-310.pycAdded
src/dependencies.pyAdded+162
src/main.pyAdded+136
src/server.pyAdded+564
src/services/__init__.pyAdded+1
src/services/__pycache__/__init__.cpython-310.pycAdded
src/services/__pycache__/cache_service.cpython-310.pycAdded
src/services/__pycache__/usage_service.cpython-310.pycAdded
src/services/cache_service.pyAdded+299
src/services/usage_service.pyAdded+318
src/tools/__init__.pyAdded+69
src/tools/__pycache__/__init__.cpython-310.pycAdded
src/tools/__pycache__/base_tool.cpython-310.pycAdded
src/tools/__pycache__/clinical_trials_tool.cpython-310.pycAdded
src/tools/__pycache__/fda_tool.cpython-310.pycAdded
src/tools/__pycache__/healthfinder_tool.cpython-310.pycAdded
src/tools/__pycache__/medical_terminology_tool.cpython-310.pycAdded
src/tools/__pycache__/pubmed_tool.cpython-310.pycAdded
base_tool.py β src/tools/base_tool.pyRenamed
clinical_trials_tool.py β src/tools/clinical_trials_tool.pyRenamed
fda_tool.py β src/tools/fda_tool.pyRenamed
healthfinder_tool.py β src/tools/healthfinder_tool.pyRenamed
medical_terminology_tool.py β src/tools/medical_terminology_tool.pyRenamed
pubmed_tool.py β src/tools/pubmed_tool.pyRenamed