mcpField
A
alterlab-clinicaltrials

alterlab-clinicaltrials

github.com/alterlab-ieu数据与数据库7867 次安装5 周前更新
代码仓库

关于 alterlab-clinicaltrials

alterlab-clinicaltrials 是通过 API v2 查询 ClinicalTrials.gov 注册库的技能,供研究者和分析人员搜索、筛选、查看并导出临床研究记录。

主要功能

  1. 01按疾病或干预措施搜索
  2. 02按地点、申办方和状态筛选
  3. 03获取详细研究记录
  4. 04分页检索匹配试验
  5. 05以 JSON 或 CSV 导出数据

适用场景

  1. 01查找某疾病的招募中试验
  2. 02查看资格条件和研究地点
  3. 03跟踪某药物或申办方的试验
  4. 04导出试验数据用于分析

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/alterlab-ieu/alterlab-academic-skills --skill alterlab-clinicaltrials

安装后在 Claude Code 中输入/alterlab-clinicaltrials确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

evals/
evals.json
references/
api_reference.md
scripts/
query_clinicaltrials.py

详细介绍

ClinicalTrials.gov 数据库

概述

ClinicalTrials.gov 是一个全面的临床研究注册库,收录了全球开展的临床研究,由美国国家医学图书馆维护。使用 API v2 搜索试验、获取详细的研究信息、按各种条件筛选,并导出数据以供分析。该 API 公开开放(无需身份验证),速率限制约为每分钟 50 个请求,支持 JSON 和 CSV 格式。

何时使用此技能

在以下场景中处理临床试验数据时,应使用此技能:

  • 患者匹配 — 为特定疾病或患者群体寻找正在招募的试验
  • 研究分析 — 分析临床试验趋势、结果或研究设计
  • 药物/干预研究 — 查找测试特定药物或干预措施的试验
  • 地理位置搜索 — 查找特定地点或地区的试验
  • 申办方/组织跟踪 — 查找由特定机构开展的试验
  • 数据导出 — 提取临床试验数据,以供进一步分析或报告
  • 试验监测 — 跟踪特定试验的状态更新或结果
  • 入选资格筛查 — 审查试验的纳入/排除标准
不适用的场景
场景改用
已发表的试验结果、RCT 论文或荟萃分析文献alterlab-pubmed
FDA 批准、药品标签、不良事件(FAERS)或召回数据alterlab-fda
撰写 CSR、SAE 叙述或其他试验报告文档alterlab-clinical-reports
基于证据分级的治疗建议/决策算法alterlab-clinical-decision

快速入门

基本搜索查询

运行辅助脚本(从此技能的 scripts/ 目录运行):

python3 scripts/query_clinicaltrials.py

也可以直接使用 Python 和 requests 库。注意:除非传入 countTotal=true,否则 API 不会返回 totalCount;分页令牌会以 nextPageToken 的形式返回。

import requests

url = "https://clinicaltrials.gov/api/v2/studies"
params = {
    "query.cond": "breast cancer",
    "filter.overallStatus": "RECRUITING",
    "pageSize": 10,
    "countTotal": "true",  # required for data['totalCount'] to exist
}

response = requests.get(url, params=params)
data = response.json()

print(f"Found {data['totalCount']} trials")
获取特定试验

使用 NCT ID 获取试验的详细信息:

import requests

nct_id = "NCT04852770"
url = f"https://clinicaltrials.gov/api/v2/studies/{nct_id}"

response = requests.get(url)
study = response.json()

# Access specific modules
title = study['protocolSection']['identificationModule']['briefTitle']
status = study['protocolSection']['statusModule']['overallStatus']

核心功能

1. 按疾病/病症搜索

使用 query.cond 参数查找研究特定疾病或病症的试验。

示例:查找正在招募的糖尿病试验

from scripts.query_clinicaltrials import search_studies

results = search_studies(
    condition="type 2 diabetes",
    status="RECRUITING",
    page_size=20,
    sort="LastUpdatePostDate:desc"
)

print(f"Found {results['totalCount']} recruiting diabetes trials")
for study in results['studies']:
    protocol = study['protocolSection']
    nct_id = protocol['identificationModule']['nctId']
    title = protocol['identificationModule']['briefTitle']
    print(f"{nct_id}: {title}")

常见用例:

  • 查找罕见病试验
  • 查找针对合并症的试验
  • 跟踪特定诊断对应的试验情况
2. 按干预措施/药物搜索

使用 query.intr 参数搜索测试特定干预措施、药物、器械或操作的试验。

示例:查找测试 Pembrolizumab 的 III 期试验

from scripts.query_clinicaltrials import search_studies

results = search_studies(
    intervention="Pembrolizumab",
    status=["RECRUITING", "ACTIVE_NOT_RECRUITING"],
    page_size=50
)

# Filter by phase in results
phase3_trials = [
    study for study in results['studies']
    if 'PHASE3' in study['protocolSection'].get('designModule', {}).get('phases', [])
]

阶段筛选说明: 没有 filter.phase 查询参数——传入该参数会返回 HTTP 400。若要在服务端筛选,请使用 aggFilters=phase:N,其中 N 为 0–4(同一分面中的值以空格分隔,例如使用 aggFilters=phase:2 3 筛选 II 期或 III 期),或使用 Essie 语法 filter.advanced=AREA[Phase](PHASE2 OR PHASE3)。 如果已经需要获取完整记录,对 designModule.phases 进行后置筛选 (如上所示)是最简单的方法。

常见用例:

  • 跟踪药物开发
  • 为制药公司提供竞争情报
  • 为临床医生研究治疗方案
3. 按地理位置搜索

使用 query.locn 参数查找特定地点的试验。

示例:查找纽约的癌症试验

from scripts.query_clinicaltrials import search_studies

results = search_studies(
    condition="cancer",
    location="New York",
    status="RECRUITING",
    page_size=100
)

# Extract location details
for study in results['studies']:
    locations_module = study['protocolSection'].get('contactsLocationsModule', {})
    locations = locations_module.get('locations', [])
    for loc in locations:
        if 'New York' in loc.get('city', ''):
            print(f"{loc['facility']}: {loc['city']}, {loc.get('state', '')}")

常见用例:

  • 将患者转介至本地试验
  • 分析试验的地理分布
  • 为新试验选择研究中心
4. 按申办方/组织搜索

使用 query.spons 参数查找由特定组织开展的试验。

示例:查找由 NCI 申办的试验

from scripts.query_clinicaltrials import search_studies

results = search_studies(
    sponsor="National Cancer Institute",
    page_size=100
)

# Extract sponsor information
for study in results['studies']:
    sponsor_module = study['protocolSection']['sponsorCollaboratorsModule']
    lead_sponsor = sponsor_module['leadSponsor']['name']
    collaborators = sponsor_module.get('collaborators', [])
    print(f"Lead: {lead_sponsor}")
    if collaborators:
        print(f"  Collaborators: {', '.join([c['name'] for c in collaborators])}")

常见用例:

  • 跟踪机构的研究组合
  • 分析资助组织的优先事项
  • 寻找合作机会
5. 按研究状态筛选

使用 filter.overallStatus 参数,按招募或完成状态筛选试验。

有效的状态值:

  • RECRUITING - 正在招募参与者
  • NOT_YET_RECRUITING - 尚未开始招募
  • ENROLLING_BY_INVITATION - 仅通过邀请招募
  • ACTIVE_NOT_RECRUITING - 正在进行,但不再招募
  • SUSPENDED - 暂时暂停
  • TERMINATED - 提前终止
  • COMPLETED - 研究已完成
  • WITHDRAWN - 在招募前撤回
  • 扩展访问记录使用 AVAILABLE、NO_LONGER_AVAILABLE、 TEMPORARILY_NOT_AVAILABLE、APPROVED_FOR_MARKETING;也可能出现 WITHHELD 和 UNKNOWN (完整列表:GET /api/v2/studies/enums)

示例:查找近期完成且包含结果的试验

from scripts.query_clinicaltrials import search_studies

results = search_studies(
    condition="alzheimer disease",
    status="COMPLETED",
    sort="LastUpdatePostDate:desc",
    page_size=50
)

# Filter for trials with results
trials_with_results = [
    study for study in results['studies']
    if study.get('hasResults', False)
]

print(f"Found {len(trials_with_results)} completed trials with results")
6. 获取详细的研究信息

获取特定试验的全面信息,包括资格标准、结局、联系人和地点。

示例:提取资格标准

from scripts.query_clinicaltrials import get_study_details

study = get_study_details("NCT04852770")
eligibility = study['protocolSection']['eligibilityModule']

print(f"Eligible Ages: {eligibility.get('minimumAge')} - {eligibility.get('maximumAge')}")
print(f"Eligible Sex: {eligibility.get('sex')}")
print(f"\nInclusion Criteria:")
print(eligibility.get('eligibilityCriteria'))

示例:提取联系信息

from scripts.query_clinicaltrials import get_study_details

study = get_study_details("NCT04852770")
contacts_module = study['protocolSection']['contactsLocationsModule']

# Overall contacts
if 'centralContacts' in contacts_module:
    for contact in contacts_module['centralContacts']:
        print(f"Contact: {contact.get('name')}")
        print(f"Phone: {contact.get('phone')}")
        print(f"Email: {contact.get('email')}")

# Study locations
if 'locations' in contacts_module:
    for location in contacts_module['locations']:
        print(f"\nFacility: {location.get('facility')}")
        print(f"City: {location.get('city')}, {location.get('state')}")
        if location.get('status'):
            print(f"Status: {location['status']}")
7. 分页和批量检索数据

使用分页高效处理大型结果集。

示例:检索所有匹配的试验

from scripts.query_clinicaltrials import search_with_all_results

# Get all trials (automatically handles pagination)
all_trials = search_with_all_results(
    condition="rare disease",
    status="RECRUITING"
)

print(f"Retrieved {len(all_trials)} total trials")

示例:手动分页并进行控制

from scripts.query_clinicaltrials import search_studies

all_studies = []
page_token = None
max_pages = 10  # Limit to avoid excessive requests

for page in range(max_pages):
    results = search_studies(
        condition="cancer",
        page_size=1000,  # Max page size
        page_token=page_token
    )

    all_studies.extend(results['studies'])

    # Check for next page. The API returns the cursor as 'nextPageToken';
    # you pass it back in as the 'pageToken' request parameter.
    page_token = results.get('nextPageToken')
    if not page_token:
        break

print(f"Retrieved {len(all_studies)} studies across {page + 1} pages")
8. 将数据导出为 CSV

将试验数据导出为 CSV 格式,以便在电子表格软件或数据分析工具中分析。

示例:导出到 CSV 文件

from scripts.query_clinicaltrials import search_studies

# Request CSV format
results = search_studies(
    condition="heart disease",
    status="RECRUITING",
    format="csv",
    page_size=1000
)

# Save to file
with open("heart_disease_trials.csv", "w") as f:
    f.write(results)

print("Data exported to heart_disease_trials.csv")

**注意:**CSV 格式返回的是字符串,而不是 JSON 字典。

9. 提取并总结研究信息

提取关键信息,以便快速概览或用于报告。

示例:创建试验摘要

from scripts.query_clinicaltrials import get_study_details, extract_study_summary

# Get details and extract summary
study = get_study_details("NCT04852770")
summary = extract_study_summary(study)

print(f"NCT ID: {summary['nct_id']}")
print(f"Title: {summary['title']}")
print(f"Status: {summary['status']}")
print(f"Phase: {', '.join(summary['phase'])}")
print(f"Enrollment: {summary['enrollment']}")
print(f"Last Update: {summary['last_update']}")
print(f"\nBrief Summary:\n{summary['brief_summary']}")
10. 组合查询策略

组合多个筛选条件,进行有针对性的搜索。

示例:多条件搜索

from scripts.query_clinicaltrials import search_studies

# Find Phase 2/3 immunotherapy trials for lung cancer in California
results = search_studies(
    condition="lung cancer",
    intervention="immunotherapy",
    location="California",
    status=["RECRUITING", "NOT_YET_RECRUITING"],
    page_size=100
)

# Further filter by phase
phase2_3_trials = [
    study for study in results['studies']
    if any(phase in ['PHASE2', 'PHASE3']
           for phase in study['protocolSection'].get('designModule', {}).get('phases', []))
]

print(f"Found {len(phase2_3_trials)} Phase 2/3 immunotherapy trials")

资源

  • scripts/query_clinicaltrials.py — 常见查询模式的辅助函数: search_studies()、get_study_details()、search_with_all_results() (自动分页)、extract_study_summary()。直接运行即可查看用法示例。
  • references/api_reference.md — 完整的端点和参数规范、响应模块、 错误处理和数据标准(ISO 8601、CommonMark)。使用不熟悉的 API 功能或排查问题时加载。

最佳实践

速率限制管理

API 的速率限制约为每分钟 50 次请求。批量检索数据时:

  1. 使用最大页面大小(1000),尽量减少请求次数
  2. 遇到速率限制错误(状态码 429)时,实施指数退避
  3. 大规模收集数据时,在请求之间添加延迟
import time
import requests

def search_with_rate_limit(params):
    try:
        response = requests.get("https://clinicaltrials.gov/api/v2/studies", params=params)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 429:
            print("Rate limited. Waiting 60 seconds...")
            time.sleep(60)
            return search_with_rate_limit(params)  # Retry
        raise
数据结构导航

API 响应采用嵌套结构。常见信息的关键路径:

  • NCT ID:study['protocolSection']['identificationModule']['nctId']
  • 标题:study['protocolSection']['identificationModule']['briefTitle']
  • 状态:study['protocolSection']['statusModule']['overallStatus']
  • 阶段:study['protocolSection']['designModule']['phases']
  • 资格标准:study['protocolSection']['eligibilityModule']
  • 地点:study['protocolSection']['contactsLocationsModule']['locations']
  • 干预措施:study['protocolSection']['armsInterventionsModule']['interventions']
错误处理

每次请求都使用 timeout,并将 HTTP 400 视为查询错误,而不是“没有试验”: API 会拒绝未知参数(例如 filter.phase)和格式错误的 Essie 表达式,并返回 400。

处理缺失数据

并非所有试验都有完整信息。始终检查字段是否存在:

# Safe navigation with .get()
phases = study['protocolSection'].get('designModule', {}).get('phases', [])
enrollment = study['protocolSection'].get('designModule', {}).get('enrollmentInfo', {}).get('count', 'N/A')

# Check before accessing
if 'resultsSection' in study:
    # Process results
    pass

Technical Specifications

  • Base URL: https://clinicaltrials.gov/api/v2
  • Authentication: Not required (public API)
  • Rate Limit: ~50 requests/minute per IP
  • Response Formats: JSON (default), CSV
  • Max Page Size: 1000 studies per request (larger values are coerced down to 1000)
  • Date Format: ISO 8601
  • Text Format: CommonMark Markdown for rich text fields
  • API Version: 2.x (v2.0 released March 2024; GET /api/v2/version reports the current build, 2.0.5 as of 2026-09, plus the data timestamp)
  • API Specification: OpenAPI 3.0

For complete technical details, see references/api_reference.md.

评论

支持 Markdown