Metadata-Version: 2.5
Name: biogrounder
Version: 0.2.0
Summary: Ever wondered what disease, function, gene, tissue, ontology term or medical code a description refers to? Ask this MCP server and REST API: it reads the text, grounds every concept to verified IDs and codes, connects them through the literature, and learns as it is used.
Project-URL: Homepage, https://github.com/djportUCD/biogrounder
Project-URL: Issues, https://github.com/djportUCD/biogrounder/issues
License-File: LICENSE
Keywords: biocuration,disease-ontology,gene-ontology,grounding,llm,mcp,mondo,ontology
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.15
Requires-Dist: anthropic>=2.17
Requires-Dist: fastapi>=0.165
Requires-Dist: httpx>=0.29
Requires-Dist: keyring>=25.7
Requires-Dist: mcp>=2.3
Requires-Dist: pydantic>=2.14
Requires-Dist: pyyaml>=6.0.4
Requires-Dist: uvicorn>=0.55
Description-Content-Type: text/markdown

# BioGrounder

<!-- mcp-name: io.github.djportUCD/biogrounder -->

**Ever get tired of reading a description and wondering which disease, function, gene, tissue,
ontology term, medical code or ID it refers to?**

Here's some help. Give `biogrounder` the text (an abstract, an assay
protocol, a mouse model, a gene summary, a clinical note), or give it to your AI, and ask:

> *"What does this refer to?"*

You get back the answer grouped by category. Every item has an ID that was checked against the
real source:

| You read… | It tells you… |
|---|---|
| "boys lose muscle strength in early childhood" | **disease** MONDO:0010679 Duchenne muscular dystrophy · **phenotype** HP:0001324 Muscle weakness |
| "Nrf2", "DMD", "the leptin gene" | **gene** NCBIGene:4780 NFE2L2 (human), with HGNC, OMIM, Ensembl and UniProt IDs |
| "chloride transport across the apical membrane" | **function / process** GO terms · **cell location** GO cellular components |
| "the Keap1-Nrf2-ARE pathway" | **pathway** Reactome:R-HSA-9755511 KEAP1-NFE2L2 pathway |
| "HaCaT keratinocytes", "bovine cells" | **cell type** CL · **organism** NCBITaxon:9913 *Bos taurus* |
| "cinnamaldehyde", "CAS 60-18-4" | **chemical** CHEBI:16731 (E)-cinnamaldehyde · CHEBI:17895 L-tyrosine |
| "a cell viability assay", "genotoxicity testing" | **assay / method** BAO:0003009 · BAO:0002167 |
| "enzyme replacement therapy", "homozygous", "22q11.2" | **medical action** MAXO:0000933 · **genotype** GENO:0000136 · **chromosome region** CHR:9606-chr22q11.2 |
| "OMIM 219700", "ICD-10 E84.0", "ORPHA:586", "rs113993960" | **IDs already in the text, resolved**: cystic fibrosis (MONDO:0009061); rs113993960 sits in CFTR |
| any disease it finds | its **MONDO ID and medical codes**: MONDO, OMIM, ICD-10-CM, ICD-10 (WHO), ICD-11, ICD-9, MeSH, UMLS, SNOMED CT, Orphanet, NCI Thesaurus, MedDRA, MedGen, GARD, NANDO, Disease Ontology; the genes that cause it (Monarch); curated treatments (MAxO annotations); and its mechanism page (DisMech) |
| any gene it finds | NCBI Gene, HGNC / MGI, OMIM, Ensembl, UniProt; and the **MONDO diseases it causes** (Monarch) |
| the whole set | **how they connect in the literature**: "cinnamaldehyde *cause* allergic contact dermatitis (12 papers)", "cinnamaldehyde *positive_correlate* NFE2L2 (34 papers)", with example PubMed IDs |

It also works out **what the thing does, how and why**: its function, mechanism and purpose, and
the subject → predicate → object relations between the concepts. It **never makes up an ID**. Every ID
comes from a live search and is verified before you see it.

It runs as an **MCP server** (Claude Desktop, Claude Code or any MCP client; also a one-line
[Claude Code plugin](#use-it-from-claude-code)) and as a **REST API**, which serves MCP at `/mcp` too.

**It checks its own answers, both ways.** Forward, every ID is verified at its source. Backward,
each chosen term's definition is read against the text, and the terms are checked against each
other with curated knowledge (do these phenotypes belong to this disease? is this gene annotated to
this function?). See [Checking an answer](#checking-an-answer-both-ways).

**The "plus":** AIs don't only *use* it, they *teach* it. Every confident mapping an AI makes (and
anything it adds on purpose with `learn_term`) goes into a **learning dictionary**, a plain YAML
file, so the same phrase is answered better next time. People stay in charge: a curator's
*confirmed* or *rejected* verdict always wins over anything learned automatically.

> **Licence:** free for **academic research and teaching only**. Commercial use needs separate
> permission. See [Licence](#licence).

---

## The question, and the ways it answers it

"Which identifier does this description refer to?" comes in several forms. Each form has its own tool:

| You want to know | MCP tool | REST | CLI |
|---|---|---|---|
| **Everything this text refers to**, grouped by category (start here) | `what_does_this_refer_to` | `POST /refer` | `refer "…"` |
| What the **IDs already written in the text** mean (OMIM, ICD-10, Orphanet, MeSH, UMLS CUI, rsID, NCBI Gene, HGNC, Ensembl, UniProt, CAS, Reactome, ontology CURIEs, PMIDs) | `identify_ids` | `POST /identify` | `identify "…"` |
| The **medical codes** for a disease or gene it found | included in every annotation (`codes`) | same | same |
| How the findings are **connected in published papers** | `find_literature_connections` | `POST /connections` | `connect ID ID … / --run RUN` |
| **What one term leads to** in the literature, or what leads to it (what treats this disease? which genes does this chemical affect?) | `find_literature_neighbours` | `POST /connections/neighbours` | `neighbours ID --kind chemical --relation treat` |
| What **outside text annotators** see in the text (PubTator3, BioPortal) | `scan_text_with_sources` → `get_scan_result` | `POST /sources/scan` → `GET /sources/scan/{id}` | – |
| The best ID for **one concept you already have** | `ground_terms` | `POST /ground` | `ground "…" --kind …` |
| Details of **one ID** | `lookup_term` | `GET /terms/{curie}` | `lookup ID` |
| The **equivalent** ID in another ontology (MONDO ⇄ DOID, …) | `crosswalk_term` | `GET /crosswalk/{curie}` | – |
| What a **lab's jargon or abbreviation** means (as learned before) | `lookup_dictionary` | `GET /dictionary/lookup` | – |

### Example

Summarised here; the CLI prints the same results as JSON.

```text
$ biogrounder identify "Cystic fibrosis (OMIM 219700; ICD-10 E84.0; ORPHA:586) from
  CFTR rs113993960; HGNC:1884; ENSG00000001626; tyrosine CAS 60-18-4; MeSH D003550; PMID 31740819."

OMIM 219700     -> MONDO:0009061  cystic fibrosis
ICD-10 E84.0    -> MONDO:0009061  cystic fibrosis   (matched the parent code E84)
ORPHA:586       -> MONDO:0009061  cystic fibrosis
rs113993960     -> dbSNP:rs113993960  rs113993960 (CFTR, CFTR-AS1)
HGNC:1884       -> NCBIGene:1080  CFTR (human): CF transmembrane conductance regulator
ENSG00000001626 -> NCBIGene:1080  CFTR (human)
60-18-4         -> CHEBI:17895    L-tyrosine          (CAS check digit verified)
MeSH D003550    -> MONDO:0009061  cystic fibrosis
PMID 31740819   -> recognised; not something this service resolves

$ biogrounder connect NCBIGene:4780 MONDO:0006525 CHEBI:16731

(E)-cinnamaldehyde | positive_correlate | NFE2L2            34 papers
(E)-cinnamaldehyde | cause              | allergic contact dermatitis   12 papers
(E)-cinnamaldehyde | associate          | NFE2L2             8 papers
allergic contact dermatitis | associate | NFE2L2             5 papers
```

The full answer from `what_does_this_refer_to` (or `analyze_text`) looks like this:

```text
"Lep ob/ob mice make no functional leptin ... overeat, become severely obese ..."
        │
        ▼
 summary    A mouse strain lacking leptin that models monogenic obesity
 function   Leptin reports fat stores to the brain and suppresses appetite
 mechanism  Adipocytes secrete leptin ∝ fat mass; it acts on hypothalamic neurons ...
 why        Matches food intake to energy stores ...
 relations  Lep loss ─causes→ polyphagia, polyphagia ─leads to→ obesity, ...
 answer
   genes      leptin gene    → NCBIGene:16846  Lep (mouse)   codes: MGI 104663
   phenotypes overeat        → MP:0001433      polyphagia
              severely obese → MP:0001261      obese
   diseases   (implied)      → MONDO:0013991   obesity due to congenital leptin deficiency  codes: OMIM, Orphanet, …
   functions  satiety signal → GO:0032099      negative regulation of appetite
 literature   Lep ─associate→ obesity  (n papers, example PMIDs …)
```

## Why this exists

Turning a description into "this means DOID:x / MONDO:y / GO:z / OMIM n" usually means asking an
AI and hoping the IDs are real, or searching five websites by hand. Existing tools each do part of
the job:

| Tool | What it does | What it doesn't do |
|---|---|---|
| [OLS](https://www.ebi.ac.uk/ols4), [ols-mcp-server](https://github.com/seandavi/ols-mcp-server), [OntoMCP](https://github.com/jeanlouishoneine-tech/OntoMCP), [mondo-link](https://github.com/berntpopp/mondo-link) | Look up a **term you already have** | Read a description and work out function, mechanism or implied concepts |
| [OntoGPT / SPIRES](https://github.com/monarch-initiative/ontogpt) | LLM extraction grounded to ontologies | Isn't an MCP server; doesn't learn from curator corrections |
| [CurateGPT](https://github.com/monarch-initiative/curategpt) | AI-assisted curation workbench | Isn't a "what does this refer to?" service |
| [PubTator3](https://www.ncbi.nlm.nih.gov/research/pubtator3/), [BioPortal Annotator](https://bioportal.bioontology.org/annotator) | Tag entities in text | Don't reason about meaning, implied concepts or medical codes |

biogrounder joins these together. It reasons about the text, grounds
against live ontologies and biomedical APIs, never invents IDs, adds the medical codes, looks up
the literature, and has a second route for teaching it.

## How it works

```
 text ──► 0. SPOT IDs            identifiers already in the text (OMIM, ICD, rsID, CAS, …) resolved
            │                    fast outside annotators run; PubTator3 starts in the background
            ▼
          1. READ (brain)        what / function / mechanism / why / relations,
            │                    concepts named + implied, with good search queries
            │   ◄── similar worked examples, guidelines, learning-dictionary entries, annotator hints
            ▼
          2. RETRIEVE            live search of EBI OLS (+ MyGene.info for genes)
            │                    + the outside helpers for that kind of concept (sources.yaml);
            │                    IDs several sources agree on rank higher;
            │                    dictionary: confirmed ≫ learned boosted, rejected demoted
            ▼
          3. CHOOSE (brain)      one ID per concept, *only from the retrieved candidates*
            ▼
          4. VERIFY + CODE       every ID re-checked at its source; invented or obsolete IDs dropped;
            │                    MONDO ⇄ DOID equivalents; medical codes grouped from cross-references
            ▼
          5. CONNECT             PubTator3: how the genes, diseases and chemicals are related in PubMed;
            │                    concepts the outside annotators found that the reading missed
            ▼
          6. SAVE + FLAG         run saved with run_id; low-confidence items go to a review queue
            ▼
          7. LEARN               confident, exact, unflagged mappings go into the dictionary
```

**No hard-coded terms.** Ontology content always comes live from the sources, so new releases are
picked up automatically. What the service *knows how to do* is kept as plain files in
[`knowledge/`](knowledge/). Anyone can read them, edit them and send changes as a pull request:

| File | What it is | How it's used |
|---|---|---|
| `examples/*.yaml` | Worked examples: input text + what a good answer looks like | The most similar ones are shown to the brain as few-shot examples |
| `guidelines.yaml` | Plain-language rules ("mouse phenotypes go to MP") | Shown to the brain on every request |
| `dictionary.yaml` | The learning dictionary: "this phrase → this ID", each `confirmed`, `learned` or `rejected` | Priors in ranking and precedent for the brain, *not* a lookup table |
| `sources.yaml` | The catalogue of outside APIs: what each is good for, which kinds it is asked about, keys, terms | Read by the AI through `list_sources`; edit to turn helpers on/off or add a new API |
| `config.yaml` | Ontologies per concept kind; `code_systems` (which cross-reference prefixes are which medical code); `identifier_patterns` (how to spot and resolve IDs in text); literature settings; thresholds | Edit to add an ontology, a code system or a new kind of identifier, with no code changes |

## Medical codes and identifiers

**Codes for what it found.** Diseases are grounded to MONDO, which carries curated cross-references
to other vocabularies. `code_systems` in `config.yaml` names them, and every annotation gets a
`codes` block that starts with the term's own ID. For example, for Duchenne muscular dystrophy:
`{"MONDO": ["0010679"], "OMIM": ["310200"], "ICD-10-CM": ["G71.01"], "MeSH": ["D020388"], "UMLS":
["C0013264"], "SNOMED CT": [...], "Orphanet": [...], "NANDO": [...]}`. A disease grounded to another
ontology (Disease Ontology, say) still gets its MONDO code. Genes get NCBI Gene, HGNC / MGI, OMIM,
Ensembl and UniProt IDs from MyGene.info.

**Codes and links from the Monarch Initiative.** Each disease and gene is also looked up in the
[Monarch Initiative](https://monarchinitiative.org/) knowledge graph (`/v3/api/entity/{id}`): a
disease by its MONDO ID, a gene by its HGNC (human) or MGI (mouse) code. Monarch's mappings are
added to `codes`, and its curated causal links go in `related`: for a gene, the MONDO diseases it
causes (CFTR → MONDO:0009061 cystic fibrosis, …); for a disease, the genes that cause it. If Monarch
is down or disabled in `sources.yaml`, analyses still work without it.

**IDs already in the text.** `identifier_patterns` in `config.yaml` is a list of regular
expressions, each with how to resolve the match: as an ontology ID, through MyDisease's
cross-reference index, as a fielded MyGene or MyChem query, or through any source in the catalogue.
ICD-10 sub-codes fall back to their parent code, and the answer says when it did. CAS numbers must
pass their check digit. To add a new kind of identifier, add an entry to that list.

These codes are **passed on from the sources' cross-references**, not issued by this project. Some
code systems (SNOMED CT, UMLS, ICD, MedDRA) have their own licence terms for some uses. See
[Data licences](#data-licences).

## Literature connections (PubTator3)

When an analysis finishes, the grounded genes, diseases and chemicals are mapped to PubTator3's
entities. PubTator3 then reports the **relations it has mined from PubMed** between each pair (treat,
cause, associate, inhibit, stimulate, interact, positive/negative correlation, …), with the
number of papers and a few example PMIDs for the strongest ones. The PubTator3 text annotator also
runs over your text in the background. Concepts it finds that the reading missed come back under
`possibly_missed`.

**How terms are matched to PubTator3, and back.**
- Diseases and chemicals are matched by their MeSH code. MONDO supplies a disease's MeSH code; for
  a chemical it comes from MyChem.info, because ChEBI carries none.
- Without a MeSH code, the name or a short synonym must match, and the entity is flagged
  `matched_by: name`.
- Genes are matched by NCBI Gene ID, or else by symbol. PubTator3 keys genes by symbol, so mouse
  *Lep* and human *LEP* share `@GENE_LEP`, and **gene evidence is pooled across species**.
- When several of your IDs are the same PubTator entity (MONDO:0010679 and DOID:11723), they are
  merged and listed together (`subject_ids` / `object_ids`).

**Direction.**
- One query per pair returns both directions.
- `directed: true` only for a chemical acting on a gene or disease ("metformin *treat* type 2
  diabetes").
- PubTator3 writes every gene–disease row as disease → gene, whatever it means. So those, and all
  symmetric relations (associate, interact, correlations), are listed gene first, not directed. The
  two directions of a symmetric relation are merged.

**Evidence.**
- Relations seen in fewer than `min_publications` papers (default 3) are left out and counted in
  `below_min_publications`.
- Example papers are fetched for the relation type itself: the "cause" papers, not every paper on
  the pair.
- Terms PubTator3 doesn't cover (GO processes, anatomy, …) are listed as `not_covered`. Terms past
  `max_entities` are listed as `skipped_over_limit`, not as unmatched. Genes, chemicals and diseases
  are taken first.

**One hop out, both ways (`find_literature_neighbours`).** From one ID you get its strongest gene,
disease or chemical neighbours, mapped back to NCBIGene / MONDO / ChEBI:
- What treats cystic fibrosis: `neighbours MONDO:0009061 --kind chemical --relation treat` gives
  ivacaftor (1,238 papers), tezacaftor, elexacaftor and tobramycin.
- What cinnamaldehyde acts on: `--kind gene` gives TRPA1, TNF, NFE2L2 and more.

It only goes one hop. Automatic chains (chemical → gene → disease) run through hub terms such as
TNF, IL6 or "inflammation" and produce spurious paths, so chain hops yourself and check each one.

These connections are **relations mined automatically from papers, not curated facts**. Read the
example papers before you rely on one. You can tune them or turn them off in `config.yaml` →
`literature`. PubTator3 asks for at most 3 requests a second, and the service keeps to that.

## The learning dictionary

Each entry in `knowledge/dictionary.yaml` looks like this:

```yaml
- phrase: Nrf2
  curie: NCBIGene:4780
  status: learned        # confirmed | learned | rejected
  source: usage          # curator | usage (a confident analysis) | ai (added with learn_term)
  kind: gene
  label: NFE2L2 (human): NFE2 like bZIP transcription factor 2
  count: 3               # times it has been seen; learned entries get stronger as this grows
```

| Status | Comes from | Effect on ranking |
|---|---|---|
| `confirmed` | A person (`refine_feedback`, `refine_confirm_run`, `refine_review_entry`) | Strong boost; always beats anything learned |
| `learned` | Automatically, from confident analyses, or from an AI calling `learn_term` | Boost; much larger when the wording is identical, grows with `count` |
| `rejected` | A person | Strong penalty; automatic learning never overwrites a rejection |

Learning is careful about what it keeps. It only learns an exact match that is not implied, at or
above `learning.min_confidence` (default 0.85), not flagged for review, and only where the phrase
says more than the label does. Every ID is checked at its source before it is stored, and obsolete or
invented IDs are refused. Set `learning.auto_learn: false` to turn automatic learning off.
Curators review what was learned with `refine_list_dictionary status=learned`, then
`refine_review_entry` with `confirmed` or `rejected`.

## Outside help: the source catalogue

OLS and MyGene.info are always searched. Each concept is also sent to the outside helpers that cover
its kind. A helper can only add IDs from ontologies that kind allows, or IDs it is the authority
for (such as Reactome pathways). Every chosen ID is still verified. When several sources find the
same candidate, it lists them all (for example `source: ols,mydisease,monarch`) and ranks higher.

| Source | Helps with | Key |
|---|---|---|
| `ols` (EMBL-EBI Ontology Lookup Service) | Every ontology: search, term details, cross-references | none |
| `mygene` (MyGene.info) | Genes in any species → NCBI Gene, with HGNC / MGI / OMIM / Ensembl / UniProt | none |
| `mydisease` (MyDisease.info) | Diseases → MONDO; reverse lookups from OMIM / Orphanet / ICD / MeSH / UMLS | none |
| `monarch` (Monarch Initiative) | Second opinion on diseases and phenotypes | none |
| `mychem` (MyChem.info) | Chemicals, drug names and CAS numbers → ChEBI, with PubChem / DrugBank | none |
| `myvariant` (MyVariant.info) | Variants (rsIDs) → gene and ClinVar conditions | none |
| `reactome` | Named signalling and metabolic pathways → `Reactome:R-HSA-…` | none |
| `ncbi_taxonomy` (NCBI E-utilities) | Organisms by common name ("bovine", "zebrafish") → NCBITaxon | optional (`NCBI_API_KEY`) |
| `pubtator` (NCBI PubTator3) | How papers name genes, diseases and chemicals; **literature connections** | none |
| `pubtator_text` (PubTator3 annotator) | Tags genes, diseases, chemicals, species and variants in your whole text (slow; background) | none |
| `bioportal` (NCBO BioPortal) | 1,000+ ontologies, and a fast **text annotator** | **required** (free) |
| `uniprot` | Proteins by name. Off by default; a template for adding any JSON API without code | none |
| `quickgo` (EMBL-EBI QuickGO) | Is a gene annotated to a GO function or process (including curators' NOT)? Used by `check_consistency` | none |
| `maxo_annotations` (Monarch, MAxO) | Curated treatments and diagnostics for a MONDO disease, with the phenotype targeted and a PMID | none |
| `dismech` (Monarch DisMech) | A disease's mechanism page and the papers it cites | none |
| `namo` (Monarch NAMO) | Model systems that replace animal testing: organoids, organ-on-chip, cell-free assays, in-silico models (QSAR, PBPK, digital twins) → `namo:ClassName`. A LinkML schema, not in OLS: downloaded once a day and searched locally | none |

The catalogue is [`knowledge/sources.yaml`](knowledge/sources.yaml). Each entry says, in plain words,
what the source is good for and not good for, which concept kinds it covers, which IDs it returns, its rate
limits and its terms of use. The AI reads it with `list_sources` and can call `ask_source` itself
when a concept is hard to ground. To add another JSON REST API, copy the `uniprot` entry
(`adapter: rest_json`) and describe its URL and fields.

### API keys

Some services need a key. **Keys are never typed into the AI chat.** When a source needs one, the
MCP's `request_api_key` tool tells the AI to ask you to run a command in your own terminal:

```bash
biogrounder keys set bioportal     # asks for the key with hidden input
biogrounder keys list              # which sources have a key, and where (never the key)
biogrounder keys remove bioportal
```

Keys are kept in your desktop's credential store (Secret Service / GNOME Keyring or KWallet on
Linux; also the macOS Keychain or Windows Credential Manager). On a headless Linux server there is
usually none, so they go in a private file, `~/.biogrounder/keys.json`, mode
0600 (readable only by you). On a server, set the
environment variable named in `sources.yaml` instead (for example `BIOPORTAL_API_KEY`), which takes
precedence. Keys never go in the repository. Each key is sent only to its own service. No key is
ever logged or returned from a tool.

## Checking an answer, both ways

Running a description forward (text → IDs) and then backward (IDs → what they mean) is a useful check,
but rewriting the whole text from the IDs and comparing would mostly measure writing style. So the
backward check is done **per term**, with evidence you can read:

| Check | What it asks | Tool / REST / CLI |
|---|---|---|
| **The ID exists** | Every ID is looked up at its source. Obsolete IDs are swapped for their `term_replaced_by` successor, and anything that can't be verified is dropped. Each annotation carries `id_check`. | automatic |
| **The text supports it** | Is the term's label, a synonym or the quoted evidence actually in the text, or was it implied? Each annotation carries `text_support` (`label` / `synonym` / `quote` / `implied` / `none`); `none` goes to the review queue. | automatic |
| **The definition fits** | Each chosen term's definition, synonyms and parents are read back against the text, and every quote a verdict cites must appear word for word. | `check_support` · `POST /check/support` · `check` |
| **The terms agree with each other** | The chosen phenotypes against the chosen disease's (or gene's) **curated phenotype profile** in Monarch, by semantic similarity over PHENIO. Each gene against each chosen GO function (QuickGO, including curators' "NOT"). Each treatment against the disease's MAxO annotations. | `check_consistency` · `POST /check/consistency` · `consistency` |
| **Against a gold answer** | Precision, recall, F1 and Jaccard against the worked examples. Each example lists acceptable alternatives and **forbidden** answers, so absence is tested as well as presence. A parent or child of the right term earns half credit, and near misses are named (`broader`, `narrower`, `sibling`, or `similar` across species). | `refine_evaluate` (server model) or `get_test_cases` + `score_answer` (any AI) |
| **Against expert curators, at scale** | Public corpora: **BC5CDR** (1,500 PubMed abstracts; chemicals and diseases, MeSH) and **CRAFT** (97 full-text articles; ChEBI, CL, GO, MONDO, NCBITaxon, UBERON). `normalize` grounds each annotated phrase (no model needed) and reports accuracy at 1 and 5 by kind, with the misses; `full` compares whole-document ID sets (server model). | `run_benchmark` · `benchmark bc5cdr` / `benchmark craft` |
| **The knowledge files are sound** | The schema, file names, contradictions, and every ID in every file (exists, not obsolete, label matches). Runs in CI on every pull request that touches `knowledge/`, and weekly. | `validate_knowledge` · `GET /check/knowledge` · `validate` |

For example, for Duchenne muscular dystrophy with proximal muscle weakness, skeletal muscle atrophy,
motor delay and obesity, `check_consistency` reports that 3 of the 4 phenotypes are among the 39
that Monarch has curated for the disease (exact matches). Obesity matches nothing close, which
is worth a second look. It reports the same for the gene, DMD.
Missing curation is not evidence against: it may simply not be curated yet.

**Benchmarks.** `biogrounder benchmark bc5cdr` (or `craft`) downloads the corpus once into
`~/.biogrounder/benchmarks` and scores grounding against what expert curators chose. The first runs
found three ranking problems, now fixed: the plain term behind a short word ("neurons", "DNA") could be
missing from the search results, so exact name and synonym matches are now looked up first;
international and US spellings (indometacin / indomethacin) now count as the same name, by explicit
rules only, so look-alike substances (insulin / inulin) never match; and a source's own ranking now
weighs less than how well the name matches. On the same small samples (60 BC5CDR and 63 CRAFT
phrases, grounding each phrase on its own), accuracy at 1 went from 0.53 to 0.58 (BC5CDR) and 0.49 to
0.54 (CRAFT). Phrase-only grounding has no context, so abbreviations such as "SRC" are expected
misses; and an answer can be the right concept yet count as a miss when no cross-reference links it to
the curators' MeSH ID. Run larger samples with `--mentions` and `--docs`.

**Tests anyone can read and improve.** The tests are published in [`tests/`](tests/) and explained
in [TESTING.md](TESTING.md). An AI connected to this server can read them too (`list_tests`,
`read_test`, `run_tests`). When it finds a problem it can **propose a change** with
`propose_change`. That saves the proposal and returns a link to a pre-filled GitHub issue, which
the person opens and submits for everyone to review. The server holds no GitHub credentials, so
nothing reaches the repository without a person and a review. See [CONTRIBUTING.md](CONTRIBUTING.md).

**Export.** A saved run can be written out three ways (CLI `export RUN --format kgx|phenopacket|omop`):

- **Knowledge graph.** `export_run_kgx` (`GET /runs/{id}/kgx`) writes [KGX](https://github.com/biolink/kgx)
  nodes and edges in the [Biolink Model](https://biolink.github.io/biolink-model/). Every edge records its
  provenance: `knowledge_level`, `agent_type` and `primary_knowledge_source`. Curated Monarch and MAxO edges
  are knowledge assertions, PubTator3 edges text mining, and relations the model read from the text
  predictions, flagged `ai_generated`.
- **GA4GH Phenopacket v2.** `export_run_phenopacket` (`GET /runs/{id}/phenopacket`) gives the phenotypes
  (each with the words that support it as ECO-coded evidence), the diseases, the genes as candidates under
  the disease, MAxO medical actions and the organism, with complete `metaData`. It describes the text, not a
  patient. IDs that are obsolete or could not be verified, and genes when no disease is named, are listed in
  `left_out` instead.
- **OMOP CDM.** `export_run_omop` (`GET /runs/{id}/omop`) gives one `SOURCE_TO_CONCEPT_MAP` row per code a
  disease, phenotype or medical action carries in an OMOP vocabulary (SNOMED, ICD10CM, MeSH, HPO, Mondo,
  ORPHAcode, ...). The OHDSI vocabularies are licensed per user, so concept IDs are 0 until you add
  `--athena <folder>` with your own [Athena](https://athena.ohdsi.org) download: they are then filled in
  locally through "Maps to", the route [mondo2omop](https://github.com/monarch-initiative/mondo2omop) takes.

## All tools

Every MCP tool is annotated as read-only, recording or destructive, and as local or calling outside
services, so an MCP client can approve lookups automatically and ask before anything is deleted. Every tool
also publishes an **output schema** ([`outputs.py`](src/biogrounder/outputs.py)), so a client or AI knows
the shape of each answer in advance. The schemas are open: a tool that cannot answer returns just `error`,
and a test calls every tool to check its answer passes through its schema unchanged.

**Route 1: analyze** (use it)

| MCP tool | REST | Purpose |
|---|---|---|
| `status` | `GET /status` | Which brain and model are active, knowledge counts, routes |
| `what_does_this_refer_to` | `POST /refer` | **Start here.** The grouped answer (server brain) or the context and steps for the calling AI (client brain) |
| `analyze_text` | `POST /analyze` | Whole pipeline in one call, full detail (needs a server-side brain) |
| `identify_ids` | `POST /identify` | IDs written in the text, and what each refers to |
| `find_literature_connections` | `POST /connections` | PubTator3 relations between a run's terms or a list of IDs |
| `find_literature_neighbours` | `POST /connections/neighbours` | One hop out from one ID: its gene, disease or chemical neighbours in PubMed, mapped back to NCBIGene / MONDO / ChEBI |
| `get_learning_context` | `POST /context` | Similar examples, guidelines, earlier verdicts for a text |
| `ground_terms` | `POST /ground` | Ranked live candidates for concepts you give it |
| `lookup_term` | `GET /terms/{curie}` | Label, definition, synonyms, xrefs, obsolete status (any source's IDs) |
| `crosswalk_term` | `GET /crosswalk/{curie}?target=DOID` | Verified equivalents (MONDO ⇄ DOID, …) |
| `record_analysis` | `POST /runs` | Save an analysis the calling AI reasoned out; IDs verified, codes added, grouped `references` returned |
| `get_run`, `list_runs` | `GET /runs[/{id}]` | Past runs; `status=needs_review` is the review queue |
| `list_sources` | `GET /sources` | The outside-API catalogue and what is active |
| `ask_source` | `POST /sources/{id}/ask` | Ask one helper directly |
| `scan_text_with_sources` | `POST /sources/scan` | Run the text annotators over the whole text |
| `get_scan_result` | `GET /sources/scan/{scan_id}` | Collect a background scan (PubTator3 often takes 1–2 minutes) |
| `request_api_key` | `GET /sources/{id}/key-help` | How a person enables a source that needs a key |
| `learn_term` | `POST /learn` | Teach it: "*this phrase* means *this ID*" (verified, stored as `learned`) |
| `lookup_dictionary` | `GET /dictionary/lookup?phrase=…` | What the dictionary already knows about a phrase |
| `check_support` | `POST /check/support` | Backward check: does each chosen term's definition fit the text? |
| `check_consistency` | `POST /check/consistency` | Do the terms agree: phenotypes vs disease or gene, gene vs GO function, disease vs treatment |
| `get_test_cases`, `score_answer` | `GET /check/cases`, `POST /check/score` | Answer the worked examples yourself and get scored |
| `validate_knowledge` | `GET /check/knowledge` | Check the knowledge files and every ID in them |
| `list_tests`, `read_test` | – | Read the published test suite |
| `export_run_kgx` | `GET /runs/{id}/kgx` | A run as KGX / Biolink nodes and edges, with provenance |
| `export_run_phenopacket` | `GET /runs/{id}/phenopacket` | A run as a GA4GH Phenopacket v2 |
| `export_run_omop` | `GET /runs/{id}/omop` | A run's codes as OMOP SOURCE_TO_CONCEPT_MAP rows |

**Route 2: refine** (make it better)

| MCP tool | REST | Purpose |
|---|---|---|
| `refine_feedback` | `POST /refine/feedback` | "For *this mention*, the right ID is X / Y was wrong, because …" |
| `refine_confirm_run` | `POST /refine/runs/{id}/confirm` | Mark a run correct; its mappings become `confirmed` entries |
| `refine_promote_to_example` | `POST /refine/runs/{id}/promote` | Turn a reviewed run into a worked example |
| `refine_add_example` / `_update_` / `_delete_` / `_list_` / `_get_` | `/refine/examples` | Manage worked examples |
| `refine_add_guideline` / `_remove_` / `_list_` | `/refine/guidelines` | Manage plain-language rules |
| `refine_list_dictionary` | `GET /refine/dictionary?status=learned` | Inspect the dictionary |
| `refine_review_entry` | `POST /refine/dictionary/review` | Confirm or reject a dictionary entry |
| `refine_remove_entry` | `DELETE /refine/dictionary` | Forget an entry |
| `refine_update_source` | `PATCH /refine/sources/{id}` | Turn a helper on/off, change its kinds, note what it is good or bad at |
| `refine_evaluate` | `POST /refine/evaluate` | Re-run every example (hidden from itself) and report precision / recall |
| `run_tests` | – | Run the offline test suite (or named tests) and return the results |
| `run_benchmark` | – | Score grounding against BC5CDR or CRAFT (capped; the CLI runs larger samples) |
| `propose_change`, `list_proposals` | – | Save a proposed fix and get a pre-filled GitHub issue link for people to review |

MCP prompts: `curate` (the full client-side workflow, including the backward check), `diagnose`
(find out why an answer was wrong and propose a fix) and `review_queue` (work through flagged runs).

The learning loop: **analyze (the dictionary grows by itself) → review the queue and the learned
entries → feedback / confirm / reject → promote good runs to examples → evaluate.**

## Any LLM: a subscription, an API key, or a local model

The reading (what the text is about, which concepts to look up) and the choosing (which candidate
ID fits) can be done by any of these. Everything else (grounding, verification, codes, connections,
learning) is the same whichever you pick, and **the model can never invent an ID**: it can only
choose from candidates the ontology services returned, and the pipeline rejects anything else. In client mode the calling AI chooses, and `record_analysis`
accepts any ID that really exists (checked at its source); one that does not is dropped.

| How you pay | Set `BIOGROUNDER_BRAIN` to | What happens |
|---|---|---|
| **A chat subscription** (Claude, ChatGPT, …) | `client` (the default) | The AI app you already use reasons. Connect this MCP server to it: Claude Desktop, Claude Code, ChatGPT or any other app that supports MCP. `what_does_this_refer_to` gives it the IDs found in the text, the context, a background scan and the steps; it reads the text, then calls `ground_terms` and `record_analysis`. The `curate` MCP prompt walks it through. No key, no cost beyond the subscription. |
| **An API key (pay per token)** | `anthropic`, `openai`, `gemini`, `mistral`, `groq`, `deepseek`, `xai`, `openrouter` (one key, many models), `together` | The server calls the model itself, so `what_does_this_refer_to` and `analyze_text` do everything in one call, and the REST API and CLI can too. |
| **A model on your own computer** | `ollama`, `lmstudio`, `llamacpp`, `vllm` | Same, with nothing leaving your machine but the ontology lookups. No key. |
| **Any other OpenAI-compatible server** | `openai-compatible` | Give its URL in `BIOGROUNDER_LLM_URL` (and a key with `keys set openai-compatible`, if it needs one). |

```bash
# A key: stored in your system's credential store, typed with hidden input (never paste it into an AI chat)
biogrounder keys set openai
export BIOGROUNDER_BRAIN=openai BIOGROUNDER_MODEL=<a model your account offers>

# A local model: start Ollama and pull a model, then
export BIOGROUNDER_BRAIN=ollama           # uses the model Ollama has loaded, or set BIOGROUNDER_MODEL

biogrounder llm list             # providers, keys stored, which is in use
biogrounder llm models           # what the chosen provider offers (spends no tokens)
biogrounder status               # shows the brain, the model, or what is missing
```

**How it talks to each kind:**
- Claude goes through the official Anthropic SDK, with structured outputs, adaptive thinking, the
  effort setting, and prompt caching of the guidelines and examples the two calls share. The
  default model is `claude-opus-5-5`.
- Every other provider goes through the OpenAI-compatible chat API, asking for output that matches
  a JSON schema. A server that doesn't support that gets JSON mode, and then the schema written into
  the prompt; the server remembers which form worked.
- Every answer is validated. A wrong one is sent back once with the errors to fix, and
  `<think>` blocks or code fences around the JSON are ignored.
- Small local models make more mistakes in both steps. That is why `confidence`, the review queue
  and `evaluate` exist: run `biogrounder evaluate` to see how a model scores
  on your worked examples before relying on it.

For other providers, pick the model by its name at that provider (`llm models` lists them). vLLM's
own default port, 8000, is also this project's REST API port, so start vLLM with `--port 8001` (the
`vllm` preset expects that) or set `BIOGROUNDER_LLM_URL`. If the server can't use the
model you chose (no key, server not running), it still starts: `status` says what is missing, and the
tools that need the model say so.

## Quick start

Built for **Linux**: CI runs on Ubuntu and the container image is Debian. It needs Python 3.15 or
newer (the current stable release). It also runs on macOS and Windows.

With [uv](https://docs.astral.sh/uv/), nothing to install first. It is on
[PyPI](https://pypi.org/project/biogrounder/) and listed in the
[MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.djportUCD/biogrounder`, so MCP
clients that browse the registry (including GitHub's) can find and install it:

```bash
uvx biogrounder status                                                  # the latest release
uvx --from git+https://github.com/djportUCD/biogrounder biogrounder status   # or the latest code on main
```

On first use it copies its starter knowledge (examples, guidelines, dictionary, sources) to
`~/.biogrounder/knowledge`, where your saved runs and learned terms are kept too.

Or from a checkout (`uv sync` installs the exact versions in `uv.lock`; `pip install -e .` also works):

```bash
git clone https://github.com/djportUCD/biogrounder.git
cd biogrounder
uv sync
. .venv/bin/activate
biogrounder status
biogrounder identify "OMIM 310200, ICD-10 G71.0, rs113993960"
biogrounder ground "Duchenne muscular dystrophy" --kind disease
biogrounder connect NCBIGene:1756 MONDO:0010679
biogrounder refer "CFTR is an ATP-gated chloride channel ..."   # full answer needs a server-side model (see above)
```

### Use it from Claude Code

As a plugin, which brings the MCP server plus the `ontology-grounding` skill (when to use which
tool, and how to check an answer before giving it). It needs uv:

```text
/plugin marketplace add djportUCD/biogrounder
/plugin install biogrounder@biogrounder
```

Or just the MCP server:

```bash
claude mcp add biogrounder -- uvx biogrounder mcp
```

### Use it from Claude Desktop

Add this to `claude_desktop_config.json` (Settings → Developer → Edit Config):

```json
{
  "mcpServers": {
    "biogrounder": {
      "command": "uvx",
      "args": ["biogrounder", "mcp"]
    }
  }
}
```

If Claude Desktop cannot find `uvx`, give its full path (`which uvx`, or `where uvx` on Windows). To use a
checkout instead, point `command` at `.venv/bin/biogrounder` in it and add
`"env": { "BIOGROUNDER_KNOWLEDGE_DIR": "/full/path/to/biogrounder/knowledge" }`.

That uses Claude Desktop itself (your subscription) to reason. To have the server use its own model
instead, add for example `"BIOGROUNDER_BRAIN": "ollama"` to `env`, or a provider whose key
you stored with `keys set`.

Then ask it things like:

> What does this abstract refer to? …
>
> Which disease is "ORPHA:586", and what are its ICD-10 and MeSH codes?
>
> How are the genes and chemicals in that run connected in the literature?
>
> That run mapped "loss of speech" to Aphasia; the right term is HP:0002371. Record that feedback.
>
> Remember that in our assay descriptions "IVM" means in vitro maturation.

### REST API

```bash
biogrounder api --port 8000         # docs at http://localhost:8000/docs
curl -s localhost:8000/identify -H 'content-type: application/json' -d '{"text":"OMIM 219700 and CAS 60-18-4"}'
curl -s localhost:8000/refer    -H 'content-type: application/json' -d '{"text":"CFTR is an ATP-gated chloride channel ..."}'
curl -s localhost:8000/connections -H 'content-type: application/json' -d '{"curies":["NCBIGene:1080","MONDO:0009061"]}'
```

### Command line

Every command prints JSON. Run `biogrounder <command> --help` for its options.

| Command | What it does |
|---|---|
| `mcp` / `api` | Run the MCP server (stdio or streamable HTTP) / the REST API, which also serves `/mcp` |
| `refer`, `analyze` | What a text refers to; the full pipeline (both need a server-side model for the full answer) |
| `identify` | IDs written in a text, resolved |
| `ground`, `lookup` | Candidates for one concept; details of one ID |
| `connect`, `neighbours` | Literature connections between IDs; one hop out from one ID |
| `check`, `consistency` | The backward check; do the terms agree with curated knowledge |
| `score`, `evaluate` | Score an answer against a worked example; score the server's model on all of them |
| `validate`, `schemas` | Check the knowledge files (exits 1 on errors); write their JSON Schemas |
| `export` | A saved run as KGX nodes and edges, a GA4GH Phenopacket, or OMOP SOURCE_TO_CONCEPT_MAP rows (`--format`, `--athena`) |
| `benchmark` | Score grounding against BC5CDR or CRAFT (`--mode normalize|full`, `--mentions`, `--docs`) |
| `sources`, `ask` | The outside sources and whether each is on; ask one directly |
| `status`, `llm`, `keys` | Configuration; model providers and their models; store, list or remove API keys |

### MCP over HTTP (for a shared server)

The REST API also serves MCP (streamable HTTP) at `/mcp`, so one process does both:
`biogrounder api` → MCP clients connect to `http://localhost:8000/mcp`. To
serve MCP on its own:

```bash
BIOGROUNDER_ROUTES=analyze biogrounder mcp --transport streamable-http --host 0.0.0.0 --port 8765
```

Either way, the server only answers requests addressed to an allowed host name, and refuses requests
that web pages on other sites send (protection against DNS rebinding). The default is localhost. Add
your server's name with `BIOGROUNDER_ALLOWED_HOSTS`. With the refine route on and
`BIOGROUNDER_ADMIN_TOKEN` set, `/mcp` needs the token. The stand-alone server warns at
start-up when it would expose the refine tools beyond this computer without one.

### Linux container (Podman)

The repository ships a `Containerfile` for a Debian-based Linux image that runs as an unprivileged
user. Build and run it with [Podman](https://podman.io/), which is rootless and has no daemon:

```bash
podman build -t biogrounder .
podman run --rm -p 8000:8000 -e BIOGROUNDER_BRAIN=anthropic -e ANTHROPIC_API_KEY=... -e BIOGROUNDER_ADMIN_TOKEN=change-me biogrounder
podman run --rm -p 8765:8765 biogrounder biogrounder mcp --transport streamable-http --host 0.0.0.0 --port 8765
```

To keep learned dictionary entries and saved runs between containers, mount the knowledge folder.
With rootless Podman, add `--userns=keep-id` so the container can write to it:

```bash
podman run --rm -p 8000:8000 --userns=keep-id -v ./knowledge:/app/knowledge:Z -e BIOGROUNDER_ADMIN_TOKEN=change-me biogrounder
```

Pass API keys as environment variables (`-e BIOPORTAL_API_KEY=...`), never inside the image. To
use a model running on the host (Ollama, say), point the container at the host:
`-e BIOGROUNDER_BRAIN=ollama -e BIOGROUNDER_LLM_URL=http://host.containers.internal:11434/v1`.
The image installs exactly the versions in `uv.lock` (a uv build stage; the final image has no build
tools). CI builds it with Podman on Linux and checks that the API answers inside it.

## Configuration

| Variable | Default | Meaning |
|---|---|---|
| `BIOGROUNDER_BRAIN` | `client` (`anthropic` if `ANTHROPIC_API_KEY` is set) | Who reasons: `client`, or a provider (see [Any LLM](#any-llm-a-subscription-an-api-key-or-a-local-model)) |
| `BIOGROUNDER_MODEL` | `claude-opus-5-5` for Claude; the loaded model for a local server | The model at that provider |
| `BIOGROUNDER_LLM_URL` | the provider's usual address | Base URL of an OpenAI-compatible server (another host or port) |
| `BIOGROUNDER_LLM_KEY` | – | Key for an `openai-compatible` server, if it needs one (or `keys set openai-compatible`) |
| `BIOGROUNDER_MAX_TOKENS` | – | Output token limit sent to OpenAI-compatible servers |
| `ANTHROPIC_API_KEY` (or `ANTHROPIC_AUTH_TOKEN`), `OPENAI_API_KEY`, `GEMINI_API_KEY`, `MISTRAL_API_KEY`, `GROQ_API_KEY`, `DEEPSEEK_API_KEY`, `XAI_API_KEY`, `OPENROUTER_API_KEY`, `TOGETHER_API_KEY` | – | Provider keys (or store them with `keys set <provider>`) |
| `BIOGROUNDER_EFFORT` | `high` | Claude's reasoning effort: `low` / `medium` / `high` / `xhigh` / `max` |
| `BIOGROUNDER_FALLBACKS` | `default` | If Claude declines a request, re-run it on a fallback model; `off` disables this |
| `BIOGROUNDER_BENCHMARK_DIR` | `~/.biogrounder/benchmarks` | Where downloaded benchmark corpora are kept |
| `BIOGROUNDER_KNOWLEDGE_DIR` | `./knowledge` if it exists, then the checkout's `knowledge/`, then `~/.biogrounder/knowledge` (seeded on first use; what `uvx` and plugin users get) | Where examples, guidelines, the dictionary and runs live |
| `BIOGROUNDER_ROUTES` | `analyze,refine` | Which routes to expose; use `analyze` on a public server |
| `BIOGROUNDER_ADMIN_TOKEN` | – | If set, REST `/refine/*` and `/mcp` (when the refine route is on) need `Authorization: Bearer <token>` |
| `BIOGROUNDER_ALLOWED_HOSTS` | `localhost`, `127.0.0.1`, `[::1]` (any port) | Host names the HTTP server answers, comma-separated (`name`, or `name:*` for any port; `*` for any host, only behind a proxy that checks it) |
| `BIOGROUNDER_OLS_URL` | EBI OLS4 | Point at a local OLS instance if you run one |
| `BIOGROUNDER_MYGENE_URL` | `https://mygene.info/v3` | Another MyGene.info instance |
| `BIOGROUNDER_HTTP_TIMEOUT` | `30` | Seconds before an outside service is given up on (each is retried with backoff) |
| `BIOPORTAL_API_KEY`, `NCBI_API_KEY` | – | Keys for outside sources (or store them with `keys set`) |

`knowledge/config.yaml` also holds `learning`, `literature`, `code_systems` and `identifier_patterns`.

**Running it publicly:** the refine route writes files, and so does learning. On a shared server,
either expose only `analyze` or set `BIOGROUNDER_ADMIN_TOKEN`, and consider
`auto_learn: false`. `/mcp` uses the same admin token, in the API and in the stand-alone
`mcp --transport streamable-http`. For anything beyond a token, put it behind a reverse proxy. The outside sources are free public services, so don't hammer them. Each
source has its own rate limit in `sources.yaml`. The client caches results, limits concurrency and
retries with backoff. A lookup that still fails is reported as a warning and the run is flagged for
review, so a failure never looks like "no such term".

## Contributing

The quickest way to help is a pull request that adds a worked example to
[`knowledge/examples/`](knowledge/examples/), a rule to `guidelines.yaml`, a code system or
identifier pattern to `config.yaml`, or a source to `sources.yaml`. See [CONTRIBUTING.md](CONTRIBUTING.md).

```bash
uv sync                          # or: pip install -e . --group dev
uv run pytest -m "not live"      # offline: every outside service and Claude are faked
uv run pytest -m live            # hits the real services
uv run ruff check && uv run ruff format --check
```

[TESTING.md](TESTING.md) explains what each test checks and how to add one.

### Keeping up with outside sources

BioGrounder depends on services, files and links it does not control. Most changes upstream need
nothing from you: the downloaded files (MAxO annotations, DisMech, NAMO) follow their latest release and
are fetched again each day, and if a download fails the last good copy is used. For the rest, the
repository watches itself and turns each change into something to review:

| What changes | How it is noticed | What happens |
|---|---|---|
| A Python package or GitHub Action has a new release | Dependabot, weekly | A pull request; CI runs on it |
| A link in the docs moved permanently, or the CRAFT corpus or uv image has a new release | Upstream watch (weekly, [`scripts/check_upstream.py`](scripts/check_upstream.py)) | Fixed on the branch `upstream/auto-fix` and offered as a pull request |
| A link is gone, or a source changed its answers or file format | Upstream watch: the live tests and the link check | An issue labelled `upstream` names the failing source or link, for a person (or an AI) to fix in a pull request |
| An ID in the knowledge files was retired or relabelled | Knowledge check (weekly) | The run fails, naming the ID |

Nothing is merged automatically: every fix is a pull request a maintainer reviews. To run the watch by
hand: `uv run python scripts/check_upstream.py` (add `--fix` to apply the mechanical fixes) and
`uv run pytest -m live`.

## Limitations

- **Not for clinical use.** The answers are machine-generated and can be wrong. Use the review
  queue: anything below `review_threshold`, ungrounded, dropped or obsolete is flagged.
- Medical codes are only as complete as the sources' cross-references. MONDO maps many diseases
  to OMIM, Orphanet, MeSH, UMLS, ICD and SNOMED CT, but not all of them. Phenotype terms (HP, MP)
  often have no cross-references at all, so they usually carry only their own ID. An ICD-10 sub-code may only
  match its parent, and the answer says so when it does.
- OLS search needs every word of a query to match, so "thyroid hormone synthesis" doesn't find GO's
  "thyroid hormone generation". The reading step is asked to give alternative queries, and outside
  helpers such as Reactome cover some of the gap. Some general concepts (for example "cardiac
  arrhythmia" as a disease) have no single MONDO term.
- Literature connections come from text mining. Two entities can co-occur for many reasons.
  PubTator3's text annotator sometimes picks an unexpected species for a gene (it uses context).
- The PubTator3 text annotator is queued and often takes a minute or two.
- Outside helpers are only as current as their services. If one fails, the failure is noted and the core
  search still runs. `pytest -m live` checks that each still answers the way its adapter expects.
- The bundled examples are a starting point, not a gold standard.

---

## Sources and citations

This project stands on the work below. If you use biogrounder in published
work, **please cite the sources you relied on** as well as this repository. Licences and terms are
summarised here; the source's own page is authoritative.

### Ontologies (searched live through OLS)

| Ontology | Used for | Cite | Licence |
|---|---|---|---|
| **MONDO** (Mondo Disease Ontology) | diseases; source of the disease medical-code cross-references | Vasilevsky NA et al. (2026) *Genetics* 232(4):iyaf215. [doi:10.1093/genetics/iyaf215](https://doi.org/10.1093/genetics/iyaf215) | CC BY 4.0 |
| **DO** (Human Disease Ontology) | diseases, MONDO ⇄ DOID | Baron JA et al. (2026) *Nucleic Acids Res* 54(D1):D1425–D1436. [doi:10.1093/nar/gkaf1213](https://doi.org/10.1093/nar/gkaf1213) | CC0 1.0 |
| **GO** (Gene Ontology) | functions, processes, cell locations | Ashburner M et al. (2000) *Nat Genet* 25(1):25–29. [doi:10.1038/75556](https://doi.org/10.1038/75556); The Gene Ontology Consortium (2026) *Nucleic Acids Res* 54(D1):D1779–D1792. [doi:10.1093/nar/gkaf1292](https://doi.org/10.1093/nar/gkaf1292) (correction [doi:10.1093/nar/gkag678](https://doi.org/10.1093/nar/gkag678)) | CC BY 4.0; please report the GO release used |
| **HPO** (Human Phenotype Ontology) | human phenotypes | Gargano MA et al. (2024) *Nucleic Acids Res* 52(D1):D1333–D1346. [doi:10.1093/nar/gkad1005](https://doi.org/10.1093/nar/gkad1005) | HPO licence: free to use with attribution and the version shown; do not modify the ontology |
| **MP** (Mammalian Phenotype Ontology) | mouse and other mammalian phenotypes | Bello SM et al. (2025) *Dis Model Mech* 18(10):dmm052385. [doi:10.1242/dmm.052385](https://doi.org/10.1242/dmm.052385); Smith CL, Eppig JT (2012) *Mamm Genome* 23(9–10):653–668. [doi:10.1007/s00335-012-9421-3](https://doi.org/10.1007/s00335-012-9421-3) | CC BY 4.0 |
| **Uberon** | tissues and anatomy | Mungall CJ et al. (2012) *Genome Biol* 13(1):R5. [doi:10.1186/gb-2012-13-1-r5](https://doi.org/10.1186/gb-2012-13-1-r5); Haendel MA et al. (2014) *J Biomed Semantics* 5:21. [doi:10.1186/2041-1480-5-21](https://doi.org/10.1186/2041-1480-5-21) | CC BY 3.0 |
| **CL** (Cell Ontology) | cell types | Tan SZK et al. (2026) *Sci Data* 13(1):946. [doi:10.1038/s41597-026-07173-8](https://doi.org/10.1038/s41597-026-07173-8); Diehl AD et al. (2016) *J Biomed Semantics* 7(1):44. [doi:10.1186/s13326-016-0088-7](https://doi.org/10.1186/s13326-016-0088-7) | CC BY 4.0 |
| **ChEBI** | chemicals | Malik A et al. (2026) *Nucleic Acids Res* 54(D1):D1768–D1778. [doi:10.1093/nar/gkaf1271](https://doi.org/10.1093/nar/gkaf1271) | CC BY 4.0 |
| **NCBI Taxonomy** | organisms | Schoch CL et al. (2020) *Database* baaa062. [doi:10.1093/database/baaa062](https://doi.org/10.1093/database/baaa062) | Public domain (US government work) |
| **BAO** (BioAssay Ontology) | assays and test methods | Glenny-Pescov J et al. (2026) *J Biomed Semantics* 17(1):6. [doi:10.1186/s13326-025-00342-5](https://doi.org/10.1186/s13326-025-00342-5); Abeyruwan S et al. (2014) *J Biomed Semantics* 5(Suppl 1):S5. [doi:10.1186/2041-1480-5-S1-S5](https://doi.org/10.1186/2041-1480-5-S1-S5) | CC BY 4.0 |
| **OBI** (Ontology for Biomedical Investigations) | assays, methods, instruments | Bandrowski A et al. (2016) *PLoS One* 11(4):e0154556. [doi:10.1371/journal.pone.0154556](https://doi.org/10.1371/journal.pone.0154556) | CC BY 4.0 |

| **MAxO** (Medical Action Ontology) | treatments, procedures, diagnostic actions | Carmody LC et al. (2023) *Med* 4(12):913–927.e3. [doi:10.1016/j.medj.2023.10.003](https://doi.org/10.1016/j.medj.2023.10.003) | CC BY 4.0 |
| **GENO** (Genotype Ontology) | zygosity, genotypes, allele types | [github.com/monarch-initiative/GENO-ontology](https://github.com/monarch-initiative/GENO-ontology) (Monarch Initiative) | See the repository |
| **CHR** (chromosome and band ontology) | chromosome regions such as 22q11.2 | [OLS: chr](https://www.ebi.ac.uk/ols4/ontologies/chr) (Monarch Initiative) | See the OLS page |

Any other ontology you add in `config.yaml` keeps its own citation and licence.

### Services and databases queried

| Service | Used for | Cite | Terms |
|---|---|---|---|
| **EMBL-EBI Ontology Lookup Service (OLS4)** | ontology search, term details, cross-references | McLaughlin J et al. (2025) *Bioinformatics* 41(5):btaf279. [doi:10.1093/bioinformatics/btaf279](https://doi.org/10.1093/bioinformatics/btaf279) | Software Apache-2.0; [EMBL-EBI terms of use](https://www.ebi.ac.uk/about/terms-of-use) |
| **BioThings APIs**: MyGene.info, MyDisease.info, MyChem.info, MyVariant.info | genes, diseases and reverse code lookups, chemicals and CAS numbers, variants | Xin J et al. (2016) *Genome Biol* 17(1):91. [doi:10.1186/s13059-016-0953-9](https://doi.org/10.1186/s13059-016-0953-9); Lelong S et al. (2022) *Bioinformatics* 38(7):2077–2079. [doi:10.1093/bioinformatics/btac017](https://doi.org/10.1093/bioinformatics/btac017); Wu C et al. (2013) *Nucleic Acids Res* 41(D1):D561–D565. [doi:10.1093/nar/gks1114](https://doi.org/10.1093/nar/gks1114) | Scripps Research terms of use (no open licence); aggregated data keep each source's licence |
| **NCBI Gene** (via MyGene.info) | gene IDs | Brown GR et al. (2015) *Nucleic Acids Res* 43(D1):D36–D42. [doi:10.1093/nar/gku1055](https://doi.org/10.1093/nar/gku1055) | Public domain |
| **dbSNP** (via MyVariant.info) | rsIDs | Sherry ST et al. (2001) *Nucleic Acids Res* 29(1):308–311. [doi:10.1093/nar/29.1.308](https://doi.org/10.1093/nar/29.1.308) | Public domain |
| **ClinVar** (via MyVariant.info) | variant–condition links | Landrum MJ et al. (2018) *Nucleic Acids Res* 46(D1):D1062–D1067. [doi:10.1093/nar/gkx1153](https://doi.org/10.1093/nar/gkx1153) | Public domain |
| **Monarch Initiative** | diseases and phenotypes (second opinion); extra disease and gene codes; gene–disease causal links; curated phenotype profiles of diseases and genes | Putman TE et al. (2024) *Nucleic Acids Res* 52(D1):D938–D949. [doi:10.1093/nar/gkad1082](https://doi.org/10.1093/nar/gkad1082) | Software BSD-3-Clause; data under each source's licence |
| **Monarch semantic similarity** (semsimian over PHENIO, served by the Monarch API) | near misses across species; phenotypes vs a disease's or gene's curated profile | [semsimian](https://github.com/monarch-initiative/semsimian), [PHENIO](https://github.com/monarch-initiative/phenio); with Putman TE et al. (2024) above | Software BSD-3-Clause; data under each source's licence |
| **QuickGO** (GO annotations) | is this gene annotated to this function, including curators' "NOT" | Binns D et al. (2009) *Bioinformatics* 25(22):3045–3046. [doi:10.1093/bioinformatics/btp536](https://doi.org/10.1093/bioinformatics/btp536); GO citations above | Annotations CC BY 4.0; [EMBL-EBI terms of use](https://www.ebi.ac.uk/about/terms-of-use) |
| **maxo-annotations** | curated treatments of a disease's phenotypes, with PMIDs | [github.com/monarch-initiative/maxo-annotations](https://github.com/monarch-initiative/maxo-annotations); Carmody LC et al. (2023) above | CC BY 4.0 |
| **DisMech** | links from a disease to its mechanism page and cited papers | [dismech.monarchinitiative.org](https://dismech.monarchinitiative.org), [github.com/monarch-initiative/dismech](https://github.com/monarch-initiative/dismech). Entries are drafted by AI agents and reviewed by people; not medical advice | Repository BSD-3-Clause; parts contain LOINC content under LOINC's terms. Only links, summaries and PMIDs are shown |
| **Reactome** | pathways | Ragueneau E et al. (2026) *Nucleic Acids Res* 54(D1):D673–D681. [doi:10.1093/nar/gkaf1223](https://doi.org/10.1093/nar/gkaf1223) | CC0 |
| **NCBI E-utilities** | NCBI Taxonomy queries | Entrez Programming Utilities Help, NCBI, [ncbi.nlm.nih.gov/books/NBK25497](https://www.ncbi.nlm.nih.gov/books/NBK25497/); Sayers EW et al. (2026) Database resources of the NCBI, *Nucleic Acids Res* 54(D1):D20–D27. [doi:10.1093/nar/gkaf1060](https://doi.org/10.1093/nar/gkaf1060) | Public domain; [NCBI usage policies](https://www.ncbi.nlm.nih.gov/home/about/policies/) |
| **PubTator3** | entity names, literature relations, example papers, text annotation | Wei CH et al. (2024) *Nucleic Acids Res* 52(W1):W540–W546. [doi:10.1093/nar/gkae235](https://doi.org/10.1093/nar/gkae235) | Public domain; at most 3 requests/second |
| **PubMed** | the papers PubTator3 links to (PMIDs) | National Library of Medicine, [pubmed.ncbi.nlm.nih.gov](https://pubmed.ncbi.nlm.nih.gov/) | Citations are public; article text keeps its publisher's copyright |
| **NCBO BioPortal** and its Annotator (optional, needs a key) | 1,000+ ontologies, text annotation | Vendetti J et al. (2025) *Nucleic Acids Res* 53(W1):W84–W94. [doi:10.1093/nar/gkaf402](https://doi.org/10.1093/nar/gkaf402); Whetzel PL et al. (2011) *Nucleic Acids Res* 39:W541–W545. [doi:10.1093/nar/gkr469](https://doi.org/10.1093/nar/gkr469); Jonquet C, Shah NH, Musen MA (2009) *Summit Transl Bioinform* 2009:56–60 ([PMID 21347171](https://pubmed.ncbi.nlm.nih.gov/21347171/)) | [BioPortal terms](https://bioportal.bioontology.org/); each ontology keeps its own licence |
| **UniProt** (optional, off by default) | protein names | The UniProt Consortium (2025) *Nucleic Acids Res* 53(D1):D609–D617. [doi:10.1093/nar/gkae1010](https://doi.org/10.1093/nar/gkae1010) | CC BY 4.0 |
| **NAMO** (Monarch New Approach Methodology Ontology and Schema) | model systems that replace animal testing (`namo:` IDs) | [github.com/monarch-initiative/namo](https://github.com/monarch-initiative/namo) | BSD-3-Clause |
| **BC5CDR** (BioCreative V CDR corpus; benchmark only, downloaded on request) | expert-annotated chemicals and diseases in 1,500 PubMed abstracts | Li J et al. (2016) *Database* 2016:baw068. [doi:10.1093/database/baw068](https://doi.org/10.1093/database/baw068); Wei CH et al. (2016) *Database* 2016:baw032. [doi:10.1093/database/baw032](https://doi.org/10.1093/database/baw032) | Public domain (NCBI); abstracts keep their publishers' copyright |
| **CRAFT** (Colorado Richly Annotated Full-Text corpus v5.2.0; benchmark only, downloaded on request) | expert concept annotations in 97 full-text articles | Bada M et al. (2012) *BMC Bioinformatics* 13:161. [doi:10.1186/1471-2105-13-161](https://doi.org/10.1186/1471-2105-13-161); [github.com/lhunter-lab/CRAFT](https://github.com/lhunter-lab/CRAFT) | Annotations CC BY 3.0; articles under their own open-access licences |
| **Anthropic Claude** (optional server-side brain) | reading the text and choosing among candidates | [Anthropic API](https://platform.claude.com/docs/en/home) | [Anthropic terms](https://www.anthropic.com/legal) |
| **Other model providers** (optional server-side brain): OpenAI, Google Gemini, Mistral AI, Groq, DeepSeek, xAI, OpenRouter, Together AI, or a local server (Ollama, LM Studio, llama.cpp, vLLM) | the same two steps, through the [OpenAI-compatible chat API](https://developers.openai.com/api/reference/resources/chat) | Each provider's own API documentation | Each provider's own terms; a local model keeps its own model licence |

### Code systems passed through as cross-references

These identifiers are **not looked up from the code systems themselves**. They are copied from the
cross-references that MONDO, the Monarch Initiative, MyGene.info and MyChem.info publish, and named by `code_systems` in
`config.yaml`. They belong to their owners, and some need a licence for some uses:
[OMIM](https://www.omim.org/) (Johns Hopkins University) ·
[Orphanet](https://www.orpha.net/) (INSERM) ·
[ICD-10 / ICD-11](https://icd.who.int/) (WHO) and [ICD-10-CM / ICD-9-CM](https://www.cdc.gov/nchs/icd/) (CDC/NCHS) ·
[MeSH](https://www.nlm.nih.gov/mesh/) (NLM) ·
[UMLS](https://www.nlm.nih.gov/research/umls/) (NLM; UMLS licence) ·
[SNOMED CT](https://www.snomed.org/) (SNOMED International; affiliate licence) ·
[NCI Thesaurus](https://evsexplore.semantics.cancer.gov/evsexplore/welcome) (NCI) ·
[MedDRA](https://www.meddra.org/) (ICH; subscription) ·
[MedGen](https://www.ncbi.nlm.nih.gov/medgen/) (NCBI) ·
[GARD](https://rarediseases.info.nih.gov/) (NIH NCATS) ·
[NANDO](https://nanbyodata.jp/ontology/nando) (Nanbyo Disease Ontology, Japanese intractable diseases; DBCLS) ·
[NCBI Gene](https://www.ncbi.nlm.nih.gov/gene/) (NCBI) ·
[HGNC](https://www.genenames.org/) ·
[MGI](https://www.informatics.jax.org/) ·
[Ensembl](https://www.ensembl.org/) ·
[CAS Registry](https://www.cas.org/) (American Chemical Society) ·
[DrugBank](https://go.drugbank.com/) (restricted licence) ·
[PubChem](https://pubchem.ncbi.nlm.nih.gov/) ·
[KEGG](https://www.kegg.jp/) (licence for some uses) ·
[HMDB](https://hmdb.ca/) ·
[FMA](http://si.washington.edu/projects/fma).

### Standards and inspiration

- **Model Context Protocol** specification, [modelcontextprotocol.io/specification/2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28).
- **RE-Place** ([re-place.be](https://www.re-place.be)), the Belgian platform for New Approach
  Methodologies coordinated by Sciensano and the Vrije Universiteit Brussel. Its way of describing
  test methods (in vitro, ex vivo, in chemico, in silico, lower-organism in vivo) inspired the
  `test-methods` guideline and the `assay` concept kind. No RE-Place content is copied or scraped.
- [OntoGPT / SPIRES](https://github.com/monarch-initiative/ontogpt) and
  [CurateGPT](https://github.com/monarch-initiative/curategpt) (Monarch Initiative), as prior work on
  LLM-assisted, ontology-grounded curation. The ID statuses and the check that each term is
  supported by the text follow OntoGPT's approach.
- **Biolink Model**, the schema of the KGX export: Unni DR et al. (2022) *Clin Transl Sci*
  15(8):1848–1855. [doi:10.1111/cts.13302](https://doi.org/10.1111/cts.13302). **KGX**
  ([github.com/biolink/kgx](https://github.com/biolink/kgx)), the exchange format; the Monarch
  Initiative's practice of flagging model-inferred edges as `ai_generated`.
- **GA4GH Phenopacket schema v2**, the Phenopacket export: Jacobsen JOB et al. (2022) *Nat Biotechnol*
  40(6):817–820. [doi:10.1038/s41587-022-01357-4](https://doi.org/10.1038/s41587-022-01357-4). Its evidence
  codes come from **ECO**, the Evidence and Conclusion Ontology: Nadendla S et al. (2022) *Nucleic Acids Res*
  50(D1):D1515–D1521. [doi:10.1093/nar/gkab1025](https://doi.org/10.1093/nar/gkab1025) (CC0 1.0).
- **OMOP Common Data Model** and the OHDSI standardized vocabularies, the OMOP export: Hripcsak G et al.
  (2015) *Stud Health Technol Inform* 216:574–578 ([PMID 26262116](https://pubmed.ncbi.nlm.nih.gov/26262116/));
  [ohdsi.github.io/CommonDataModel](https://ohdsi.github.io/CommonDataModel/). The vocabularies are not
  included: each user downloads their own from [Athena](https://athena.ohdsi.org) under its licences.
  [mondo2omop](https://github.com/monarch-initiative/mondo2omop) (Monarch Initiative, MIT) showed the route
  from cross-references to OMOP concepts through "Maps to".

### Software

Built with [Python](https://www.python.org/), the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) (MIT),
the [Anthropic Python SDK](https://github.com/anthropics/anthropic-sdk-python) (MIT),
[FastAPI](https://fastapi.tiangolo.com/) (MIT), [Uvicorn](https://uvicorn.dev/) (BSD-3-Clause),
[HTTPX](https://www.python-httpx.org/) (BSD-3-Clause), [Pydantic](https://pydantic.dev/docs/) (MIT),
[PyYAML](https://pyyaml.org/) (MIT) and [keyring](https://github.com/jaraco/keyring) (MIT); tested with
[pytest](https://pytest.org/) (MIT) and [RESPX](https://lundberg.github.io/respx/) (BSD-3-Clause); linted and
formatted with [Ruff](https://docs.astral.sh/ruff/) (MIT) and locked with [uv](https://docs.astral.sh/uv/) (MIT / Apache-2.0).

### Data licences

This project's licence covers its own code and knowledge files only. **Everything it fetches stays
under its source's licence and terms**, as summarised above. In particular: BioThings APIs are
provided under Scripps Research's terms of use; HPO must not be modified and its version should be
shown; DrugBank, SNOMED CT, UMLS, MedDRA, KEGG and some ICD uses need their own licences. Check
these before you redistribute results.

## Licence

**Academic Research and Education Use Licence 1.0**: see [LICENSE](LICENSE).

- ✅ Free for non-commercial **academic research, teaching and scholarly publication** by
  individuals and non-profit academic or research institutions.
- ✅ You may modify it and share it under the same licence; cite it and the sources you used.
- ❌ **No commercial use** (companies, paid services, contract research) without separate written
  permission from the copyright holders.
- No warranty. **Not for clinical decisions.**

This is not an OSI open-source licence, because it restricts the field of use.
