clinicaltrialsgov-mcp-server
Servidor público alojado: https://clinicaltrials.caseyjhand.com/mcp
Descripción general
Siete herramientas para buscar, descubrir, analizar y emparejar ensayos clínicos:
Nombre de la herramienta | Descripción |
| Busca estudios con consultas de texto completo, filtros, paginación, ordenación y selección de campos. |
| Obtiene un estudio individual por NCT ID. Devuelve el registro completo: protocolo, elegibilidad, resultados, brazos, intervenciones, contactos y ubicaciones. |
| Obtiene el recuento total de estudios para una consulta sin recuperar datos. Estadísticas rápidas y desgloses. |
| Descubre valores válidos para campos de la API (estado, fase, tipo de estudio, etc.) con recuentos por valor. |
| Explora el árbol de campos del modelo de datos de estudio: nombres de piezas, tipos, anidamiento. Admite navegación por subárboles y búsqueda por palabras clave. |
| Extrae resultados, eventos adversos, flujo de participantes y línea base de estudios completados. El modo de resumen opcional reduce cargas útiles de ~200KB a ~5KB. |
| Empareja datos demográficos y condiciones del paciente con ensayos de reclutamiento elegibles. Proporciona edad, sexo, condiciones y ubicación para encontrar estudios con criterios de elegibilidad, contactos y ubicaciones de reclutamiento coincidentes. |
Recurso | Descripción |
| Obtiene un estudio clínico individual por NCT ID. JSON completo. |
Prompt | Descripción |
| Flujo de trabajo adaptable para el análisis del panorama de ensayos basado en datos utilizando herramientas de recuento + búsqueda. |
Related MCP server: ClinicalTrials.gov MCP Server
Herramientas
clinicaltrials_search_studies
Herramienta de búsqueda principal con capacidades completas de consulta de ClinicalTrials.gov.
Consultas de texto completo y específicas por campo (condición, intervención, patrocinador, ubicación, título, resultado)
Filtros de estado y fase con valores de enumeración tipados
Filtrado de proximidad geográfica por coordenadas y distancia
Soporte avanzado de expresiones Essie AREA[] para consultas complejas
Selección de campos para reducir el tamaño de la carga útil (los registros completos son de ~70KB cada uno)
Paginación con tokens de cursor, ordenación por cualquier campo
clinicaltrials_get_study_results
Obtiene datos de resultados publicados para estudios completados.
Medidas de resultados con estadísticas, eventos adversos, flujo de participantes, características de línea base
Filtrado a nivel de sección (solicita solo los datos que necesitas)
El modo de resumen opcional condensa los resultados completos (~200KB) a metadatos esenciales (~5KB por estudio)
Procesamiento por lotes de múltiples NCT IDs por llamada con informes de éxito parcial
Seguimiento separado de estudios sin resultados y errores de obtención
clinicaltrials_find_eligible
Empareja un perfil de paciente con ensayos de reclutamiento elegibles.
Toma edad, sexo, condiciones y ubicación como datos demográficos del paciente
Crea consultas de API optimizadas con filtros demográficos (rango de edad, sexo, voluntarios sanos)
Devuelve estudios con campos de elegibilidad y ubicación para que el llamador los evalúe
Proporciona sugerencias prácticas cuando no hay estudios coincidentes (ampliar condiciones, ajustar filtros)
Características
Construido sobre @cyanheads/mcp-ts-core:
Definiciones declarativas de herramientas/recursos/prompts con esquemas Zod y funciones de formato
Manejo de errores unificado: los controladores lanzan, el framework captura y clasifica
Transporte dual: stdio y HTTP transmitible desde la misma base de código
Autenticación conectable (
none,jwt,oauth) para transporte HTTPRegistro estructurado con rastreo opcional de OpenTelemetry
Específico de ClinicalTrials.gov:
Cliente con seguridad de tipos para la API REST v2 de ClinicalTrials.gov
API pública: no se requiere autenticación ni claves de API
Reintento con retroceso exponencial (3 intentos) y limitación de tasa (~1 req/seg)
Detección de errores HTML y fábricas de errores estructuradas
Primeros pasos
Instancia pública alojada
Hay una instancia pública disponible en https://clinicaltrials.caseyjhand.com/mcp: no requiere instalación. Apunta cualquier cliente MCP hacia ella mediante HTTP transmitible:
{
"mcpServers": {
"clinicaltrialsgov-mcp-server": {
"type": "streamable-http",
"url": "https://clinicaltrials.caseyjhand.com/mcp"
}
}
}Autoalojado / Local
Agrégalo a la configuración de tu cliente MCP (por ejemplo, claude_desktop_config.json):
{
"mcpServers": {
"clinicaltrialsgov-mcp-server": {
"type": "stdio",
"command": "bunx",
"args": ["clinicaltrialsgov-mcp-server@latest"],
"env": {
"MCP_TRANSPORT_TYPE": "stdio"
}
}
}
}O para HTTP transmitible:
MCP_TRANSPORT_TYPE=http
MCP_HTTP_PORT=3010Requisitos previos
Bun v1.2.0 o superior (o Node.js >= 22.0.0)
Instalación
Clona el repositorio:
git clone https://github.com/cyanheads/clinicaltrialsgov-mcp-server.gitNavega al directorio:
cd clinicaltrialsgov-mcp-serverInstala las dependencias:
bun install
Configuración
Toda la configuración es opcional: el servidor funciona con valores predeterminados y sin claves de API.
Variable | Descripción | Predeterminado |
| URL base de la API de ClinicalTrials.gov. |
|
| Tiempo de espera por solicitud en milisegundos. |
|
| Límite máximo de tamaño de página. |
|
| Transporte: |
|
| Puerto para el servidor HTTP. |
|
| Modo de autenticación: |
|
| Nivel de registro (RFC 5424). |
|
| Directorio para archivos de registro (solo Node.js). |
|
| Habilitar rastreo de OpenTelemetry. |
|
Ejecución del servidor
Desarrollo local
Compila y ejecuta la versión de producción:
bun run build bun run start:http # or start:stdioEjecuta en modo de desarrollo (con watch):
bun run dev:http # or dev:stdioEjecuta comprobaciones y pruebas:
bun run devcheck # Lints, formats, type-checks bun run test # Runs test suite
Docker
docker build -t clinicaltrialsgov-mcp-server .
docker run -p 3010:3010 clinicaltrialsgov-mcp-serverEstructura del proyecto
Directorio | Propósito |
| Definiciones de herramientas ( |
| Definiciones de recursos ( |
| Definiciones de prompts ( |
| Cliente y tipos de la API de ClinicalTrials.gov. |
| Análisis y validación de variables de entorno con Zod. |
| Pruebas unitarias y de integración. |
Guía de desarrollo
Consulta CLAUDE.md para conocer las pautas de desarrollo y las reglas arquitectónicas. La versión corta:
Los controladores lanzan, el framework captura: no uses
try/catchen la lógica de la herramientaUsa
ctx.logpara el registro con alcance de solicitud, no llamadas aconsoleRegistra nuevas herramientas y recursos en los archivos barril
index.ts
Contribución
Las incidencias y las solicitudes de extracción son bienvenidas. Ejecuta las comprobaciones antes de enviar:
bun run devcheck
bun run testLicencia
Apache-2.0: consulta LICENSE para obtener más detalles.
Available Tools
7 toolsclinicaltrials_find_eligibleClinicaltrials Find EligibleARead-onlyIdempotentInspect
Find candidate clinical trials for a patient profile. Provide age, sex, conditions, and location to get studies with their demographic limits, contact information, and recruiting locations. Candidates are matched on age, sex, location, recruitment status, and ClinicalTrials.gov's fuzzy condition search only — inclusion/exclusion criteria are not checked, and a candidate can exclude the requested condition, so review each one's criteria with clinicaltrials_get_study_record before treating it as a match. Results are re-ranked so studies whose own condition matches a requested condition surface above tangential matches from ClinicalTrials.gov's fuzzy condition search. Each candidate returns only the sites matching the requested location (capped by locationLimit), not the study's full registered site list — a large trial can register hundreds of sites worldwide. Give location.near (the patient's lat, lon, and a radiusMi) in place of city and state to match by travel distance: candidates then return their sites within the radius, nearest first, each with distanceMi from the patient. When none of a candidate's matched sites is recruiting, one recruiting site is added so an enrollable site is never hidden behind a closer closed one: the one nearest the matched sites (under location.near, the patient) by their published coordinates, in the requested country whenever a site there recruits, carrying distanceMi, or the first in match order when coordinates are missing. Under location.near that one site is also added when none of a candidate's listed sites is in location.country and one of its sites there recruits, so a recruiting site in the patient's country is never hidden behind sites across a border. Fetch a study's complete record with clinicaltrials_get_study_record.
Inputs: age (required), sex (required), location (required), conditions (required), +5 more. Returns: cap, near, error, shown, +6 more
clinicaltrials_get_field_definitionsClinicaltrials Get Field DefinitionsARead-onlyIdempotentInspect
Resolve valid field names from the ClinicalTrials.gov data model — the canonical PascalCase identifiers (OverallStatus, EnrollmentCount, LeadSponsorName) the other tools take. Every record piece works in clinicaltrials_search_studies fields; a leaf piece (sourceType other than STRUCT) also works in AREA[…] expressions in advancedFilter and the query parameters, and as input to clinicaltrials_get_field_values (LocationGeoPoint aside); a leaf of a date or integer type (NormalizedDate, PartialDate, DateTimeMinutes, integer, long, short) also works in sort. An index-only piece (drill with includeIndexedOnly, e.g. NumLocations) works wherever a leaf does except fields. Select a mode: "search" — keyword search returning ranked matches (pass query, e.g. "enrollment", "sponsor", "adverse events"); "drill" — drill into a specific section by dot-notation path (pass path, e.g. "protocolSection.designModule"); "overview" — top-level summary of all sections (no additional args).
Inputs: mode (required), path, limit, query, +1 more. Returns: cap, error, shown, fields, +6 more
clinicaltrials_get_field_valuesClinicaltrials Get Field ValuesARead-onlyIdempotentInspect
Discover valid values for ClinicalTrials.gov fields with study counts per value. Use to explore available filter options before building a search — e.g., valid OverallStatus, Phase, InterventionType, StudyType, or LeadSponsorClass values.
Inputs: fields (required). Returns: error, notice, fieldStats
clinicaltrials_get_study_countClinicaltrials Get Study CountARead-onlyIdempotentInspect
Get total clinical trial study count from ClinicalTrials.gov matching a query, without fetching study data. Fast and lightweight. Use for quick statistics or to build breakdowns by calling multiple times with different filters (e.g., count by phase, count by status, count recruiting vs completed for a condition).
Inputs: query, titleQuery, phaseFilter, outcomeQuery, +7 more. Returns: error, notice, totalCount, searchCriteria
clinicaltrials_get_study_recordClinicaltrials Get Study RecordARead-onlyIdempotentInspect
Fetch a single clinical trial study by NCT ID from ClinicalTrials.gov. Returns the full study record including protocol details, eligibility criteria, outcomes, arms, interventions, contacts, and locations. Optional locationLimit / outcomeLimit / referenceLimit / nearLocation parameters trim locations, outcomes, and references — original totals are preserved in filtersApplied only when a cap actually trims the set.
Inputs: nctId (required), nearLocation, outcomeLimit, locationLimit, +1 more. Returns: error, study, filtersApplied, resultsSummary
clinicaltrials_get_study_resultsClinicaltrials Get Study ResultsARead-onlyIdempotentInspect
Fetch clinical trial results data from ClinicalTrials.gov for completed studies — outcome measures with statistics, adverse events, participant flow, baseline characteristics, and results metadata (limitations & caveats, certain-agreement disclosure restrictions, results point of contact). Posted results exist only for studies where hasResults is true; the entry for a study without them names, in resultPublications, the journal articles its record lists as reporting its results (RESULT references, with PMID and citation), when it lists any. Use clinicaltrials_search_studies first to find studies with results. Each call fetches up to 20 distinct NCT IDs and returns any further IDs in deferredNctIds for a follow-up call. A results-rich record can exceed 500KB per study in full mode — bound it with summary=true, narrower sections, or the outcomeLimit / adverseEventLimit caps; outcomeLimit / outcomeOffset also page summarized outcomes. A bounded list is resumable: outcomeOffset / seriousEventOffset / otherEventOffset start the next window, and each study's filtersApplied reports what was trimmed and the next offset for every list left short. A previous (alias) NCT ID resolves to its canonical study, named in canonicalNctId.
Inputs: nctIds (required), summary, sections, outcomeLimit, +4 more. Returns: error, results, truncated, fetchErrors, +2 more
clinicaltrials_search_studiesClinicaltrials Search StudiesARead-onlyIdempotentInspect
Search for clinical trial studies from ClinicalTrials.gov. Supports full-text and field-specific queries, status/phase/geographic filters, pagination, sorting, and field selection. Returns a compact per-study index by default; pass the fields parameter to get specific leaves at full fidelity — full study records are ~70KB each.
Inputs: sort, query, fields, nctIds, +14 more. Returns: cap, error, shown, notice, +8 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
The seven tools cover distinct facets: lightweight counting, compact index search, full single-record fetch, results-only fetch, schema introspection (definitions vs. values), and patient-oriented candidate matching. The main soft spots are search_studies vs. find_eligible (both surface studies) and get_study_record vs. get_study_results (results are a subset of the record), but descriptions explicitly state the boundaries and cross-reference each other, so an agent can pick correctly.
Every tool uses the same clinicaltrials_ prefix with a snake_case verb_noun form: search_studies, get_study_results, get_study_count, get_field_definitions, get_field_values, get_study_record, find_eligible. The lone 'find_' verb in find_eligible is a meaningful semantic choice (candidate matching, not lookup) rather than an inconsistency.
Seven tools is well within the ideal range and each earns its place: search, count, record, results, two schema helpers, and eligibility matching. There is no redundant or filler tool, and the granularity (count vs. index search vs. full record) avoids forcing agents to over-fetch large payloads.
The surface covers the domain lifecycle well: discover/filter, count, inspect valid fields and values, retrieve full records, retrieve posted results, and eligibility screening, with pagination and trimming controls throughout. The notable gap is batch retrieval of full study records — get_study_results accepts up to 20 NCT IDs while get_study_record is single-study only, so multi-study analysis requires repeated calls.
Maintenance
Related MCP Connectors
Clinical trial search and status from ClinicalTrials.gov
Search ClinicalTrials.gov by condition, drug, location and status, with full trial details
Search and read ClinicalTrials.gov studies, sites and outcomes.
Provide structured access to ClinicalTrials.gov data for searching, retrieving, and analyzing clin…
Related MCP Servers
- AlicenseAqualityAmaintenanceProvides LLMs with structured access to critical biomedical databases including PubTator3 (PubMed/PMC), ClinicalTrials.gov, and MyVariant.info through the Model Context Protocol.4635840 PyPI685MIT
- FlicenseNot gradedqualityDmaintenanceEnables searching and retrieving information from the ClinicalTrials.gov database of over 400,000 clinical studies, including trial details, eligibility criteria, locations, and results across 220+ countries.5-
- FlicenseNot gradedqualityDmaintenanceEnables AI agents to search and analyze clinical trial data from ClinicalTrials.gov using both structured SQL queries for filtering trials by status, phase, and conditions, and semantic vector search for exploring detailed protocol information like exclusion criteria.-
- AlicenseAqualityDmaintenanceEnables conversational access to 400,000+ clinical trials on ClinicalTrials.gov, allowing users to search, compare, and retrieve trial details using plain English through MCP-compatible clients like Cursor and Claude Desktop.53MIT