AgentAPIGate
NLM REST API v2 · Python & Cursor Pagination · -96% Token Biomedical MCP

ClinicalTrials.gov API v2 Guide: Python, JSON Schema & Claude MCP

Direct Answer (BLUF · Cost, Rate Limits & Token Math)

The official NLM ClinicalTrials.gov REST API v2 (https://clinicaltrials.gov/api/v2/studies) is free with no API key (~50 requests/minute per IP before HTTP 429, max pageSize=1000 via cursor pageToken), but raw protocolSection payloads average 1,818 tokens per NCT study (86,313 tokens across a 10-study search) and routinely overflow LLM context windows. Calling AgentAPIGate’s /v1/biomed/clinical_trials/search ($0.0005/call, 45 ms p50) and /v1/gov/clinical_trials/detail ($0.0010/call, 38 ms p50, $0.00 on empty/error or X-Sandbox: 1) strips nested AdverseEvents/OutcomeMeasures bloat into 84-token study Markdown (-96% to -99% LLM context cost) across REST, Python, and Remote Claude MCP.

“About 50 requests per minute from the same IP address are allowed; exceeding the limit returns HTTP 429 Too Many Requests. Set countTotal=true and iterate nextPageToken with pageToken (up to pageSize=1000 studies per page) to paginate ClinicalTrials.gov API v2 results.”
Primary Source: U.S. National Library of Medicine — ClinicalTrials.gov REST API v2 Specificationclinicaltrials.gov/data-api/api ↗
Interactive Micro-Tool · Zero Login Required

NCT Trial Filter & Eligibility Criteria JSON Explorer

Filter real ClinicalTrials.gov v2 studies by condition, phase, and recruitment status, inspect structured inclusion/exclusion criteria, or fire a live $0.00 X-Sandbox: 1 request.

Presets:
Parsed Eligibility (NCT04280705)Open Endpoint →
Inclusion Criteria (4)
  • Admitted to a hospital with symptoms suggestive of COVID-19 infection.
  • Male or non-pregnant female adult >= 18 years of age at time of enrollment.
  • Laboratory-confirmed SARS-CoV-2 infection by PCR in specimen collected < 72 hours prior to randomization.
  • Signed informed consent from participant or legally authorized representative.
Exclusion Criteria (4)
  • ALT or AST > 5 times the upper limit of normal (ULN).
  • Estimated glomerular filtration rate (eGFR) < 30 mL/min or need for hemodialysis/hemofiltration.
  • Pregnancy or breastfeeding at screening.
  • Anticipated discharge from hospital or transfer within 72 hours.
Raw v2 JSON: 1,818 tokens → Agent Markdown: 84 tokens (-95%)$0.0010/call · 38 ms p50
{
  "ok": true,
  "meta": {
    "endpoint": "gov.clinical_trials.detail",
    "format": "json",
    "cost_usd": 0.001,
    "tokens_est": 70,
    "raw_tokens_est": 1818,
    "cached": false,
    "source_url": "https://clinicaltrials.gov/study/NCT04280705"
  },
  "data": {
    "nct_id": "NCT04280705",
    "brief_title": "Adaptive COVID-19 Treatment Trial (ACTT)",
    "overall_status": "COMPLETED",
    "study_type": "INTERVENTIONAL",
    "phases": [
      "PHASE3"
    ],
    "enrollment_count": 1062,
    "lead_sponsor": "National Institute of Allergy and Infectious Diseases (NIAID)",
    "conditions": [
      "COVID-19",
      "SARS-CoV-2 Hospitalized Adults"
    ],
    "interventions": [
      {
        "type": "DRUG",
        "name": "Remdesivir"
      },
      {
        "type": "OTHER",
        "name": "Placebo"
      }
    ],
    "eligibility_parsed": {
      "inclusion": [
        "Admitted to a hospital with symptoms suggestive of COVID-19 infection.",
        "Male or non-pregnant female adult >= 18 years of age at time of enrollment.",
        "Laboratory-confirmed SARS-CoV-2 infection by PCR in specimen collected < 72 hours prior to randomization.",
        "Signed informed consent from participant or legally authorized representative."
      ],
      "exclusion": [
        "ALT or AST > 5 times the upper limit of normal (ULN).",
        "Estimated glomerular filtration rate (eGFR) < 30 mL/min or need for hemodialysis/hemofiltration.",
        "Pregnancy or breastfeeding at screening.",
        "Anticipated discharge from hospital or transfer within 72 hours."
      ]
    },
    "url": "https://clinicaltrials.gov/study/NCT04280705"
  }
}
Architecture & Token Footprint Benchmark

Direct ClinicalTrials.gov API v2 vs Normalized Agent REST & MCP

Access MethodEndpoint / SurfaceCost & Rate PolicyLLM Token FootprintProduction Tradeoff
Legacy ClinicalTrials.gov v1 XML / Classic APIRetired June 2024 (HTTP 410 / Redirect)Deprecated permanently12,000+ tokens nested XML per studyBroken in legacy biomedical Python notebooks that still request study_fields or /api/query/full_studies.
Direct NLM ClinicalTrials.gov REST API v2GET https://clinicaltrials.gov/api/v2/studies$0 public · ~50 req/min per IP (HTTP 429 above limit)1,818 tokens/study · 86,313 tokens per 10-trial searchAuthoritative raw protocolSection JSON, but floods Claude/GPT context windows without field projection and Markdown stripping.
AgentAPIGate Biomedical Trial SearchGET /v1/biomed/clinical_trials/search$0.0005 / call ($0 on empty/error · $0 X-Sandbox: 1)765 tokens Markdown (-99% vs 86,313 raw tokens)45 ms p50 cached/normalized search returning NCT IDs, phase, status, sponsor, and conditions ready for LLM RAG.
AgentAPIGate NCT Study & Eligibility DetailGET /v1/gov/clinical_trials/detail$0.0010 / call · 300–600 RPM paid concurrency70t compact JSON / 84t Markdown (-96% vs 1,818t raw)38 ms p50 single-NCT lookup extracting clean inclusion/exclusion criteria, drug interventions, enrollment, and dates.
Remote Streamable HTTP MCP Connectorhttps://mcp.agentapigate.ai/mcpOAuth 2.1 / Scoped aag_agent_* daily USD cap~680 tokens lazy 4-tool discovery hub1-command install in Claude Code, Cursor, Windsurf, and ChatGPT exposing biomed_clinical_trials + gov_clinical_trials_detail.
v1 XML Sunset Migration & Cursor Pagination

ClinicalTrials.gov API v2 Query Parameters & Python pageToken Loop

If you are migrating scripts from the retired v1 /api/query/study_fields endpoint or calling NLM directly in Python, map legacy rank parameters to v2 cursor tokens and field projections as follows:

v2 ParameterRetired v1 EquivalentSample Query StringEngineering Notes
query.condexpr (AREA[Condition])query.cond=Non-Small+Cell+Lung+CancerSearches Condition/Disease MeSH & free-text fields using Essie expression syntax.
query.intrexpr (AREA[InterventionName])query.intr=Semaglutide+OR+TirzepatideMatches drug, biological, device, or behavioral intervention names and synonyms.
filter.overallStatusRecruiting status flagsfilter.overallStatus=RECRUITING,NOT_YET_RECRUITINGComma-separated uppercase enum values (RECRUITING, ACTIVE_NOT_RECRUITING, COMPLETED, TERMINATED).
pageSize & pageTokenmin_rnk & max_rnk (1–1000)pageSize=100&pageToken=NF0g5B...Replaces rank offsets; pass nextPageToken from the prior JSON page until nextPageToken is omitted.
fieldsfields (study_fields)fields=NCTId,BriefTitle,OverallStatus,EligibilityModuleProjects specific protocolSection modules so responses omit multi-megabyte adverse-event tables.
Direct NLM v2 Cursor Pagination in Python (50 RPM Backoff + Field Projection)Python 3.10+ · requests
import time
import requests

BASE_V2 = "https://clinicaltrials.gov/api/v2/studies"

def iter_recruiting_trials(condition: str, max_pages: int = 3):
    params = {
        "query.cond": condition,
        "filter.overallStatus": "RECRUITING",
        "fields": "NCTId,BriefTitle,OverallStatus,Phase,LeadSponsorName,EligibilityModule",
        "countTotal": "true",
        "pageSize": 100,
    }
    for _ in range(max_pages):
        resp = requests.get(BASE_V2, params=params, timeout=20)
        if resp.status_code == 429:
            # Respect ~50 req/min per-IP ClinicalTrials.gov v2 rate limit
            time.sleep(2.0)
            resp = requests.get(BASE_V2, params=params, timeout=20)
        resp.raise_for_status()
        payload = resp.json()
        for study in payload.get("studies", []):
            yield study
        next_tok = payload.get("nextPageToken")
        if not next_tok:
            break
        params["pageToken"] = next_tok
        params.pop("countTotal", None)  # Only request totalCount on page 1
Recorded Production Receipt · gov.clinical_trials.detail

Normalized NCT Study JSON Receipt (NCT04280705)

Every response from GET /v1/gov/clinical_trials/detail includes deterministic cost headers (X-AAG-Cost-USD: 0.0010), token estimates (raw_tokens_est: 1818 → tokens_est: 214 JSON / 84 Markdown), and prompt-injection provenance markers (content_trust: "external_untrusted"):

HTTP 200 OK · GET /v1/gov/clinical_trials/detail?nct_id=NCT04280705X-AAG-Cost-USD: 0.0010 · 38 ms p50 · -96% Tokens in ?format=md
{
  "ok": true,
  "meta": {
    "request_id": "req_ctv2_91f4c802e71a4d11",
    "endpoint": "gov.clinical_trials.detail",
    "format": "json",
    "cost_usd": 0.001,
    "tokens_est": 214,
    "raw_tokens_est": 1818,
    "latency_ms": 38,
    "cached": true,
    "source_url": "https://clinicaltrials.gov/study/NCT04280705",
    "content_trust": "external_untrusted"
  },
  "data": {
    "nct_id": "NCT04280705",
    "brief_title": "Adaptive COVID-19 Treatment Trial (ACTT)",
    "overall_status": "COMPLETED",
    "start_date": "2020-02-21",
    "completion_date": "2020-05-21",
    "study_type": "INTERVENTIONAL",
    "phases": [
      "PHASE3"
    ],
    "enrollment_count": 1062,
    "lead_sponsor": "National Institute of Allergy and Infectious Diseases (NIAID)",
    "conditions": [
      "COVID-19"
    ],
    "interventions": [
      {
        "type": "OTHER",
        "name": "Placebo"
      },
      {
        "type": "DRUG",
        "name": "Remdesivir"
      }
    ],
    "eligibility_criteria": "Inclusion Criteria: 1. Admitted to a hospital with symptoms suggestive of COVID-19 infection... Male or non-pregnant female adult >= 18 years of age... Laboratory-confirmed SARS-CoV-2 infection by PCR < 72 hours prior to randomization.",
    "url": "https://clinicaltrials.gov/study/NCT04280705"
  }
}
Endpoint Explorer · $0.001/call

gov.clinical_trials.detail →

Interactive 3-pane endpoint reference for fetching full NCT protocol, interventions, sponsor, and eligibility criteria by NCT ID.

Search Endpoint · $0.0005/call

biomed.clinical_trials.search →

Search recruiting and completed trials across conditions, GLP-1/oncology interventions, phases, and academic or pharma sponsors.

Remote Streamable HTTP MCP

1-Click Biomedical & Research MCP →

Combine ClinicalTrials.gov v2 with OpenAlex, PubMed, openFDA, and SEC filings under one scoped aag_agent_* budget key.

ClinicalTrials.gov API v2 & MCP Frequently Asked Questions

Is the ClinicalTrials.gov API v2 free, and what is its rate limit?

Yes. The U.S. National Library of Medicine (NLM) provides ClinicalTrials.gov REST API v2 at https://clinicaltrials.gov/api/v2/studies free of charge without an API key, subject to a rate limit of roughly 50 requests per minute per IP address (returning HTTP 429 above that threshold). When deploying multi-agent RAG pipelines that also need 96%–99% LLM token compression, response caching, scoped USD sub-key caps, and unified MCP access alongside PubMed/OpenAlex/openFDA, AgentAPIGate exposes /v1/biomed/clinical_trials/search ($0.0005/call) and /v1/gov/clinical_trials/detail ($0.0010/call).

Why did my old ClinicalTrials.gov /api/query/study_fields Python script stop working?

NLM permanently retired the classic ClinicalTrials.gov v1 XML and study_fields endpoints in June 2024. Legacy min_rnk/max_rnk rank pagination and study_fields parameters must be migrated to REST API v2 (/api/v2/studies and /api/v2/studies/{nctId}), which uses camelCase nested protocolSection JSON, uppercase status enums (such as RECRUITING), and opaque nextPageToken cursor pagination.

How do I connect ClinicalTrials.gov API v2 to Claude Code, Cursor, or ChatGPT via MCP?

Run claude mcp add --transport http agentapigate https://mcp.agentapigate.ai/mcp in your terminal. Claude Code immediately gains access to biomed_clinical_trials (search by disease, drug intervention, or sponsor) and gov_clinical_trials_detail (structured protocol, interventions, and inclusion/exclusion criteria by NCT ID) with ?format=md reducing raw study JSON from ~1,818 tokens to ~84 tokens.

Can I test ClinicalTrials.gov endpoints on AgentAPIGate for $0.00 without signing up?

Yes. Pass the header X-Sandbox: 1 (or query parameter ?sandbox=1) to /v1/gov/clinical_trials/detail?nct_id=NCT04280705&sandbox=1 or /v1/biomed/clinical_trials/search?query=GLP-1+obesity&sandbox=1 to replay authentic recorded ClinicalTrials.gov v2 fixtures at $0.00 with zero API key required.