Update mcp/clinicaltrials.py
Browse files- mcp/clinicaltrials.py +27 -43
mcp/clinicaltrials.py
CHANGED
@@ -1,47 +1,31 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
Fetch clinical trials from ClinicalTrials.gov without external clients.
|
4 |
-
"""
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
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=
|
29 |
-
|
30 |
-
|
31 |
-
|
|
|
32 |
except Exception:
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
"
|
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", [])
|
|
|
|
|
|
|
|