mgbam commited on
Commit
a130367
·
verified ·
1 Parent(s): 7186f2c

Update mcp/clinicaltrials.py

Browse files
Files changed (1) hide show
  1. mcp/clinicaltrials.py +43 -30
mcp/clinicaltrials.py CHANGED
@@ -1,34 +1,47 @@
1
- # mcp/clinicaltrials.py
 
 
 
2
 
3
- from pytrials.client import ClinicalTrials
4
- import asyncio
5
 
6
- async def fetch_clinical_trials(query: str, max_studies: int = 10) -> list[dict]:
 
 
 
7
  """
8
- Pulls NCTId, Title, Phase, and Status for studies matching the given query.
9
- Uses the pytrials wrapper over ClinicalTrials.gov.
10
  """
11
- # pytrials expects a direct search expression, e.g. disease MeSH term or drug
12
- client = ClinicalTrials()
13
- # These are the fields you want from the API
14
- study_fields = ["NCTId", "BriefTitle", "Phase", "OverallStatus"]
15
- # Wrap in a ThreadPool so we can call it in asyncio
16
- loop = asyncio.get_event_loop()
17
- records = await loop.run_in_executor(
18
- None,
19
- lambda: client.get_study_fields(
20
- search_expr=query,
21
- fields=study_fields,
22
- max_studies=max_studies
23
- )
24
- )
25
- # Normalize the field names for your UI
26
- return [
27
- {
28
- "nctId": rec.get("NCTId"),
29
- "briefTitle": rec.get("BriefTitle"),
30
- "phase": rec.get("Phase"),
31
- "status": rec.get("OverallStatus"),
32
- }
33
- for rec in records
34
- ]
 
 
 
 
 
 
 
 
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