All connectors

ClinicalTrials.gov

Official

ClinicalTrials.gov

Let agents search clinical studies by condition, treatment, location, sponsor, phase or recruitment status, then read eligibility, contacts, study design and posted results. Access is read-only and requires no account.

Credit ClinicalTrials.gov, U.S. National Library of Medicine when sharing results. The registry's terms apply. This connector is not affiliated with the National Library of Medicine.

Add ClinicalTrials.gov.

Setup instructions

Add ClinicalTrials.gov

Select Add connection in Houston. No account, API key or settings are required.

Study IDs use NCT followed by eight digits, such as NCT04368728. If a study was merged, use the replacement ID reported in the error.

ClinicalTrials.gov API guide.

Files

  • connector.luau
    -- ClinicalTrials.gov data API v2, public and read-only. Arguments and results keep ClinicalTrials.gov's native field names.
    type Options = {[string]: any}
    
    local API = "https://clinicaltrials.gov/api/v2"
    -- The first page stays small because record sizes vary widely; later pages grow to fit the budget.
    local DEFAULT_LIMIT, MAX_LIMIT, FIRST_PAGE, PAGE_SIZE, MAX_PAGES = 50, 2000, 50, 1000, 10
    local MAX_BYTES = 4 * 1024 * 1024
    local MAX_TEXT, MAX_IDS = 2000, 500
    -- Bounds the encoded criteria, which go in every page URL and the sealed continuation token.
    local MAX_QUERY = 8192
    local SUMMARY_FIELDS = table.freeze({"NCTId", "BriefTitle", "OverallStatus", "Phase", "StudyType", "Condition",
    	"InterventionName", "LeadSponsorName", "EnrollmentCount", "StartDate", "PrimaryCompletionDate", "HasResults"})
    local STATUSES = table.freeze({"ACTIVE_NOT_RECRUITING", "COMPLETED", "ENROLLING_BY_INVITATION", "NOT_YET_RECRUITING",
    	"RECRUITING", "SUSPENDED", "TERMINATED", "WITHDRAWN", "AVAILABLE", "NO_LONGER_AVAILABLE",
    	"TEMPORARILY_NOT_AVAILABLE", "APPROVED_FOR_MARKETING", "WITHHELD", "UNKNOWN"})
    -- Essie expressions passed as single strings.
    local TEXT_PARAMS = table.freeze({"query.cond", "query.term", "query.intr", "query.locn", "query.titles", "query.outc",
    	"query.spons", "query.lead", "query.id", "query.patient", "filter.geo", "filter.advanced"})
    
    local function text(value: any, field: string): string
    	assert(type(value) == "string" and value ~= "" and #value <= MAX_TEXT,
    		field .. " must be a nonempty string of at most " .. tostring(MAX_TEXT) .. " bytes")
    	return value
    end
    
    local function isNctId(value: any): boolean
    	return type(value) == "string" and string.match(value, "^NCT%d%d%d%d%d%d%d%d$") ~= nil
    end
    
    -- A list option takes an array or one string separated by commas or pipes.
    local function list(value: any, field: string, check: (string) -> boolean, maximum: number): {string}
    	local items: {string} = {}
    	if type(value) == "string" then
    		for item in string.gmatch(value, "[^,|]+") do
    			local trimmed = string.match(item, "^%s*(.-)%s*$") :: string
    			if trimmed ~= "" then table.insert(items, trimmed) end
    		end
    	else
    		assert(type(value) == "table", field .. " must be a string or an array of strings")
    		for index, item in value do
    			assert(index == #items + 1 and type(item) == "string", field .. " must be a dense array of strings")
    			table.insert(items, item)
    		end
    	end
    	assert(#items > 0 and #items <= maximum, field .. " must list 1 to " .. tostring(maximum) .. " values")
    	for _, item in items do
    		assert(check(item), field .. " contains an invalid value: " .. string.sub(item, 1, 64))
    	end
    	return items
    end
    
    local function fieldName(name: string): boolean
    	return #name <= 200 and string.match(name, "^%a[%w%-%. ]*$") ~= nil
    end
    
    local function searchField(name: string): boolean
    	return name == "@query" or fieldName(name)
    end
    
    -- A sort key is Field or Field:asc|desc, for a dotted field name or @relevance.
    local function sortKey(key: string): boolean
    	local field, direction = string.match(key, "^(.*):(%a+)$")
    	if field == nil then
    		field = key
    	elseif direction ~= "asc" and direction ~= "desc" then
    		return false
    	end
    	return #key <= 200 and (field == "@relevance" or string.match(field :: string, "^%a[%w%.]*$") ~= nil)
    end
    
    -- Lists sent comma-separated, with each value's check and the most values allowed.
    local LIST_PARAMS: {[string]: {check: (string) -> boolean, maximum: number}} = table.freeze({
    	["filter.overallStatus"] = {check = function(item: string): boolean return table.find(STATUSES, item) ~= nil end, maximum = #STATUSES},
    	["filter.ids"] = {check = isNctId, maximum = MAX_IDS},
    	sort = {check = sortKey, maximum = 2},
    })
    
    local function failure(name: string, response: HttpResponse, id: string?): never
    	local status = response.statusCode
    	local message
    	if status >= 300 and status < 400 then
    		response.body:close()
    		local location = response.headers.location
    		-- An alias redirects to the current study, by relative or absolute URL, with or without a query.
    		local path = if location and location[1] then string.match(location[1], "^[^?#]*") :: string else ""
    		if string.sub(path, 1, 26) == "https://clinicaltrials.gov" then path = string.sub(path, 27) end
    		local target = string.match(path, "^/api/v2/studies/(NCT%d%d%d%d%d%d%d%d)$")
    		message = if target and id
    			then "ClinicalTrials.gov HTTP " .. tostring(status) .. ": " .. id .. " is an alias of " .. target .. "; call getStudy with " .. target
    			else "ClinicalTrials.gov HTTP " .. tostring(status) .. ": unexpected redirect"
    	else
    		-- Errors are plain text; keep a bounded snippet that ends on a whole UTF-8 character.
    		local snippet = string.match(string.gsub(await(response.body:readPrefix(300)), "%s+", " "), "^ ?(.-) ?$") :: string
    		local valid, invalid = utf8.len(snippet)
    		if not valid and invalid then snippet = string.sub(snippet, 1, invalid - 1) end
    		message = "ClinicalTrials.gov HTTP " .. tostring(status) .. (if snippet == "" then "" else ": " .. snippet)
    	end
    	local retry = response.headers["retry-after"]
    	if (status == 429 or status == 503) and retry and retry[1] then
    		-- Retry-After is either delay seconds or an HTTP date.
    		local value = string.sub(retry[1], 1, 32)
    		message ..= "; retry after " .. value .. (if string.match(value, "^%d+$") then "s" else "")
    	end
    	return houston.fail({operation = name, layer = "upstream", upstream_status = status,
    		retryable = status == 429 or status >= 500, message = message})
    end
    
    -- Returns the decoded JSON object and the bytes read. A body over budget fails, or returns nil when partial.
    local function fetch(name: string, target: string, budget: number, id: string?, partial: boolean?): (any, number)
    	local response = await(http.request({method = "GET", url = target, headers = {Accept = {"application/json"}}}))
    	if response.statusCode ~= 200 then failure(name, response, id) end
    	local read, raw = pcall(function() return await(response.body:readAll(budget)) end)
    	if not read then
    		local code: any = if type(raw) == "table" then (raw :: any).code else nil
    		if code == "limit_exceeded" and partial then
    			return nil, 0
    		elseif code == "limit_exceeded" then
    			houston.fail({operation = name, layer = "upstream", upstream_status = 200, retryable = false,
    				message = "ClinicalTrials.gov returned more data than one call can hold; request fewer fields or a lower limit"})
    		elseif code == "cancelled" or code == "timeout" then
    			error(raw, 0)
    		end
    		local detail = if type(raw) == "table" and type(raw.message) == "string" then raw.message else tostring(raw)
    		houston.fail({operation = name, layer = "upstream", upstream_status = 200, retryable = true,
    			message = "ClinicalTrials.gov response failed: " .. string.sub(detail, 1, 300)})
    	end
    	local ok, value = pcall(json.decode, raw)
    	if not ok or type(value) ~= "table" or not string.match(raw, "^%s*{") then
    		houston.fail({operation = name, layer = "upstream", upstream_status = 200, retryable = false,
    			message = "ClinicalTrials.gov returned an invalid JSON object"})
    	end
    	return value, #raw
    end
    
    local function options(value: any, name: string): Options
    	assert(value == nil or type(value) == "table", name .. " options must be a table")
    	return table.clone((value or {}) :: Options)
    end
    
    local function fieldsParam(args: Options, check: (string) -> boolean, default: {string}?): string?
    	local value = args.fields
    	args.fields = nil
    	if value == nil and default == nil then return nil end
    	local fields = if value == nil then default :: {string} else list(value, "fields", check, 200)
    	return "fields=" .. url.encode(table.concat(fields, ","))
    end
    
    -- Builds the search's fixed query string; only pageSize, countTotal and pageToken vary between pages.
    local function searchQuery(args: Options): string
    	local query: {string} = {}
    	for _, field in TEXT_PARAMS do
    		if args[field] ~= nil then table.insert(query, field .. "=" .. url.encode(text(args[field], field))) end
    		args[field] = nil
    	end
    	for field, rule in LIST_PARAMS do
    		if args[field] ~= nil then
    			table.insert(query, field .. "=" .. url.encode(table.concat(list(args[field], field, rule.check, rule.maximum), ",")))
    		end
    		args[field] = nil
    	end
    	table.insert(query, fieldsParam(args, searchField, SUMMARY_FIELDS) :: string)
    	table.sort(query)
    	local encoded = table.concat(query, "&")
    	assert(#encoded <= MAX_QUERY, "search criteria are too long: " .. tostring(#encoded) .. " bytes once URL-encoded, at most " .. tostring(MAX_QUERY))
    	return encoded
    end
    
    local function searchStudies(input: Options?)
    	local args = options(input, "searchStudies")
    	local limit = if args.limit == nil then DEFAULT_LIMIT else args.limit
    	assert(type(limit) == "number" and limit % 1 == 0 and limit >= 1 and limit <= MAX_LIMIT,
    		"limit must be an integer from 1 to " .. tostring(MAX_LIMIT))
    	args.limit = nil
    	local query: string, token: string?, countTotal = "", nil, false
    	if args.pageToken ~= nil then
    		local ok, cursor = pcall(houston.unseal, args.pageToken)
    		assert(ok and type(cursor) == "table" and cursor.operation == "searchStudies" and type(cursor.query) == "string"
    			and type(cursor.token) == "string", "pageToken must be the nextPageToken of an earlier searchStudies result")
    		args.pageToken = nil
    		assert(next(args) == nil, "pageToken continues an earlier search with its own criteria; pass only pageToken and limit")
    		query, token = cursor.query, cursor.token
    	else
    		if args.countTotal ~= nil then
    			assert(type(args.countTotal) == "boolean", "countTotal must be a boolean")
    			countTotal = args.countTotal
    			args.countTotal = nil
    		end
    		query = searchQuery(args)
    		local unknown = next(args)
    		assert(unknown == nil, "searchStudies received an unknown option " .. string.sub(tostring(unknown), 1, 64))
    	end
    	local studies = json.decode("[]")
    	local result: Options = {studies = studies}
    	local used = 0
    	for page = 1, MAX_PAGES do
    		local size = math.min(limit - #studies, if page == 1 then FIRST_PAGE else PAGE_SIZE)
    		if page > 1 then
    			-- Size later pages from the bytes per study so far, so they fit the remaining budget.
    			size = math.min(size, (MAX_BYTES - used) // (2 * used / #studies))
    			if size < 1 then break end
    		end
    		local target = API .. "/studies?" .. query .. "&pageSize=" .. tostring(size)
    			.. (if countTotal and page == 1 then "&countTotal=true" else "")
    			.. (if token then "&pageToken=" .. url.encode(token) else "")
    		-- After the first page, an oversized page ends the call; its token stays for the continuation.
    		local body, bytes = fetch("searchStudies", target, MAX_BYTES - used, nil, page > 1)
    		if body == nil then break end
    		used += bytes
    		if type(body.studies) ~= "table" or (body.nextPageToken ~= nil and type(body.nextPageToken) ~= "string") then
    			houston.fail({operation = "searchStudies", layer = "upstream", upstream_status = 200, retryable = false,
    				message = "ClinicalTrials.gov returned an unexpected search page"})
    		end
    		if page == 1 and body.totalCount ~= nil then result.totalCount = body.totalCount end
    		for _, study in body.studies do table.insert(studies, study) end
    		-- An exactly full last page still carries a token, followed by an empty page.
    		token = if #body.studies > 0 and body.nextPageToken ~= "" then body.nextPageToken else nil
    		if token == nil or #studies >= limit then break end
    	end
    	if token then
    		result.nextPageToken = houston.seal({operation = "searchStudies", query = query, token = token})
    	end
    	return result
    end
    
    local function getStudy(id: any, input: Options?)
    	local args = options(input, "getStudy")
    	if type(id) == "table" then
    		assert(input == nil, "getStudy takes (nctId, opts?) or one table with nctId")
    		args = options(id, "getStudy")
    		id = args.nctId
    		args.nctId = nil
    	end
    	assert(isNctId(id), "nctId must be NCT followed by 8 digits, such as NCT04368728")
    	local fields = fieldsParam(args, fieldName, nil)
    	local unknown = next(args)
    	assert(unknown == nil, "getStudy received an unknown option " .. string.sub(tostring(unknown), 1, 64))
    	assert(fields == nil or #fields <= MAX_QUERY, "fields is too long once URL-encoded, at most " .. tostring(MAX_QUERY) .. " bytes")
    	local target = API .. "/studies/" .. id .. (if fields then "?" .. fields else "")
    	return (fetch("getStudy", target, MAX_BYTES, id))
    end
    
    local function help(): string
    	return [[ClinicalTrials.gov: search and read the public registry of clinical studies (data API v2, https://clinicaltrials.gov/data-api/api). No account or credentials. Read-only. Calls return completed values; do not wrap them in await(). Records keep ClinicalTrials.gov's JSON unchanged: protocolSection (identification, status, sponsor, description, conditions, design, arms and interventions, outcomes, eligibility, contacts and locations), resultsSection (participant flow, baseline, outcome measures, adverse events), derivedSection (MeSH terms) and hasResults. Data refreshes Monday to Friday. Credit "Source: ClinicalTrials.gov, U.S. National Library of Medicine" when presenting results.
    
    ## searchStudies(opts?)
    
    GET /api/v2/studies. Returns `{studies, totalCount?, nextPageToken?}`. Options use the API's own names (quote dotted keys: `["query.cond"] = "..."`); unknown options are rejected.
    - Essie text queries, which also rank by relevance: query.cond (condition or disease), query.intr (intervention or treatment), query.locn (city, state, country or facility), query.term (any field), query.titles, query.outc (outcome measures), query.spons (any sponsor), query.lead (lead sponsor), query.id (NCT and other study IDs), query.patient (patient-oriented search). Essie supports AND, OR, NOT, quotes and AREA[Field]value, for example `["query.cond"] = "lung cancer AND NOT small cell"`.
    - filter.overallStatus: array or comma-separated string of RECRUITING, NOT_YET_RECRUITING, ENROLLING_BY_INVITATION, ACTIVE_NOT_RECRUITING, COMPLETED, SUSPENDED, TERMINATED, WITHDRAWN, UNKNOWN, and for expanded access AVAILABLE, NO_LONGER_AVAILABLE, TEMPORARILY_NOT_AVAILABLE, APPROVED_FOR_MARKETING, WITHHELD.
    - filter.advanced: an Essie expression. There is no phase parameter: filter phases with `["filter.advanced"] = "AREA[Phase](PHASE2 OR PHASE3)"` (NA, EARLY_PHASE1, PHASE1, PHASE2, PHASE3, PHASE4). Other examples: `AREA[StudyType]INTERVENTIONAL`, `AREA[HasResults]true`, `AREA[LastUpdatePostDate]RANGE[2025-01-01,MAX]`, `AREA[MinimumAge]RANGE[MIN, 16 years]`; combine with AND.
    - filter.geo: `distance(42.36,-71.06,25mi)` (km also accepted). filter.ids: up to 500 NCT IDs (aliases match too). A query.* value made only of NCT IDs makes ClinicalTrials.gov ignore every filter, so look IDs up with filter.ids.
    - sort: up to 2 keys such as `LastUpdatePostDate:desc`, `EnrollmentCount:desc` or `@relevance`; only date and numeric fields sort. Without sort and without a text query, order is unspecified.
    - fields: array or comma-separated names of fields, modules or sections, such as `NCTId`, `BriefSummary`, `EligibilityModule`, `ContactsLocationsModule`, `ProtocolSection`, or `@query` (the fields the query matched). Default: NCTId, BriefTitle, OverallStatus, Phase, StudyType, Condition, InterventionName, LeadSponsorName, EnrollmentCount, StartDate, PrimaryCompletionDate, HasResults. Selected fields keep their nested position, for example Phase is protocolSection.designModule.phases.
    - countTotal: true adds totalCount, the number of matching studies.
    - limit: studies to return, 1 to 2000 (default 50). The call pages internally: 50 studies first, then pages of up to 1000 sized to fit.
    - pageToken: pass an earlier result's nextPageToken, with only limit, to continue that same search. nextPageToken is present while more matches may remain: when the last matches exactly fill limit it is still returned, and continuing then returns no studies and no token. A call may return fewer than limit studies when they would exceed one call's size budget; continue with nextPageToken.
    
    ## getStudy(nctId, opts?)
    
    GET /api/v2/studies/{nctId}. Returns one full study record. nctId is NCT plus 8 digits, such as NCT04368728; shorter forms are rejected rather than padded. Also accepts one table `{nctId = ..., fields = ...}`. opts.fields selects parts, like searchStudies fields (without @query): for posted results use `{"ResultsSection"}` or modules such as `OutcomeMeasuresModule`, `AdverseEventsModule`, `ParticipantFlowModule`, `BaselineCharacteristicsModule`. A study without results returns {} for ResultsSection; check hasResults first. Most records are 10 to 50 KB, but some with results exceed 3 MB, so select modules when only part is needed. An unknown ID fails with HTTP 404. An old ID that became an alias fails with HTTP 301 and names the current NCT ID to use.
    
    ## Errors and limits
    
    Invalid options fail before any request, including search criteria or fields over 8 KB once URL-encoded. ClinicalTrials.gov errors (plain text, such as an Essie syntax error or an invalid field name) come back as upstream errors with the HTTP status; HTTP 429 and 5xx are retryable. The API publishes no rate limit: keep calls few and use limit and fields rather than many small requests. Each call reads at most 4 MiB.
    
    ## Example
    
    Here trials is the configured ClinicalTrials.gov connection.
    
    ```lua
    local found = trials.searchStudies({
    	["query.cond"] = "type 2 diabetes",
    	["query.locn"] = "Boston",
    	["filter.overallStatus"] = {"RECRUITING", "NOT_YET_RECRUITING"},
    	["filter.advanced"] = "AREA[Phase](PHASE2 OR PHASE3)",
    	countTotal = true,
    	limit = 50,
    })
    for _, study in found.studies do
    	local id = study.protocolSection.identificationModule
    	print(id.nctId, id.briefTitle)
    end
    -- More: trials.searchStudies({pageToken = found.nextPageToken, limit = 50}) while found.nextPageToken.
    local record = trials.getStudy(found.studies[1].protocolSection.identificationModule.nctId,
    	{fields = {"EligibilityModule", "ContactsLocationsModule"}})
    ```]]
    end
    
    return {searchStudies = searchStudies, getStudy = getStudy, help = help}
    
  • houston.json
    {
      "schema_version": 2,
      "name": "ClinicalTrials.gov",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "proxy": [
        {
          "match": {
            "protocol": "http",
            "host": [
              "clinicaltrials.gov"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/api/v2/studies",
              "/api/v2/studies/{nctId}"
            ]
          },
          "action": {}
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Search and read clinical studies from the public ClinicalTrials.gov registry.
    ---
    
    # ClinicalTrials.gov
    
    Let agents search clinical studies by condition, treatment, location, sponsor,
    phase or recruitment status, then read eligibility, contacts, study design and
    posted results. Access is read-only and requires no account.
    
    Credit **ClinicalTrials.gov, U.S. National Library of Medicine** when sharing
    results. The registry's [terms](https://clinicaltrials.gov/about-site/terms-conditions)
    apply. This connector is not affiliated with the National Library of Medicine.
    
    [Add ClinicalTrials.gov](SETUP.md).
    
  • SETUP.md
    # Add ClinicalTrials.gov
    
    Select **Add connection** in Houston. No account, API key or settings are required.
    
    Study IDs use `NCT` followed by eight digits, such as `NCT04368728`. If a study was
    merged, use the replacement ID reported in the error.
    
    [ClinicalTrials.gov API guide](https://clinicaltrials.gov/data-api/about-api).
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {},
      				endpoint = { "GET", "https://clinicaltrials.gov/api/v2/studies" },
      				expected = "caller-forgery",
      				header = "Authorization",
      				method = "",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • errors.luau
      -- Invalid input never reaches the network; plain-text errors, aliases and bad pages map to clear failures.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		calls = 0
      		status = 200
      		payload = "{}"
      		responseHeaders = {}
      		-- Sealing is native; a table of opaque handles stands in for it.
      		local sealed, count = {}, 0
      		houston = table.clone(houston)
      		houston.seal = function(value)
      			count += 1
      			sealed["sealed:" .. count] = json.encode(value)
      			return "sealed:" .. count
      		end
      		houston.unseal = function(token)
      			assert(type(token) == "string" and sealed[token], "invalid sealed token")
      			return json.decode(sealed[token])
      		end
      		http = {request = function()
      			calls += 1
      			-- A body whose read fails stands in for a dropped connection or a cancelled invocation.
      			local body = if readError then {readAll = function() error(readError, 0) end, close = function() end} else fixture.reader(payload)
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = body})
      		end}
      	end,
      	run = function(trials)
      		local function rejected(fn, expected)
      			local before = calls
      			local ok, err = pcall(fn)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err))
      			assert(calls == before, "invalid input reached ClinicalTrials.gov")
      		end
      		for _, id in {"NCT123", "nct04368728", "NCT123456789", "04368728", "NCT0436872a", "NCT04368728/../x", 4368728, ""} do
      			rejected(function() trials.getStudy(id) end, "nctId must be NCT followed by 8 digits")
      		end
      		rejected(function() trials.getStudy() end, "nctId must be")
      		rejected(function() trials.getStudy({nctId = "NCT04368728"}, {}) end, "takes (nctId, opts?)")
      		rejected(function() trials.getStudy("NCT04368728", {format = "csv"}) end, "unknown option format")
      		rejected(function() trials.getStudy("NCT04368728", {fields = "@query"}) end, "fields contains an invalid value")
      		rejected(function() trials.getStudy("NCT04368728", {fields = {}}) end, "fields must list 1 to 200")
      		rejected(function() trials.getStudy("NCT04368728", {fields = table.create(60, string.rep("A", 150))}) end, "fields is too long")
      		rejected(function() trials.getStudy("NCT04368728", "fields") end, "options must be a table")
      		rejected(function() trials.searchStudies("diabetes") end, "options must be a table")
      		rejected(function() trials.searchStudies({pageSize = 10}) end, "unknown option pageSize")
      		rejected(function() trials.searchStudies({phase = "PHASE3"}) end, "unknown option phase")
      		rejected(function() trials.searchStudies({["query.cond"] = ""}) end, "query.cond must be a nonempty string")
      		rejected(function() trials.searchStudies({["query.cond"] = string.rep("a", 2001)}) end, "at most 2000 bytes")
      		rejected(function() trials.searchStudies({["filter.advanced"] = 3}) end, "filter.advanced must be")
      		rejected(function() trials.searchStudies({["filter.overallStatus"] = "recruiting"}) end, "invalid value: recruiting")
      		rejected(function() trials.searchStudies({["filter.overallStatus"] = {"RECRUITING", 1}}) end, "dense array of strings")
      		rejected(function() trials.searchStudies({["filter.overallStatus"] = {[1] = "RECRUITING", [3] = "COMPLETED"}}) end, "dense array")
      		rejected(function() trials.searchStudies({["filter.overallStatus"] = ", |"}) end, "must list 1 to 14")
      		rejected(function() trials.searchStudies({["filter.ids"] = "NCT04368728,NCT123"}) end, "invalid value: NCT123")
      		rejected(function() trials.searchStudies({["filter.ids"] = table.create(501, "NCT04368728")}) end, "1 to 500")
      		rejected(function()
      			trials.searchStudies({["filter.ids"] = table.create(500, "NCT04368728"), ["query.term"] = string.rep("%", 2000)})
      		end, "search criteria are too long")
      		for _, key in {"BriefTitle:up", "LastUpdatePostDate:", "Last Update", ":desc", "@relevance:"} do
      			rejected(function() trials.searchStudies({sort = {key}}) end, "sort contains an invalid value")
      		end
      		rejected(function() trials.searchStudies({sort = {"A", "B", "C"}}) end, "sort must list 1 to 2")
      		rejected(function() trials.searchStudies({fields = "Bad;Field"}) end, "fields contains an invalid value")
      		rejected(function() trials.searchStudies({countTotal = "true"}) end, "countTotal must be a boolean")
      		for _, limit in {0, 2001, 1.5, "10", false} do
      			rejected(function() trials.searchStudies({limit = limit}) end, "limit must be an integer from 1 to 2000")
      		end
      		rejected(function() trials.searchStudies({pageToken = "ZVJ76sWHmqU2wRk2CJf6"}) end, "nextPageToken of an earlier searchStudies")
      		rejected(function()
      			trials.searchStudies({pageToken = houston.seal({operation = "getStudy", query = "fields=NCTId", token = "t"})})
      		end, "nextPageToken of an earlier searchStudies")
      		rejected(function()
      			trials.searchStudies({pageToken = houston.seal({operation = "searchStudies", query = "fields=NCTId", token = "t"}),
      				["query.cond"] = "asthma"})
      		end, "pass only pageToken and limit")
      
      		local function upstream(code, body, headers, call, expected, absent)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(call)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			if absent then assert(not string.find(tostring(err), absent, 1, true), "unexpected " .. absent .. " in " .. tostring(err)) end
      			assert(calls == before + 1, "a failed request was repeated")
      		end
      		local function search() trials.searchStudies({["query.cond"] = "asthma"}) end
      		local function read() trials.getStudy("NCT05730322") end
      
      		upstream(400, "Error parsing query in advanced filter: Allowed values for enum field `protocolSection.designModule.phases` are `NA`\n", {}, search,
      			{"HTTP 400: Error parsing query in advanced filter: Allowed values", "`NA`", '"retryable":false'}, "\\n")
      		upstream(400, string.rep("y", 1000), {}, search, {"HTTP 400: " .. string.rep("y", 300)}, string.rep("y", 301))
      		upstream(400, string.rep("y", 299) .. "é", {}, search, {"HTTP 400: " .. string.rep("y", 299)})
      		upstream(404, "NCT number NCT05730322 not found", {}, read, {"HTTP 404: NCT number NCT05730322 not found", '"retryable":false'})
      		upstream(404, "", {}, read, {"HTTP 404"}, "HTTP 404:")
      		upstream(301, "", {location = {"/api/v2/studies/NCT03682900"}}, read,
      			{"HTTP 301: NCT05730322 is an alias of NCT03682900; call getStudy with NCT03682900", '"retryable":false'})
      		for _, location in {"https://clinicaltrials.gov/api/v2/studies/NCT03682900", "/api/v2/studies/NCT03682900?fields=NCTId"} do
      			upstream(301, "", {location = {location}}, read, {"NCT05730322 is an alias of NCT03682900; call getStudy with NCT03682900"})
      		end
      		upstream(301, "", {location = {"https://clinicaltrials.gov.example.com/api/v2/studies/NCT03682900"}}, read, {"unexpected redirect"}, "alias")
      		upstream(302, "", {location = {"https://evil.example.com/"}}, read, {"HTTP 302: unexpected redirect"}, "evil")
      		upstream(429, "Too Many Requests", {["retry-after"] = {"7"}}, search, {"HTTP 429", "retry after 7s", '"retryable":true'})
      		upstream(503, "", {["retry-after"] = {"Thu, 29 Oct 2026 20:00:00 GMT"}}, search,
      			{"retry after Thu, 29 Oct 2026 20:00:00 GMT", '"retryable":true'}, "GMTs")
      		upstream(503, "<html>Unavailable</html>", {}, read, {"HTTP 503", '"retryable":true'})
      		upstream(500, "", {}, search, {"HTTP 500", '"retryable":true'})
      		upstream(200, "<html>Maintenance</html>", {}, read, {"invalid JSON object", '"retryable":false'})
      		upstream(200, "[]", {}, read, {"invalid JSON object"})
      		upstream(200, '{"studies":null}', {}, search, {"unexpected search page"})
      		upstream(200, '{"studies":[],"nextPageToken":5}', {}, search, {"unexpected search page"})
      		upstream(200, '{"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}', {}, read, {"more data than one call can hold"})
      		upstream(200, '{"studies":[],"x":"' .. string.rep("z", 4 * 1024 * 1024) .. '"}', {}, search, {"more data than one call can hold"})
      		readError = {code = "io_error", message = "connection reset by peer"}
      		upstream(200, "", {}, search, {"ClinicalTrials.gov response failed: connection reset by peer", '"retryable":true'}, "more data")
      		readError = {code = "cancelled", message = "invocation cancelled"}
      		local before = calls
      		local ok, err = pcall(read)
      		-- A stand-in error loses its native identity across the export boundary; it must still not become an upstream failure.
      		assert(not ok and not string.find(tostring(err), "retryable", 1, true), "cancellation became an upstream error: " .. tostring(err))
      		assert(calls == before + 1)
      		readError = nil
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		-- TestClinicalTrialsPublicReadRoutes
      		do
      			local r, err = m.resolve(nil, nil, nil, "")
      			assert(not err, tostring(err))
      			local api = "https://clinicaltrials.gov/api/v2"
      			for _, route in
      				{
      					"GET " .. api .. "/studies?query.cond=asthma&pageSize=100",
      					"GET " .. api .. "/studies/NCT04368728?fields=ResultsSection",
      				}
      			do
      				m.routes(r, "forged", true, { route })
      			end
      			m.routes(r, "", false, {
      				"POST " .. api .. "/studies",
      				"HEAD " .. api .. "/studies",
      				"GET " .. api .. "/studies/NCT04368728/history",
      				"GET " .. api .. "/stats/size",
      				"GET " .. api .. "/version",
      				"GET https://clinicaltrials.gov/api/legacy/study-fields",
      				"GET https://www.clinicaltrials.gov/api/v2/studies",
      				"GET https://classic.clinicaltrials.gov/api/v2/studies",
      				"GET https://clinicaltrials.gov.example.com/api/v2/studies",
      				"GET http://clinicaltrials.gov:8080/api/v2/studies",
      				"GET " .. api .. "/studies/%2e%2e/version",
      			})
      		end
      	end,
      }
      
    • reads.luau
      -- Searches page inside one call and continue only through sealed tokens; study reads select fields.
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "", auth_config = {}},
      	configure = function()
      		requests, responses = {}, {}
      		-- Sealing is native; a table of opaque handles stands in for it.
      		local sealed, count = {}, 0
      		houston = table.clone(houston)
      		houston.seal = function(value)
      			count += 1
      			sealed["sealed:" .. count] = json.encode(value)
      			return "sealed:" .. count
      		end
      		houston.unseal = function(token)
      			assert(type(token) == "string" and sealed[token], "invalid sealed token")
      			return json.decode(sealed[token])
      		end
      		http = {request = function(req)
      			table.insert(requests, req)
      			assert(req.method == "GET" and req.body == nil, "ClinicalTrials.gov reads must be bodiless GETs")
      			assert(req.headers.Authorization == nil, "the public API takes no credentials")
      			assert(req.headers.Accept[1] == "application/json")
      			assert(#responses > 0, "unexpected request: " .. req.url)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(table.remove(responses, 1))})
      		end}
      		function respond(body) table.insert(responses, body) end
      	end,
      	run = function(trials)
      		local API = "https://clinicaltrials.gov/api/v2"
      		local SUMMARY = "fields=NCTId%2CBriefTitle%2COverallStatus%2CPhase%2CStudyType%2CCondition%2CInterventionName%2CLeadSponsorName%2CEnrollmentCount%2CStartDate%2CPrimaryCompletionDate%2CHasResults"
      		local function study(id) return '{"protocolSection":{"identificationModule":{"nctId":"' .. id .. '"}},"hasResults":false}' end
      		local function url(i) return requests[i].url end
      
      		local names = {}
      		for name, fn in trials do
      			assert(type(fn) == "function")
      			table.insert(names, name)
      		end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getStudy,searchStudies", table.concat(names, ","))
      		assert(#requests == 0, "initialization reached ClinicalTrials.gov")
      
      		-- Default search: summary fields, default limit, no token when the page has none.
      		respond('{"studies":[' .. study("NCT00000001") .. ']}')
      		local page = trials.searchStudies()
      		assert(url(1) == API .. "/studies?" .. SUMMARY .. "&pageSize=50", url(1))
      		assert(#page.studies == 1 and page.studies[1].protocolSection.identificationModule.nctId == "NCT00000001")
      		assert(page.nextPageToken == nil and page.totalCount == nil)
      
      		-- Every criterion, sorted and encoded; countTotal only on the first page.
      		local opts = {["query.cond"] = "type 2 diabetes", ["query.intr"] = "metformin OR insulin", ["query.locn"] = "Boston",
      			["query.term"] = "AREA[StudyType]INTERVENTIONAL", ["query.titles"] = "t", ["query.outc"] = "o", ["query.spons"] = "s",
      			["query.lead"] = "l", ["query.id"] = "i", ["query.patient"] = "p", ["filter.geo"] = "distance(42.36,-71.06,25mi)",
      			["filter.overallStatus"] = "RECRUITING, NOT_YET_RECRUITING", ["filter.advanced"] = "AREA[Phase](PHASE2 OR PHASE3)",
      			["filter.ids"] = {"NCT04368728", "NCT05730322"}, sort = {"LastUpdatePostDate:desc", "@relevance"},
      			fields = "NCTId|@query", countTotal = true, limit = 3}
      		respond('{"totalCount":388,"studies":[' .. study("NCT04368728") .. "," .. study("NCT05730322") .. '],"nextPageToken":"t+1/="}')
      		respond('{"totalCount":999,"studies":[' .. study("NCT00000003") .. '],"nextPageToken":"t2"}')
      		page = trials.searchStudies(opts)
      		local query = "fields=NCTId%2C%40query&filter.advanced=AREA%5BPhase%5D%28PHASE2%20OR%20PHASE3%29"
      			.. "&filter.geo=distance%2842.36%2C-71.06%2C25mi%29&filter.ids=NCT04368728%2CNCT05730322"
      			.. "&filter.overallStatus=RECRUITING%2CNOT_YET_RECRUITING&query.cond=type%202%20diabetes&query.id=i"
      			.. "&query.intr=metformin%20OR%20insulin&query.lead=l&query.locn=Boston&query.outc=o&query.patient=p"
      			.. "&query.spons=s&query.term=AREA%5BStudyType%5DINTERVENTIONAL&query.titles=t"
      			.. "&sort=LastUpdatePostDate%3Adesc%2C%40relevance"
      		assert(url(2) == API .. "/studies?" .. query .. "&pageSize=3&countTotal=true", url(2))
      		assert(url(3) == API .. "/studies?" .. query .. "&pageSize=1&pageToken=t%2B1%2F%3D", url(3))
      		assert(#page.studies == 3 and page.totalCount == 388, "totalCount comes from the first page")
      		assert(opts.limit == 3 and opts.fields == "NCTId|@query", "caller options were modified")
      
      		-- A sealed token continues the same query, whatever limit the caller picks.
      		respond('{"studies":[' .. study("NCT00000004") .. "]}")
      		local more = trials.searchStudies({pageToken = page.nextPageToken, limit = 10})
      		assert(url(4) == API .. "/studies?" .. query .. "&pageSize=10&pageToken=t2", url(4))
      		assert(#more.studies == 1 and more.nextPageToken == nil and more.totalCount == nil)
      
      		-- An exactly full page keeps a token, then an empty page ends the search.
      		respond('{"studies":[' .. study("NCT00000005") .. '],"nextPageToken":"full"}')
      		respond('{"studies":[],"nextPageToken":"stale"}')
      		page = trials.searchStudies({["query.cond"] = "asthma", limit = 5})
      		assert(url(5) == API .. "/studies?" .. SUMMARY .. "&query.cond=asthma&pageSize=5", url(5))
      		assert(url(6) == API .. "/studies?" .. SUMMARY .. "&query.cond=asthma&pageSize=4&pageToken=full", url(6))
      		assert(#page.studies == 1 and page.nextPageToken == nil, "an empty page must end the search")
      
      		-- Empty results stay an array.
      		respond('{"totalCount":0,"studies":[]}')
      		page = trials.searchStudies({["query.cond"] = "nothing", countTotal = true})
      		assert(json.encode(page.studies) == "[]" and page.totalCount == 0 and page.nextPageToken == nil)
      
      		-- The first page starts small: 1,000 ProtocolSection records are about 11.7 MB, and 100 ResultsSection ones 3.9 MB.
      		local protocol = '{"protocolSection":{"descriptionModule":{"detailedDescription":"' .. string.rep("p", 12 * 1024) .. '"}}}'
      		respond('{"studies":[' .. string.rep(protocol .. ",", 49) .. protocol .. '],"nextPageToken":"r2"}')
      		respond('{"studies":[]}')
      		page = trials.searchStudies({fields = {"ProtocolSection"}, limit = 2000})
      		assert(url(#requests - 1) == API .. "/studies?fields=ProtocolSection&pageSize=50", url(#requests - 1))
      		local grown = tonumber(string.match(url(#requests), "pageSize=(%d+)&pageToken=r2$"))
      		assert(grown and grown > 50 and grown < 1000, "later pages grow within the budget: " .. url(#requests))
      		assert(#page.studies == 50 and page.nextPageToken == nil)
      		protocol, page = nil, nil
      
      		-- Later pages shrink to the remaining byte budget, and stop when nothing more fits.
      		local big = '{"protocolSection":{"descriptionModule":{"briefSummary":"' .. string.rep("x", 1024 * 1024) .. '"}}}'
      		respond('{"studies":[' .. big .. '],"nextPageToken":"p2"}')
      		respond('{"studies":[' .. big .. '],"nextPageToken":"p3"}')
      		local first = #requests + 1
      		page = trials.searchStudies({fields = {"ProtocolSection"}, limit = 2000})
      		assert(#requests == first + 1, "the byte budget must stop paging")
      		for i, expected in {"pageSize=50", "pageSize=1&pageToken=p2"} do
      			assert(url(first + i - 1) == API .. "/studies?fields=ProtocolSection&" .. expected, url(first + i - 1))
      		end
      		assert(#page.studies == 2 and page.nextPageToken ~= nil, "a budget stop keeps the continuation token")
      		local token = page.nextPageToken
      		big, page = nil, nil
      		respond('{"studies":[' .. study("NCT00000010") .. "]}")
      		trials.searchStudies({pageToken = token})
      		assert(url(#requests) == API .. "/studies?fields=ProtocolSection&pageSize=50&pageToken=p3", url(#requests))
      
      		-- A later page over the remaining budget ends the call with what was collected and that page's token.
      		local medium = '{"protocolSection":{"descriptionModule":{"briefSummary":"' .. string.rep("m", 512 * 1024) .. '"}}}'
      		respond('{"studies":[' .. medium .. '],"nextPageToken":"q2"}')
      		respond('{"studies":[{"x":"' .. string.rep("o", 3584 * 1024) .. '"}],"nextPageToken":"q3"}')
      		page = trials.searchStudies({fields = {"ProtocolSection"}, limit = 2000})
      		assert(url(#requests) == API .. "/studies?fields=ProtocolSection&pageSize=3&pageToken=q2", url(#requests))
      		assert(#page.studies == 1 and page.nextPageToken ~= nil, "collected studies were discarded")
      		token, medium, page = page.nextPageToken, nil, nil
      		respond('{"studies":[]}')
      		trials.searchStudies({pageToken = token, limit = 1})
      		assert(url(#requests) == API .. "/studies?fields=ProtocolSection&pageSize=1&pageToken=q2", url(#requests))
      
      		-- Study reads: full record, selected modules, and the table form.
      		respond('{"protocolSection":{"identificationModule":{"nctId":"NCT04368728"}},"resultsSection":{},"hasResults":true}')
      		local record = trials.getStudy("NCT04368728")
      		assert(url(#requests) == API .. "/studies/NCT04368728", url(#requests))
      		assert(record.hasResults == true and record.protocolSection.identificationModule.nctId == "NCT04368728")
      		respond('{"resultsSection":{"outcomeMeasuresModule":{"outcomeMeasures":[]}}}')
      		record = trials.getStudy("NCT04368728", {fields = {"OutcomeMeasuresModule", "AdverseEventsModule"}})
      		assert(url(#requests) == API .. "/studies/NCT04368728?fields=OutcomeMeasuresModule%2CAdverseEventsModule", url(#requests))
      		assert(json.encode(record.resultsSection.outcomeMeasuresModule.outcomeMeasures) == "[]")
      		respond("{}")
      		local args = {nctId = "NCT00587795", fields = "ResultsSection"}
      		assert(next(trials.getStudy(args)) == nil)
      		assert(url(#requests) == API .. "/studies/NCT00587795?fields=ResultsSection", url(#requests))
      		assert(args.nctId == "NCT00587795" and args.fields == "ResultsSection", "caller table was modified")
      		assert(#responses == 0, "unused responses")
      	end,
      }