mgbam commited on
Commit
1ec3999
·
verified ·
1 Parent(s): eadeaf9

Update mcp/clinicaltrials.py

Browse files
Files changed (1) hide show
  1. mcp/clinicaltrials.py +48 -39
mcp/clinicaltrials.py CHANGED
@@ -1,53 +1,62 @@
1
- import httpx, random
2
 
3
- _BASE_V2 = "https://clinicaltrials.gov/api/v2/studies"
4
- _BASE_V1 = "https://clinicaltrials.gov/api/query/study_fields"
5
- _HEADERS = {
6
- # 3 random desktop UAs – simple rotation avoids naïve geo blocks
7
- 0: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
8
- "(KHTML, like Gecko) Chrome/125 Safari/537.36",
9
- 1: "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_6) AppleWebKit/605.1.15 "
10
- "(KHTML, like Gecko) Version/16 Safari/605.1.15",
11
- 2: "Mozilla/5.0 (X11; Linux x86_64) Gecko/20100101 Firefox/126.0",
 
 
 
12
  }
13
 
14
- async def _try_v2(term: str, n: int):
15
- p = {
 
16
  "query": term,
17
- "pageSize": n,
18
- "fields": ",".join([
19
- "nctId", "briefTitle", "phase", "status",
20
- "startDate", "conditions", "interventions",
21
- ]),
22
  }
23
- async with httpx.AsyncClient(
24
- headers={"User-Agent": _HEADERS[random.randint(0,2)]}, timeout=12
25
- ) as c:
26
- r = await c.get(_BASE_V2, params=p)
27
  if r.status_code == 403:
28
- raise RuntimeError("v2 blocked")
29
  r.raise_for_status()
30
- return r.json().get("studies", [])
 
 
31
 
32
- async def _try_v1(term: str, n: int):
33
- p = dict(
 
34
  expr=term,
35
- fields="NCTId,BriefTitle,Phase,OverallStatus,StartDate,Condition,InterventionName",
36
- max_rnk=n, min_rnk=1, fmt="json",
 
 
37
  )
38
- async with httpx.AsyncClient(
39
- headers={"User-Agent": _HEADERS[random.randint(0,2)]}, timeout=12
40
- ) as c:
41
- r = await c.get(_BASE_V1, params=p)
42
  r.raise_for_status()
43
- return r.json()["StudyFieldsResponse"]["StudyFields"]
 
44
 
45
- # public
46
- async def search_trials(term: str, max_studies: int = 20):
 
 
 
 
 
 
47
  try:
48
- return await _try_v2(term, max_studies)
 
49
  except Exception:
50
- try:
51
- return await _try_v1(term, max_studies)
52
- except Exception:
53
- return [] # always return list
 
1
+ # mcp/clinicaltrials.py
2
 
3
+ import httpx
4
+ from typing import List, Dict
5
+
6
+ BASE_V2 = "https://clinicaltrials.gov/api/v2/studies"
7
+ BASE_V1 = "https://clinicaltrials.gov/api/query/study_fields"
8
+
9
+ HEADERS = {
10
+ "User-Agent": (
11
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
12
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
13
+ "Chrome/124.0 Safari/537.36"
14
+ )
15
  }
16
 
17
+ async def fetch_trials_v2(term: str, limit: int = 10) -> List[Dict]:
18
+ """Fetch clinical trials using v2 API."""
19
+ params = {
20
  "query": term,
21
+ "pageSize": limit,
22
+ "fields": "nctId,briefTitle,phase,status,startDate,conditions,interventions"
 
 
 
23
  }
24
+ async with httpx.AsyncClient(timeout=20, headers=HEADERS) as client:
25
+ r = await client.get(BASE_V2, params=params)
 
 
26
  if r.status_code == 403:
27
+ return [] # API blocked or IP rate-limited
28
  r.raise_for_status()
29
+ js = r.json()
30
+ # List of studies under ['studies']
31
+ return js.get("studies", [])
32
 
33
+ async def fetch_trials_v1(term: str, limit: int = 10) -> List[Dict]:
34
+ """Fallback: Fetch trials using legacy v1 API."""
35
+ params = dict(
36
  expr=term,
37
+ fields="NCTId,BriefTitle,Condition,InterventionName,Phase,OverallStatus,StartDate",
38
+ max_rnk=limit,
39
+ min_rnk=1,
40
+ fmt="json",
41
  )
42
+ async with httpx.AsyncClient(timeout=20, headers=HEADERS) as client:
43
+ r = await client.get(BASE_V1, params=params)
44
+ if r.status_code == 403:
45
+ return []
46
  r.raise_for_status()
47
+ js = r.json()
48
+ return js.get("StudyFieldsResponse", {}).get("StudyFields", [])
49
 
50
+ async def search_trials(term: str, max_studies: int = 10) -> List[Dict]:
51
+ """Unified entry point. Try V2, fallback to V1 if needed."""
52
+ try:
53
+ trials = await fetch_trials_v2(term, max_studies)
54
+ if trials:
55
+ return trials
56
+ except Exception:
57
+ pass
58
  try:
59
+ trials = await fetch_trials_v1(term, max_studies)
60
+ return trials
61
  except Exception:
62
+ return []