cyanheads

PubMed MCP Server Pubmed

Community cyanheads
Updated

A Model Context Protocol (MCP) server enabling AI agents to intelligently search, retrieve, and analyze biomedical literature from PubMed via NCBI E-utilities. Includes a research agent scaffold. STDIO & HTTP

PubMed MCP Server Pubmed

TypeScriptModel Context Protocol SDKMCP Spec VersionVersionLicenseStatusGitHub

Unlock the power of biomedical literature for your AI agents with the PubMed MCP Server!

This server acts as a bridge, connecting your AI to NCBI's PubMed and E-utilities through the Model Context Protocol (MCP). It empowers language models to seamlessly search, retrieve, and analyze biomedical articles and data. Built with TypeScript and adhering to the MCP 2025-03-26 specification, it's designed for robustness and includes production-grade utilities.

๐Ÿš€ Core Capabilities: PubMed Tools ๐Ÿ› ๏ธ

This server equips your AI with specialized tools to interact with PubMed:

Tool Name Description Key Features
search_pubmed_articles Searches PubMed for articles based on your query. (See Example) - Filter by max results, sort order, date range, publication types.- Uses NCBI ESearch for PMIDs.- Optionally fetches brief summaries (title, authors, source, dates) via ESummary.
fetch_pubmed_content Retrieves detailed information for PubMed articles. Can use a list of PMIDs or ESearch history (queryKey/webEnv) with pagination. (See Example) - Flexible detailLevel: abstract_plus (parsed details, optional MeSH/grant), full_xml (JSON representation of the PubMedArticle XML structure), medline_text (MEDLINE format), citation_data (minimal for citations).- Supports direct PMID list or queryKey/webEnv from ESearch history.- Supports retstart/retmax for pagination with history.- Uses NCBI EFetch.
get_pubmed_article_connections Finds related articles (cited by, similar, references) or formats citations for a PMID. (See Ex.1, Ex.2) - Uses NCBI ELink for relationships.- Uses NCBI EFetch for citation data (RIS, BibTeX, APA, MLA).- Filter by max related results.
pubmed_research_agent Generates a standardized JSON research plan outline from component details. (See Example) - Accepts granular inputs for all research phases.- Optionally embeds instructive prompts for agent execution.- Structures rough ideas into a formal, machine-readable plan for further processing.
generate_pubmed_chart Generates a chart image (SVG) from given input data. (See Bar, Line, Scatter) - Supports 'bar', 'line', and 'scatter' chart types.- Takes data values and field specifications for axes and encoding.- Constructs a Vega-Lite specification internally and renders it as an SVG.

โœจ Key Features Beyond Tools

Feature Category Description
๐Ÿ”Œ MCP Compliant Fully functional server supporting stdio and http (SSE) transports.
๐Ÿš€ Production-Ready Utils Includes robust logging, error handling, ID generation, rate limiting, request context tracking, and input sanitization.
๐Ÿ”’ Secure & Type-Safe Built with TypeScript & Zod for strong type checking and input validation. Manages NCBI API keys, implements rate limiting, and features JWT-based auth middleware for HTTP.
โš™๏ธ Advanced Error Handling Consistent error categorization, detailed logging, and centralized handling, including specific error types for NCBI interactions.
๐Ÿ“š Well-Documented Comprehensive JSDoc comments, API references, and project specifications.
๐Ÿค– Agent-Friendly Includes a .clinerules developer cheatsheet tailored for LLM coding agents using this server.
๐Ÿ› ๏ธ Developer Utilities Scripts for cleaning builds, setting executable permissions, generating directory trees, and fetching OpenAPI specifications.

๐Ÿš€ Quick Start

Get the PubMed MCP server running in minutes:

  1. Clone the repository:

    git clone https://github.com/cyanheads/pubmed-mcp-server.git
    cd pubmed-mcp-server
    
  2. Install dependencies:

    npm install
    
  3. Configure Environment Variables (.env file):Create a .env file in the project root. Key variables:

    # REQUIRED FOR HTTP TRANSPORT
    MCP_AUTH_SECRET_KEY=generate_a_strong_random_32_plus_char_secret_key
    
    # RECOMMENDED FOR NCBI E-UTILITIES (for higher rate limits)
    # NCBI_API_KEY=your_ncbi_api_key_here
    # [email protected] # Recommended if using an API key
    # NCBI_TOOL_IDENTIFIER=@cyanheads/pubmed-mcp-server/1.0.13 # Optional: Tool identifier for NCBI (defaults to current version)
    

    For all options, see the Configuration section below or the Developer Cheatsheet (.clinerules).

    New example files for each tool are available in the examples/ directory (e.g., examples/search_pubmed_articles_example.md, examples/generate_pubmed_chart_example_bar.svg).

  4. Build the project:

    npm run build
    # Or use 'npm run rebuild' for a clean install (deletes node_modules, logs, dist)
    
  5. Format the code (Optional but Recommended):

    npm run format
    
  6. Run the Server:

    • Via Stdio (Default): Many MCP host applications will run this automatically using stdio. To run manually for testing:
      npm start
      # or 'npm run start:stdio'
      
    • Via HTTP (SSE): (Ensure MCP_TRANSPORT_TYPE=http and MCP_AUTH_SECRET_KEY are set in your .env)
      npm run start:http
      
      This starts an HTTP server (default: http://127.0.0.1:3010) using Server-Sent Events.

โš™๏ธ Configuration

Server Configuration (Environment Variables)

Configure the PubMed MCP server's behavior using environment variables (typically in a .env file).

Variable Description Default
MCP_TRANSPORT_TYPE Server transport: stdio or http. stdio
MCP_HTTP_PORT Port for the HTTP server (if MCP_TRANSPORT_TYPE=http). 3010
MCP_HTTP_HOST Host address for the HTTP server (if MCP_TRANSPORT_TYPE=http). 127.0.0.1
MCP_ALLOWED_ORIGINS Comma-separated allowed origins for CORS (if MCP_TRANSPORT_TYPE=http). (none)
MCP_LOG_LEVEL Server logging level (debug, info, warning, error, etc.). debug
LOGS_DIR Directory for log files. logs/ (in project root)
NODE_ENV Runtime environment (development, production). development
MCP_AUTH_SECRET_KEY Required for HTTP transport. Secret key (min 32 chars) for signing/verifying auth tokens (JWT). (none - MUST be set in production)
NCBI_API_KEY Optional, but highly recommended. Your NCBI API Key for higher rate limits (10/sec vs 3/sec). (none)
NCBI_ADMIN_EMAIL Optional, but recommended if using an API key. Your email for NCBI contact. (none)
NCBI_TOOL_IDENTIFIER Optional. Tool identifier sent to NCBI. @cyanheads/pubmed-mcp-server/<version>
NCBI_REQUEST_DELAY_MS Milliseconds to wait between NCBI requests. Dynamically set (e.g., 100ms with API key, 334ms without). (see src/config/index.ts)
NCBI_MAX_RETRIES Maximum number of retries for failed NCBI requests. 3

Note on HTTP Port Retries: If the MCP_HTTP_PORT is busy, the server automatically tries the next port (up to 15 times).

Security Note for HTTP Transport: When using MCP_TRANSPORT_TYPE=http, authentication is mandatory as per the MCP specification. This server includes JWT-based authentication middleware. You MUST set a strong, unique MCP_AUTH_SECRET_KEY in your production environment.

For a comprehensive list of all available environment variables, their descriptions, and default values, please review the configuration loader at src/config/index.ts.

๐Ÿ—๏ธ Project Structure Overview

The src/ directory contains the core logic:

  • config/: Environment variable loading and package information.
  • mcp-server/: The heart of the PubMed MCP server.
    • server.ts: Initializes the server instance and registers all tools and resources.
    • resources/: Implementations for MCP resources (e.g., server status, PubMed statistics).
    • tools/: Implementations for MCP tools (like searchPubMedArticles, fetchPubMedContent, getPubMedArticleConnections).
    • transports/: Handles stdio and http (SSE) communication, including authentication for HTTP.
  • services/: Integrations with external services.
    • NCBI/ncbiService.ts: Manages all interactions with NCBI E-utilities, including API calls, rate limiting, and response parsing.
    • llm-providers/: (Optional) For integrating LLM capabilities directly within the server.
  • types-global/: Shared TypeScript definitions, especially for errors and MCP types.
  • utils/: A comprehensive suite of reusable utilities for logging, error handling, security, parsing, metrics, and more.

For a detailed file tree, run: npm run tree or see Directory Tree.

๐Ÿงฉ Extending with More PubMed Capabilities

Adding new tools or resources is straightforward:

  1. Directory Setup: Create a new directory under src/mcp-server/tools/yourNewTool/ or src/mcp-server/resources/yourNewResource/.
  2. Implement Core Logic (logic.ts):
    • Define Zod schemas for input validation.
    • Write the function that interacts with src/services/NCBI/ncbiService.ts (e.g., ncbiService.eLink(...)).
    • Parse the NCBI response and format it according to MCP specifications (CallToolResult or ReadResourceResult).
  3. Register the Capability (registration.ts):
    • For tools: server.tool(name, description, zodSchemaShape, handlerFunction)
    • For resources: server.resource(registrationName, template, metadata, handlerFunction)
    • Always wrap your logic in ErrorHandler.tryCatch for robust error management.
  4. Export and Integrate: Export the registration function from your new directory's index.ts and call it within src/mcp-server/server.ts.

๐ŸŒ Learn More

๐Ÿ“œ License

This project is licensed under the Apache License 2.0. See the LICENSE file for details.

Empowering AI with PubMed | Built on the Model Context Protocol

MCP Server ยท Populars

MCP Server ยท New