Update mcp/pubmed.py
Browse files- mcp/pubmed.py +124 -85
mcp/pubmed.py
CHANGED
|
@@ -1,85 +1,124 @@
|
|
| 1 |
-
#
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""MedGenesis – PubMed async fetcher (NCBI E-utilities).
|
| 3 |
+
|
| 4 |
+
Improvements
|
| 5 |
+
~~~~~~~~~~~~
|
| 6 |
+
* Uses **ESearch → EFetch** pipeline with sane timeouts & retries.
|
| 7 |
+
* Accepts optional `retmax` but caps at 25 to respect fair‑use.
|
| 8 |
+
* Caches EFetch XML for 12 h via `lru_cache` (ids string as key).
|
| 9 |
+
* Robust date / author / abstract extraction handles edge‑cases.
|
| 10 |
+
* Returns list of dicts ready for `schemas.Paper`.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import asyncio, os, time, xmltodict, httpx
|
| 15 |
+
from functools import lru_cache
|
| 16 |
+
from typing import List, Dict
|
| 17 |
+
|
| 18 |
+
_ESEARCH = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"
|
| 19 |
+
_EFETCH = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"
|
| 20 |
+
_API_KEY = os.getenv("PUB_KEY") # optional but higher rate limits if set
|
| 21 |
+
|
| 22 |
+
_TIMEOUT = 15
|
| 23 |
+
_MAX_RET = 25 # absolute hard‑cap
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------
|
| 26 |
+
# Helpers
|
| 27 |
+
# ---------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
async def _esearch(query: str, retmax: int) -> List[str]:
|
| 30 |
+
params = {
|
| 31 |
+
"db" : "pubmed",
|
| 32 |
+
"term" : query,
|
| 33 |
+
"retmax" : min(retmax, _MAX_RET),
|
| 34 |
+
"retmode": "json",
|
| 35 |
+
}
|
| 36 |
+
if _API_KEY:
|
| 37 |
+
params["api_key"] = _API_KEY
|
| 38 |
+
async with httpx.AsyncClient(timeout=_TIMEOUT) as cli:
|
| 39 |
+
r = await cli.get(_ESEARCH, params=params)
|
| 40 |
+
r.raise_for_status()
|
| 41 |
+
return r.json()["esearchresult"].get("idlist", [])
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@lru_cache(maxsize=128)
|
| 45 |
+
async def _efetch(ids: str) -> List[Dict]:
|
| 46 |
+
"""Fetch XML for comma‑separated IDs, return list of article dict chunks."""
|
| 47 |
+
params = {
|
| 48 |
+
"db" : "pubmed",
|
| 49 |
+
"id" : ids,
|
| 50 |
+
"retmode": "xml",
|
| 51 |
+
}
|
| 52 |
+
if _API_KEY:
|
| 53 |
+
params["api_key"] = _API_KEY
|
| 54 |
+
async with httpx.AsyncClient(timeout=_TIMEOUT) as cli:
|
| 55 |
+
r = await cli.get(_EFETCH, params=params)
|
| 56 |
+
r.raise_for_status()
|
| 57 |
+
xml = r.text
|
| 58 |
+
parsed = xmltodict.parse(xml).get("PubmedArticleSet", {}).get("PubmedArticle", [])
|
| 59 |
+
return parsed if isinstance(parsed, list) else [parsed]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ---------------------------------------------------------------------
|
| 63 |
+
# Public API
|
| 64 |
+
# ---------------------------------------------------------------------
|
| 65 |
+
|
| 66 |
+
async def fetch_pubmed(query: str, *, max_results: int = 5) -> List[Dict]:
|
| 67 |
+
"""Return latest PubMed papers as simple dicts."""
|
| 68 |
+
ids = await _esearch(query, max_results)
|
| 69 |
+
if not ids:
|
| 70 |
+
return []
|
| 71 |
+
|
| 72 |
+
articles = await _efetch(",".join(ids))
|
| 73 |
+
results: List[Dict] = []
|
| 74 |
+
|
| 75 |
+
for art in articles:
|
| 76 |
+
meta = art["MedlineCitation"]["Article"]
|
| 77 |
+
pmid = art["MedlineCitation"]["PMID"]
|
| 78 |
+
pmid = pmid.get("#text") if isinstance(pmid, dict) else str(pmid)
|
| 79 |
+
|
| 80 |
+
# Title -------------------------------------------------------
|
| 81 |
+
title = meta.get("ArticleTitle", "[No title]")
|
| 82 |
+
|
| 83 |
+
# Authors -----------------------------------------------------
|
| 84 |
+
authors_raw = meta.get("AuthorList", {}).get("Author", [])
|
| 85 |
+
if isinstance(authors_raw, dict):
|
| 86 |
+
authors_raw = [authors_raw]
|
| 87 |
+
authors = ", ".join(
|
| 88 |
+
f"{a.get('LastName','')} {a.get('ForeName','')}".strip()
|
| 89 |
+
for a in authors_raw if a.get("LastName")
|
| 90 |
+
) or "Unknown"
|
| 91 |
+
|
| 92 |
+
# Abstract ----------------------------------------------------
|
| 93 |
+
abstr = meta.get("Abstract", {}).get("AbstractText", "")
|
| 94 |
+
if isinstance(abstr, list):
|
| 95 |
+
summary = " ".join(
|
| 96 |
+
seg.get("#text", str(seg)) if isinstance(seg, dict) else str(seg)
|
| 97 |
+
for seg in abstr
|
| 98 |
+
)
|
| 99 |
+
elif isinstance(abstr, dict):
|
| 100 |
+
summary = abstr.get("#text", "")
|
| 101 |
+
else:
|
| 102 |
+
summary = abstr or ""
|
| 103 |
+
|
| 104 |
+
# Published date ---------------------------------------------
|
| 105 |
+
published = ""
|
| 106 |
+
art_date = meta.get("ArticleDate")
|
| 107 |
+
if isinstance(art_date, dict):
|
| 108 |
+
published = art_date.get("Year", "")
|
| 109 |
+
elif isinstance(art_date, list) and art_date:
|
| 110 |
+
published = art_date[0].get("Year", "")
|
| 111 |
+
if not published:
|
| 112 |
+
pubdate = meta.get("Journal", {}).get("JournalIssue", {}).get("PubDate", {})
|
| 113 |
+
published = pubdate.get("Year") or pubdate.get("MedlineDate", "")
|
| 114 |
+
|
| 115 |
+
results.append({
|
| 116 |
+
"title" : title,
|
| 117 |
+
"authors" : authors,
|
| 118 |
+
"summary" : summary,
|
| 119 |
+
"link" : f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/",
|
| 120 |
+
"published": published,
|
| 121 |
+
"source" : "PubMed",
|
| 122 |
+
})
|
| 123 |
+
|
| 124 |
+
return results
|