mgbam commited on
Commit
e78e519
·
verified ·
1 Parent(s): 169858b

Update mcp/clinicaltrials.py

Browse files
Files changed (1) hide show
  1. mcp/clinicaltrials.py +27 -43
mcp/clinicaltrials.py CHANGED
@@ -1,47 +1,31 @@
1
- #!/usr/bin/env python3
2
- """
3
- Fetch clinical trials from ClinicalTrials.gov without external clients.
4
- """
5
 
6
- import httpx
7
- import urllib.parse
8
-
9
- async def fetch_clinical_trials(
10
- query: str,
11
- max_studies: int = 10
12
- ) -> list[dict]:
13
- """
14
- Query ClinicalTrials.gov study_fields API for NCTId, Title, Phase, Status.
15
- Returns up to `max_studies` results.
16
- """
17
- # Build the API URL
18
- base = "https://clinicaltrials.gov/api/query/study_fields"
19
- params = {
20
- "expr": query,
21
- "fields": ",".join(["NCTId", "BriefTitle", "Phase", "OverallStatus"]),
22
- "max_rnk": max_studies,
23
- "fmt": "json",
24
- }
25
- url = f"{base}?{urllib.parse.urlencode(params)}"
26
 
 
 
27
  try:
28
- async with httpx.AsyncClient(timeout=10) as client:
29
- resp = await client.get(url)
30
- resp.raise_for_status()
31
- data = resp.json()
 
32
  except Exception:
33
- # In case of any network / parse error
34
- return []
35
-
36
- # Navigate JSON response
37
- # API docs: https://clinicaltrials.gov/api/gui/ref/study_fields
38
- studies = data.get("StudyFieldsResponse", {}).get("StudyFields", [])
39
- output = []
40
- for s in studies:
41
- output.append({
42
- "nctId": s.get("NCTId", [""])[0],
43
- "briefTitle": s.get("BriefTitle", [""])[0],
44
- "phase": s.get("Phase", [""])[0],
45
- "status": s.get("OverallStatus", [""])[0],
46
- })
47
- return output
 
1
+ # mcp/clinicaltrials.py
2
+ import httpx, random
 
 
3
 
4
+ V2_URL = "https://clinicaltrials.gov/api/v2/studies"
5
+ V1_URL = "https://clinicaltrials.gov/api/query/study_fields"
6
+ UA_LIST = [
7
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64)…Chrome/125…",
8
+ "Mozilla/5.0 (Macintosh)…Safari/605…",
9
+ "Mozilla/5.0 (X11)…Firefox/126…"
10
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ async def search_trials(term: str, max_studies: int = 20) -> list[dict]:
13
+ ua = random.choice(UA_LIST)
14
  try:
15
+ async with httpx.AsyncClient(headers={"User-Agent": ua}, timeout=12) as c:
16
+ r = await c.get(V2_URL, params={"query": term, "pageSize": max_studies})
17
+ if r.status_code == 200:
18
+ return r.json().get("studies", [])
19
+ raise httpx.HTTPStatusError("v2 failed", request=r.request, response=r)
20
  except Exception:
21
+ params = {
22
+ "expr": term,
23
+ "fields": "NCTId,BriefTitle,Phase,OverallStatus,StartDate",
24
+ "max_rnk": max_studies,
25
+ "min_rnk": 1,
26
+ "fmt": "json"
27
+ }
28
+ async with httpx.AsyncClient(headers={"User-Agent": ua}, timeout=12) as c:
29
+ r = await c.get(V1_URL, params=params)
30
+ r.raise_for_status()
31
+ return r.json().get("StudyFieldsResponse", {}).get("StudyFields", [])