biomed-mcp
# biomed-mcp
**An MCP server that gives LLM agents safe, typed, citable tools over public biomedical data: PubMed, ClinicalTrials.gov, UniProt and openFDA.**
[](https://github.com/tuigoku1212/biomed-mcp/actions/workflows/ci.yml)
[](https://www.python.org/)
[](LICENSE)
[](https://modelcontextprotocol.io)
> **Not medical advice.** biomed-mcp is a research and engineering tool. Its outputs are excerpts of public databases, which can be incomplete or out of date, and must not be used for diagnosis, treatment or other clinical decisions. See the [disclaimer](#disclaimer).
## Why
LLM agents are increasingly asked biomedical questions: what a trial measures, what a protein does, what a drug label warns about, what the literature says. Answered from model memory alone, those answers can be stale, unverifiable or simply invented. Agents need **grounded** data with **citations** a human can check.
biomed-mcp exposes a small set of read-only tools over authoritative public sources through the [Model Context Protocol](https://modelcontextprotocol.io), so any MCP client (Claude Desktop, Claude Code, IDE agents, custom agents) can:
- **search and read** the primary record instead of guessing;
- get **compact, structured** results (typed JSON with an output schema) that fit in a context window;
- **cite** every claim, because every record carries a canonical URL;
- **recover from mistakes**, because bad input and upstream failures come back as plain-language tool errors rather than crashes.
## Tools
| Tool | Source | Returns |
| --- | --- | --- |
| `search_pubmed(query, max_results, since_year, sort)` | PubMed (NCBI E-utilities) | PMID, title, first authors, journal, date, DOI/PMCID, PubMed URL; total hit count and query translation |
| `get_pubmed_abstract(pmid)` | PubMed | Abstract (structured sections kept), authors, journal, DOI, MeSH terms, keywords, PubMed + PMC links |
| `search_clinical_trials(condition, intervention, status, max_results, term)` | ClinicalTrials.gov API v2 | NCT ID, title, status, phases, conditions, interventions, sponsor, enrollment, key dates, registry URL |
| `get_clinical_trial(nct_id)` | ClinicalTrials.gov API v2 | Summary, design, eligibility criteria, primary/secondary outcomes, collaborators, sites and countries (no contact details) |
| `search_proteins(query, organism, reviewed_only, max_results)` | UniProtKB REST | Accession, entry name, protein and gene names, organism, length, UniProt URL |
| `get_protein(accession, include_sequence, max_sequence_length)` | UniProtKB REST | Names and synonyms, gene, organism, mass, curated function (with PubMed citations), sequence (optionally truncated), FASTA URL |
| `get_drug_label(drug_name, max_section_chars)` | openFDA drug labels | Boxed warning, indications, dosage, contraindications, warnings; manufacturer, pharmacologic class, label date, DailyMed URL |
All tools are annotated `readOnlyHint: true` and publish JSON Schemas for both inputs (with ranges, enums and descriptions) and outputs.
## Quickstart
You need [uv](https://docs.astral.sh/uv/getting-started/installation/). Nothing else: uv fetches a suitable Python (3.11+) and the dependencies.
**Run straight from GitHub** (no clone):
```bash
uvx --from git+https://github.com/tuigoku1212/biomed-mcp biomed-mcp
```
The server speaks MCP over stdio, so on its own it simply waits for a client. Normally your MCP client launches it for you, as configured below.
**From a local clone:**
```bash
git clone https://github.com/tuigoku1212/biomed-mcp.git
cd biomed-mcp
uv sync # create .venv and install dependencies
uv run biomed-mcp # start the stdio server
uv run python examples/direct_calls.py # call the tools directly, no MCP client needed
uv run pytest # offline test suite
```
To poke at the tools interactively, the [MCP Inspector](https://github.com/modelcontextprotocol/inspector) works well: `npx @modelcontextprotocol/inspector uv run biomed-mcp`.
### Claude Desktop
Add the server to `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`, Windows: `%APPDATA%\Claude\`) and restart Claude Desktop:
```json
{
"mcpServers": {
"biomed": {
"command": "uvx",
"args": ["--from", "git+https://github.com/tuigoku1212/biomed-mcp", "biomed-mcp"],
"env": {
"NCBI_EMAIL": "you@example.org"
}
}
}
}
```
If Claude Desktop cannot find `uvx`, use its absolute path (`which uvx`). To run a local clone instead, use `"command": "uv"` with `"args": ["--directory", "/path/to/biomed-mcp", "run", "biomed-mcp"]`.
### Claude Code
```bash
claude mcp add biomed -- uvx --from git+https://github.com/tuigoku1212/biomed-mcp biomed-mcp
```
Pass environment variables with `-e`, for example `claude mcp add biomed -e NCBI_EMAIL=you@example.org -- uvx --from git+https://github.com/tuigoku1212/biomed-mcp biomed-mcp`.
### Configuration
All settings are optional environment variables.
| Variable | Effect |
| --- | --- |
| `NCBI_EMAIL` | Sent to NCBI with every E-utilities request, as [NCBI asks](https://www.ncbi.nlm.nih.gov/books/NBK25497/). Strongly recommended. |
| `NCBI_API_KEY` | Raises the NCBI rate limit from 3 to 10 requests/second (free with an NCBI account; see [API keys](https://www.ncbi.nlm.nih.gov/books/NBK25497/)). |
| `OPENFDA_API_KEY` | Raises openFDA's anonymous daily quota ([get a key](https://open.fda.gov/apis/authentication/)). |
ClinicalTrials.gov and UniProt need no credentials.
## Example
**An agent conversation** (illustrative: the flow is real, but the IDs and numbers below are placeholders, not actual records):
> **User:** What does the recent literature say about cytokine release syndrome with BCMA-directed CAR-T, and are any trials recruiting?
>
> **Agent** calls `search_pubmed(query="BCMA CAR-T cytokine release syndrome", since_year=2022, sort="date", max_results=5)`
> and receives five summaries, each with a PMID, journal, date and `https://pubmed.ncbi.nlm.nih.gov/<PMID>/` URL.
>
> **Agent** calls `get_pubmed_abstract(pmid="<PMID>")` for the two most relevant hits
> and reads the BACKGROUND / METHODS / RESULTS / CONCLUSIONS sections before summarising.
>
> **Agent** calls `search_clinical_trials(condition="multiple myeloma", intervention="BCMA CAR-T", status=["RECRUITING", "NOT_YET_RECRUITING"])`
> and receives `total_count: <N>` plus the first studies, each with phase, sponsor and `https://clinicaltrials.gov/study/<NCT ID>`.
>
> **Agent** answers with a short synthesis in which every statement carries a numbered citation, followed by the sources:
> `[1] https://pubmed.ncbi.nlm.nih.gov/<PMID>/` · `[2] …` · `[3] https://clinicaltrials.gov/study/<NCT ID>`
**A real tool result**, from `get_protein(accession="P01308", max_sequence_length=24)` (function text shortened here):
```json
{
"accession": "P01308",
"entry_name": "INS_HUMAN",
"reviewed": true,
"protein_name": "Insulin",
"gene": "INS",
"organism": "Homo sapiens",
"taxon_id": 9606,
"length": 110,
"url": "https://www.uniprot.org/uniprotkb/P01308/entry",
"source": "UniProt",
"alternative_names": [],
"gene_synonyms": [],
"mass_da": 11981,
"function": "Hormone secreted by pancreatic islet beta cells, that is the principal anabolic regulator of glucose, lipid, and protein metabolism … (PubMed:32291281) …",
"sequence": "MALWMRLLPLLALLALWGPDPAAA",
"sequence_truncated": true,
"fasta_url": "https://rest.uniprot.org/uniprotkb/P01308.fasta"
}
```
## Architecture
```mermaid
flowchart LR
client["MCP client<br/>Claude Desktop · Claude Code · agents"] -- "JSON-RPC over stdio" --> server["server.py<br/>FastMCP · tool registry · error guard"]
server --> pubmed["pubmed.py"]
server --> trials["clinicaltrials.py"]
server --> uniprot["uniprot.py"]
server --> openfda["openfda.py"]
pubmed -. "≤ 3 req/s (10 with key)" .-> limiter["ratelimit.py"]
pubmed & trials & uniprot & openfda --> http["_http.py<br/>timeouts · retries · error mapping"]
http --> apis[("NCBI E-utilities · ClinicalTrials.gov v2<br/>UniProt REST · openFDA")]
```
```text
src/biomed_mcp/
├── server.py # thin: registers the tool functions with FastMCP, runs stdio
├── pubmed.py # esearch + esummary, efetch (XML) for abstracts
├── clinicaltrials.py # /api/v2/studies search and single-study lookup
├── uniprot.py # /uniprotkb/search and /uniprotkb/{accession}
├── openfda.py # /drug/label.json lookup and best-label ranking
├── _http.py # shared client factory, retries, HTTP status → error mapping
├── ratelimit.py # asyncio rate limiter used for NCBI
├── _text.py # whitespace cleanup and truncation helpers
└── errors.py # BiomedError → InvalidInputError / NotFoundError / UpstreamError
```
Each data source is one self-contained module of plain async functions. A function's signature (with `Annotated` pydantic constraints) becomes the tool's input schema, its docstring becomes the tool description, and its pydantic return model becomes the output schema. `server.py` only registers them, so the same functions are usable directly from Python (see [`examples/direct_calls.py`](examples/direct_calls.py)).
## Design notes
- **Rate limiting.** NCBI allows 3 requests/second without an API key and 10 with one. A process-wide limiter hands out evenly spaced time slots (no locks, safe under concurrent tool calls), and the rate switches automatically when `NCBI_API_KEY` is set. Every request identifies the client with `tool=biomed-mcp` and, if configured, `email`.
- **Retries and timeouts.** Each source has its own timeout (15 to 20 s, 5 s to connect). HTTP 429 and 5xx responses are retried at most twice with exponential backoff, honouring `Retry-After`. Everything else fails fast.
- **Compact output.** Searches return summaries; detail tools return one record. Long text (abstracts, eligibility criteria, label sections, function annotations) is truncated at a word boundary with an explicit `… [truncated, N more characters]` marker, and lists are capped (authors, outcomes, sites). Where the API supports it, only the needed fields are requested (UniProt `fields`, ClinicalTrials.gov `fields`), which also keeps responses small.
- **Citations.** Every record includes a canonical `url` (PubMed, ClinicalTrials.gov, UniProt, DailyMed); searches add a `search_url` that reproduces the query on the source website, and PubMed records include DOI and a PubMed Central link when free full text exists.
- **Error handling.** Expected failures raise typed `BiomedError`s whose messages are written for the model: which source failed, why, and what to try next (for example, *"'EGFR' is not a UniProtKB accession … Use search_proteins to look up a protein or gene name"*). MCP clients receive them as `isError: true` tool results. Unexpected exceptions are logged and returned as a clear internal-error message instead of a stack trace.
- **Input validation.** The same `Annotated` constraints are enforced whether a tool is called through MCP (FastMCP's argument model) or directly from Python (`pydantic.validate_call`), and they are published in the input schema so the model can see them up front. Identifiers are checked against their official formats (PMID, NCT ID, UniProt accession) before any request is made, and drug names are allow-listed so they cannot inject openFDA query syntax.
- **Safety and privacy.** All tools are read-only. XML is parsed with `defusedxml`. Trial records are returned without investigator or site contact details. Error messages never echo request URLs, and the HTTP client's URL logging is silenced, so API keys sent as query parameters do not end up in transcripts or client logs.
- **Simplicity over cleverness.** Each tool call uses a short-lived HTTP client: no shared state to manage across event loops, and the cost is negligible at agent call rates. Caching and connection pooling are on the roadmap.
## Development
```bash
uv sync # install runtime + dev dependencies
uv run ruff check . # lint
uv run ruff format --check . # formatting
uv run pytest # offline tests (HTTP mocked with respx)
uv run pytest --live -m live # optional smoke test against the real APIs
```
The test suite runs fully offline. Fixtures in `tests/fixtures/` are trimmed real responses from ClinicalTrials.gov, UniProt and openFDA (contact details removed); the PubMed fixtures reproduce the documented E-utilities formats with synthetic records. CI runs lint, format and tests on Python 3.11, 3.12 and 3.13.
## Roadmap
- [ ] Europe PMC: full-text search and retrieval for open-access articles
- [ ] ChEMBL: compounds, bioactivity, mechanisms of action and targets
- [ ] RCSB PDB: structure search and entry metadata
- [ ] Response caching (TTL, optional on-disk) and pooled connections
- [ ] Streamable HTTP transport for remote / multi-user deployment
- [ ] openFDA adverse events (FAERS) and recalls
- [ ] Pagination for search tools
- [ ] Migrate to MCP Python SDK v2 (`MCPServer`)
- [ ] Publish to PyPI
## Contributing
Issues and pull requests are welcome. To add a data source:
1. Create one module under `src/biomed_mcp/` with async functions whose `Annotated` signatures and docstrings read well as tool schemas and descriptions, and pydantic return models that include a `url` for citation.
2. Route HTTP through `_http.get` so timeouts, retries and error messages stay consistent.
3. Add trimmed fixtures captured from real responses to `tests/fixtures/`, with offline tests for parsing, validation and error paths.
4. Register the functions in `server.TOOLS` and document them in the tools table above.
Please run `uv run ruff check . && uv run ruff format --check . && uv run pytest` before opening a pull request, and add an entry to [`CHANGELOG.md`](CHANGELOG.md).
## License
[MIT](LICENSE) © 2026 tuigoku1212
## Disclaimer
biomed-mcp is provided for **research and educational use only**. It is **not a medical device and does not provide medical advice**. Tool outputs are automated, possibly truncated excerpts of third-party databases that may be incomplete, outdated or wrong, and they can be misread by both people and language models. Always verify information against the primary source and consult qualified healthcare professionals for medical decisions.
This project is not affiliated with or endorsed by the U.S. National Library of Medicine, NCBI, ClinicalTrials.gov, the UniProt Consortium or the U.S. Food and Drug Administration. Use of each data source is subject to its own terms; see [NCBI](https://www.ncbi.nlm.nih.gov/home/about/policies/), [ClinicalTrials.gov](https://clinicaltrials.gov/about-site/terms-conditions), [UniProt](https://www.uniprot.org/help/license) and [openFDA](https://open.fda.gov/terms/).
TDQS
Scored across 7 tools
Each tool targets a distinct resource and action, with clear search/get pairings across proteins, PubMed, and clinical trials plus a standalone drug label lookup. Descriptions explicitly direct agents from search tools to the corresponding get tool, removing overlap.
All seven tools follow a consistent snake_case verb_noun pattern: search_pubmed, get_pubmed_abstract, search_proteins, get_protein, search_clinical_trials, get_clinical_trial, get_drug_label. The convention is predictable throughout.
Seven tools is well-scoped for a biomedical data server spanning literature, proteins, trials, and drug labels. Each tool has a clear role and none appear redundant.
The search/get pattern provides solid lifecycle coverage for PubMed, UniProt, and ClinicalTrials.gov, with no obvious dead ends for those workflows. The main gap is drug-related coverage: only get_drug_label exists, with no drug search, adverse-event, or interaction lookup tools.