Create cbio.py
Browse files- mcp/cbio.py +41 -0
mcp/cbio.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
cBioPortal async helper – returns cohort-level mutation summary.
|
3 |
+
|
4 |
+
• Works for ANY public molecular-profile ID
|
5 |
+
• One retry on 5xx, returns [] on 404/timeout
|
6 |
+
• Optional CBIO_KEY (JWT) for private studies
|
7 |
+
"""
|
8 |
+
|
9 |
+
from functools import lru_cache
|
10 |
+
import os, asyncio, httpx
|
11 |
+
|
12 |
+
_BASE = "https://www.cbioportal.org/api"
|
13 |
+
_URL = _BASE + (
|
14 |
+
"/molecular-profiles/{profile}/genes/{gene}/mutations?projection=SUMMARY"
|
15 |
+
)
|
16 |
+
_KEY = os.getenv("CBIO_KEY") # optional
|
17 |
+
|
18 |
+
@lru_cache(maxsize=256)
|
19 |
+
async def fetch_cbio(gene: str,
|
20 |
+
profile: str = "brca_tcga_pan_can_atlas_2018_mutations"
|
21 |
+
) -> list[dict]:
|
22 |
+
hdr = {"Accept": "application/json"}
|
23 |
+
if _KEY:
|
24 |
+
hdr["Authorization"] = f"Bearer {_KEY}"
|
25 |
+
|
26 |
+
async def _once() -> list[dict]:
|
27 |
+
async with httpx.AsyncClient(timeout=10, headers=hdr) as c:
|
28 |
+
r = await c.get(_URL.format(profile=profile, gene=gene))
|
29 |
+
if r.status_code == 404: # gene not present
|
30 |
+
return []
|
31 |
+
r.raise_for_status()
|
32 |
+
return r.json()
|
33 |
+
|
34 |
+
try:
|
35 |
+
return await _once()
|
36 |
+
except httpx.HTTPStatusError:
|
37 |
+
await asyncio.sleep(0.4) # back-off then retry
|
38 |
+
try:
|
39 |
+
return await _once()
|
40 |
+
except Exception: # still bad → empty payload
|
41 |
+
return []
|