mgbam commited on
Commit
20e7231
·
verified ·
1 Parent(s): 4b619d6

Update mcp/cbio.py

Browse files
Files changed (1) hide show
  1. mcp/cbio.py +29 -27
mcp/cbio.py CHANGED
@@ -1,41 +1,43 @@
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 []
 
1
  """
2
+ cBioPortal helper · REST v4 · zero-crash
3
 
4
+ * Public instance needs **no** API-key :contentReference[oaicite:0]{index=0}
5
+ * Optional Bearer token (`CBIO_KEY`) for private portals (e.g. GENIE) :contentReference[oaicite:1]{index=1}
6
+ * One retry on 5xx / ReadTimeout, else returns []
7
  """
8
 
9
+ from __future__ import annotations
10
  import os, asyncio, httpx
11
+ from functools import lru_cache
12
+ from typing import List, Dict
13
 
14
+ _TOKEN = os.getenv("CBIO_KEY") # optional
15
+ _HDR = {"Accept": "application/json"}
16
+ if _TOKEN:
17
+ _HDR["Authorization"] = f"Bearer {_TOKEN}"
 
18
 
19
+ _URL = ("https://www.cbioportal.org/api"
20
+ "/molecular-profiles/{profile}/genes/{gene}/mutations?projection=SUMMARY"
21
+ ) # swagger ref :contentReference[oaicite:2]{index=2}
 
 
 
 
22
 
23
+ @lru_cache(maxsize=256)
24
+ async def fetch_cbio(
25
+ gene : str,
26
+ profile : str = "brca_tcga_pan_can_atlas_2018_mutations"
27
+ ) -> List[Dict]:
28
+ async def _hit() -> List[Dict]:
29
+ async with httpx.AsyncClient(timeout=10, headers=_HDR) as c:
30
  r = await c.get(_URL.format(profile=profile, gene=gene))
31
+ if r.status_code == 404:
32
+ return [] # gene absent
33
  r.raise_for_status()
34
  return r.json()
35
 
36
  try:
37
+ return await _hit()
38
+ except (httpx.HTTPStatusError, httpx.ReadTimeout):
39
+ await asyncio.sleep(0.5) # one back-off
40
  try:
41
+ return await _hit()
42
+ except Exception:
43
+ return [] # graceful fallback