
Tooluniverse Immunotherapy Response Prediction
- 316 installs
- 1.6k repo stars
- Updated August 4, 2026
- mims-harvard/tooluniverse
tooluniverse-immunotherapy-response-prediction is a ToolUniverse skill from mims-harvard that estimates immunotherapy response likelihood from multi-omic and clinical features for developers designing stratified trials o
About
tooluniverse-immunotherapy-response-prediction is a biomedical ML skill in the mims-harvard/tooluniverse collection for developers working on oncology informatics pipelines. It applies multi-omic and clinical inputs to estimate patient or tumor immunotherapy response likelihood, supporting stratified trial design and biomarker panel selection. Developers reach for this skill when prototyping precision-oncology tools, clinical decision-support agents, or research workflows that need structured response prediction without hand-rolling model interfaces. The skill sits in Harvard's ToolUniverse ecosystem of domain-specific scientific tools and expects familiarity with omics feature tables and clinical covariates rather than general web app development.
- Immunotherapy response scoring
- Multi-omic feature integration
- Trial stratification prototyping
- Biomarker panel exploration
- Agent-orchestrated prediction tools
Tooluniverse Immunotherapy Response Prediction by the numbers
- 316 all-time installs (skills.sh)
- +5 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #575 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mims-harvard/tooluniverse --skill tooluniverse-immunotherapy-response-predictionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 316 |
|---|---|
| repo stars | ★ 1.6k |
| Last updated | August 4, 2026 |
| Repository | mims-harvard/tooluniverse ↗ |
How do you predict immunotherapy response from omics data?
Estimate patient or tumor immunotherapy response likelihood using multi-omic and clinical features when designing stratified trials or biomarker panels.
Who is it for?
Developers building oncology informatics pipelines, clinical trial stratification tools, or biomarker panel prototypes with multi-omic inputs.
Skip if: Developers building general web apps, ecommerce features, or clinical workflows unrelated to immunotherapy response modeling.
When should I use this skill?
A user asks to predict immunotherapy response, stratify trial cohorts, or evaluate biomarker panels using multi-omic and clinical features.
What you get
Immunotherapy response likelihood estimates and biomarker stratification guidance for trial or panel design.
Files
Immunotherapy Response Prediction
Predict patient response to immune checkpoint inhibitors (ICIs) using multi-biomarker integration. Transforms a patient tumor profile (cancer type + mutations + biomarkers) into a quantitative ICI Response Score with drug-specific recommendations, resistance risk assessment, and monitoring plan.
Reasoning Before Searching
Not all tumors respond to checkpoint inhibitors. Reason through the biology before running tools:
- TMB (tumor mutational burden): More somatic mutations produce more neoantigens, which are recognized by T cells. High TMB (>=10 mut/Mb, FDA-approved threshold for pembrolizumab) generally predicts better response — but this varies by cancer type (e.g., RCC responds despite low TMB).
- MSI-H (microsatellite instability-high): Caused by defective DNA mismatch repair (MMR). MSI-H tumors have very high TMB and are pan-cancer approved for pembrolizumab. Check MLH1, MSH2, MSH6, PMS2 mutations.
- PD-L1 expression: The direct target of pembrolizumab/atezolizumab. High PD-L1 (TPS >=50% or CPS >=10 depending on cancer) predicts response in some cancers (NSCLC) but not all (melanoma, where TMB is more predictive).
- Resistance factors are equally important: STK11, KEAP1, JAK1/2 loss, B2M mutations can render an otherwise TMB-high tumor non-responsive.
Before calling any tool, determine which biomarkers are available for this patient and which are unknown. This determines which phases can be scored with data vs. must use cancer-type priors. Do not default to "moderate" for unknowns — flag them explicitly as missing.
LOOK UP DON'T GUESS: Never assume FDA approval for a biomarker-ICI combination — always verify with fda_pharmacogenomic_biomarkers or FDA_get_indications_by_drug_name. Cancer-specific thresholds differ from pan-cancer approvals.
KEY PRINCIPLES: 1. Report-first approach - Create report file FIRST, then populate progressively 2. Evidence-graded - Every finding has an evidence tier (T1-T4) 3. Quantitative output - ICI Response Score (0-100) with transparent component breakdown 4. Cancer-specific - All thresholds and predictions are cancer-type adjusted 5. Multi-biomarker - Integrate TMB + MSI + PD-L1 + neoantigen + mutations 6. Resistance-aware - Always check for known resistance mutations (STK11, PTEN, JAK1/2, B2M) 7. Drug-specific - Recommend specific ICI agents with evidence 8. Source-referenced - Every statement cites the tool/database source 9. English-first queries - Always use English terms in tool calls
---
COMPUTE, DON'T DESCRIBE
When analysis requires computation (statistics, data processing, scoring, enrichment), write and run Python code via Bash. Don't describe what you would do — execute it and report actual results. Use ToolUniverse tools to retrieve data, then Python (pandas, scipy, statsmodels, matplotlib) to analyze it.
When to Use
Apply when user asks:
- "Will this patient respond to immunotherapy?"
- "Should I give pembrolizumab to this melanoma patient?"
- "Patient has NSCLC with TMB 25, PD-L1 80% - predict ICI response"
- "MSI-high colorectal cancer - which checkpoint inhibitor?"
- "Patient has BRAF V600E melanoma, TMB 15 - immunotherapy or targeted?"
- "Compare pembrolizumab vs nivolumab for this patient profile"
---
Input Parsing
Required: Cancer type + at least one of: mutation list OR TMB value Optional: PD-L1 expression, MSI status, immune infiltration data, HLA type, prior treatments, intended ICI
See INPUT_REFERENCE.md for input format examples, cancer type normalization, and gene symbol normalization tables.
---
Workflow Overview
Input: Cancer type + Mutations/TMB + Optional biomarkers (PD-L1, MSI, etc.)
Phase 1: Input Standardization & Cancer Context
Phase 2: TMB Analysis
Phase 3: Neoantigen Analysis
Phase 4: MSI/MMR Status Assessment
Phase 5: PD-L1 Expression Analysis
Phase 6: Immune Microenvironment Profiling
Phase 7: Mutation-Based Predictors
Phase 8: Clinical Evidence & ICI Options
Phase 9: Resistance Risk Assessment
Phase 10: Multi-Biomarker Score Integration
Phase 11: Clinical Recommendations---
Phase 1: Input Standardization & Cancer Context
1. Resolve cancer type to EFO ID via OpenTargets_get_disease_id_description_by_name 2. Parse mutations into structured format: {gene, variant, type} 3. Resolve gene IDs via MyGene_query_genes 4. Look up cancer-specific ICI baseline ORR from the cancer context table (see SCORING_TABLES.md)
Phase 2: TMB Analysis
1. Classify TMB: Very-Low (<5), Low (5-9.9), Intermediate (10-19.9), High (>=20) 2. Check FDA TMB-H biomarker via fda_pharmacogenomic_biomarkers(drug_name='pembrolizumab') 3. Apply cancer-specific TMB thresholds (see SCORING_TABLES.md) 4. Note: RCC responds to ICIs despite low TMB; TMB is less predictive in some cancers
Phase 3: Neoantigen Analysis
1. Estimate neoantigen burden: missense_count 0.3 + frameshift_count 1.5 2. Check mutation impact via UniProt_get_function_by_accession 3. Query known epitopes via iedb_search_epitopes 4. POLE/POLD1 mutations indicate ultra-high neoantigen load
Phase 4: MSI/MMR Status Assessment
1. Integrate MSI status if provided (MSI-H = 25 pts, MSS = 5 pts) 2. Check mutations in MMR genes: MLH1, MSH2, MSH6, PMS2, EPCAM 3. Check FDA MSI-H approvals via fda_pharmacogenomic_biomarkers(biomarker='Microsatellite Instability')
Phase 5: PD-L1 Expression Analysis
1. Classify PD-L1: High (>=50%), Positive (1-49%), Negative (<1%) 2. Apply cancer-specific PD-L1 thresholds and scoring methods (TPS vs CPS) 3. Get baseline expression via HPA_get_cancer_prognostics_by_gene(gene_name='CD274')
Phase 6: Immune Microenvironment Profiling
1. Query immune checkpoint gene expression for: CD274, PDCD1, CTLA4, LAG3, HAVCR2, TIGIT, CD8A, CD8B, GZMA, GZMB, PRF1, IFNG 2. Classify tumor: Hot (T cell inflamed), Cold (immune desert), Immune excluded, Immune suppressed 3. Run immune pathway enrichment via enrichr_gene_enrichment_analysis
Phase 7: Mutation-Based Predictors
1. Resistance mutations (apply PENALTIES): STK11 (-10), PTEN (-5), JAK1/2 (-10 each), B2M (-15), KEAP1 (-5), MDM2/4 (-5), EGFR (-5) 2. Sensitivity mutations (apply BONUSES): POLE (+10), POLD1 (+5), BRCA1/2 (+3), ARID1A (+3), PBRM1 (+5 RCC only) 3. Check CIViC and OpenTargets for driver mutation ICI context 4. Check DDR pathway genes: ATM, ATR, CHEK1/2, BRCA1/2, PALB2, RAD50, MRE11
Phase 8: Clinical Evidence & ICI Options
1. Query FDA indications for ICI drugs via FDA_get_indications_by_drug_name 2. Search clinical trials via search_clinical_trials (params: condition, intervention, query_term) 3. Search PubMed for biomarker-specific response data 4. Get drug mechanisms via OpenTargets_get_drug_mechanisms_of_action_by_chemblId
See SCORING_TABLES.md for ICI drug profiles and ChEMBL IDs.
Phase 9: Resistance Risk Assessment
1. Check CIViC for resistance evidence via civic_search_evidence_items 2. Assess pathway-level resistance: IFN-g signaling, antigen presentation, WNT/b-catenin, MAPK, PI3K/AKT/mTOR 3. Summarize risk: Low / Moderate / High
Phase 10: Multi-Biomarker Score Integration
TOTAL SCORE = TMB_score + MSI_score + PDL1_score + Neoantigen_score + Mutation_bonus + Resistance_penalty
TMB_score: 5-30 points MSI_score: 5-25 points
PDL1_score: 5-20 points Neoantigen_score: 5-15 points
Mutation_bonus: 0-10 points Resistance_penalty: -20 to 0 points
Floor: 0, Cap: 100Response Likelihood Tiers:
- 70-100 HIGH (50-80% ORR): Strong ICI candidate
- 40-69 MODERATE (20-50% ORR): Consider ICI, combo preferred
- 0-39 LOW (<20% ORR): ICI alone unlikely effective
Confidence: HIGH (all 4 biomarkers), MODERATE-HIGH (3/4), MODERATE (2/4), LOW (1), VERY LOW (cancer only)
Phase 11: Clinical Recommendations
1. ICI drug selection using cancer-specific algorithm (see SCORING_TABLES.md) 2. Monitoring plan: CT/MRI q8-12wk, ctDNA at 4-6wk, thyroid/liver function, irAEs 3. Alternative strategies if LOW response: targeted therapy, chemotherapy, ICI+chemo combo, ICI+anti-angiogenic, ICI+CTLA-4 combo, clinical trials
---
Output Report
Save as immunotherapy_response_prediction_{cancer_type}.md. See REPORT_TEMPLATE.md for the full report structure.
---
Tool Parameter Reference
BEFORE calling ANY tool, verify parameters. See TOOLS_REFERENCE.md for verified tool parameters table.
Key reminders:
MyGene_query_genes: usequery(NOTq)EnsemblVEP_annotate_rsid: usevariant_id(NOTrsid)drugbank_*tools: ALL 4 params required (query,case_sensitive,exact_match,limit)cBioPortal_get_mutations:gene_listis a STRING not arrayensembl_lookup_gene: REQUIRESspecies='homo_sapiens'
---
Evidence Tiers
| Tier | Description | Source Examples |
|---|---|---|
| T1 | FDA-approved biomarker/indication | FDA labels, NCCN guidelines |
| T2 | Phase 2-3 clinical trial evidence | Published trial data, PubMed |
| T3 | Preclinical/computational evidence | Pathway analysis, in vitro data |
| T4 | Expert opinion/case reports | Case series, reviews |
---
References
- OpenTargets: https://platform.opentargets.org
- CIViC: https://civicdb.org
- FDA Drug Labels: https://dailymed.nlm.nih.gov
- DrugBank: https://go.drugbank.com
- PubMed: https://pubmed.ncbi.nlm.nih.gov
- IEDB: https://www.iedb.org
- HPA: https://www.proteinatlas.org
- cBioPortal: https://www.cbioportal.org
Immunotherapy Response Prediction - Examples
Example 1: High-Biomarker NSCLC (Expected: HIGH Response)
Input: "NSCLC patient, TMB 25 mut/Mb, PD-L1 TPS 80%, no STK11/EGFR mutations. Predict ICI response."
Expected Score Breakdown:
| Component | Value | Score |
|---|---|---|
| TMB | 25 (High) | 30 |
| MSI | Unknown | 10 |
| PD-L1 | 80% (High) | 20 |
| Neoantigens | Est. moderate | 10 |
| Resistance | None | 0 |
| Sensitivity | None | 0 |
| TOTAL | 70 |
Expected Recommendation: Pembrolizumab monotherapy (KEYNOTE-024: 44.8% ORR, 10.3mo PFS with PD-L1>=50%)
---
Example 2: Melanoma with BRAF V600E
Input: "Melanoma, BRAF V600E, TP53 R175H, TMB 15 mut/Mb, PD-L1 50%, MSS"
Expected Score Breakdown:
| Component | Value | Score |
|---|---|---|
| TMB | 15 (Intermediate) | 20 |
| MSI | MSS | 5 |
| PD-L1 | 50% | 20 |
| Neoantigens | Moderate (~10-20) | 10 |
| Resistance | None ICI-specific | 0 |
| Sensitivity | None | 0 |
| TOTAL | 55 |
Expected Recommendation: MODERATE response. Consider: 1. ICI first if no rapid progression risk: pembrolizumab or nivolumab 2. BRAF/MEK targeted (dabrafenib+trametinib) if rapid response needed 3. Nivolumab + ipilimumab for aggressive approach
---
Example 3: MSI-High Colorectal Cancer
Input: "Colorectal cancer, MSI-high, TMB 40 mut/Mb"
Expected Score Breakdown:
| Component | Value | Score |
|---|---|---|
| TMB | 40 (High) | 30 |
| MSI | MSI-H | 25 |
| PD-L1 | Unknown | 10 |
| Neoantigens | High (MSI-H) | 15 |
| Resistance | None | 0 |
| Sensitivity | High TMB/MSI-H | 5 |
| TOTAL | 85 |
Expected Recommendation: HIGH response. Pembrolizumab first-line (KEYNOTE-177: 43.8% ORR, 16.5mo PFS)
---
Example 4: Low-Biomarker NSCLC with Resistance
Input: "NSCLC, TMB 2 mut/Mb, PD-L1 <1%, STK11 loss of function mutation"
Expected Score Breakdown:
| Component | Value | Score |
|---|---|---|
| TMB | 2 (Very Low) | 5 |
| MSI | Unknown | 10 |
| PD-L1 | <1% | 5 |
| Neoantigens | Low | 5 |
| Resistance | STK11 loss | -10 |
| Sensitivity | None | 0 |
| TOTAL | 15 |
Expected Recommendation: LOW response. ICI monotherapy unlikely effective. 1. Platinum-based chemotherapy preferred 2. Consider ICI + chemotherapy combination (may have modest benefit) 3. Clinical trial enrollment
---
Example 5: Bladder Cancer Moderate Profile
Input: "Bladder cancer, TMB 12 mut/Mb, PD-L1 CPS 10, no resistance mutations"
Expected Score Breakdown:
| Component | Value | Score |
|---|---|---|
| TMB | 12 (Intermediate) | 20 |
| MSI | Unknown | 10 |
| PD-L1 | 10% (Positive) | 12 |
| Neoantigens | Moderate | 10 |
| Resistance | None | 0 |
| Sensitivity | None | 0 |
| TOTAL | 52 |
Expected Recommendation: MODERATE response. 1. Pembrolizumab (second-line, KEYNOTE-045: 21.1% ORR) 2. Atezolizumab (second-line option) 3. Avelumab maintenance after platinum
---
Example 6: RCC (Renal Cell Carcinoma)
Input: "Clear cell RCC, no specific mutations reported, PD-L1 positive"
Expected Score Breakdown:
| Component | Value | Score |
|---|---|---|
| TMB | Unknown | 15 (neutral, RCC context) |
| MSI | Unknown | 10 |
| PD-L1 | Positive (1-49%) | 12 |
| Neoantigens | Unknown | 8 |
| Resistance | None known | 0 |
| Sensitivity | None | 0 |
| TOTAL | 45 |
Expected Recommendation: MODERATE response (RCC is ICI-responsive despite low TMB). 1. Nivolumab + ipilimumab (CheckMate-214: 42% ORR for intermediate/poor risk) 2. Pembrolizumab + axitinib (KEYNOTE-426: 59% ORR) 3. Nivolumab + cabozantinib (CheckMate-9ER)
Note: RCC is a special case where TMB is not as predictive.
---
Example 7: HNSCC with CPS
Input: "Head and neck squamous cell carcinoma, PD-L1 CPS 25, TMB 8 mut/Mb"
Expected Score:
| Component | Value | Score |
|---|---|---|
| TMB | 8 (Low) | 10 |
| MSI | Unknown | 10 |
| PD-L1 | CPS 25 (High) | 20 |
| Neoantigens | Low-Moderate | 8 |
| Resistance | None | 0 |
| TOTAL | 48 |
Expected Recommendation: MODERATE response. Pembrolizumab monotherapy (KEYNOTE-048: CPS>=20, 23.3% ORR mono, 36% combo)
---
Example 8: Edge Case - Conflicting Biomarkers
Input: "NSCLC, TMB 30 mut/Mb (high), PD-L1 <1% (negative), JAK2 mutation"
Expected Score:
| Component | Value | Score |
|---|---|---|
| TMB | 30 (High) | 30 |
| MSI | Unknown | 10 |
| PD-L1 | <1% | 5 |
| Neoantigens | Moderate-High | 12 |
| Resistance | JAK2 mutation | -10 |
| TOTAL | 47 |
Expected Recommendation: MODERATE but with caveats. High TMB suggests neoantigen load, but JAK2 mutation may impair IFN-gamma signaling. Consider combination ICI or clinical trial.
Input Reference: Immunotherapy Response Prediction
Accepted Input Formats
| Format | Example | How to Parse |
|---|---|---|
| Cancer + mutations | "Melanoma, BRAF V600E, TP53 R273H" | cancer=melanoma, mutations=[BRAF V600E, TP53 R273H] |
| Cancer + TMB | "NSCLC, TMB 25 mut/Mb" | cancer=NSCLC, tmb=25 |
| Cancer + full profile | "Melanoma, BRAF V600E, TMB 15, PD-L1 50%, MSS" | cancer=melanoma, mutations=[BRAF V600E], tmb=15, pdl1=50, msi=MSS |
| Cancer + MSI status | "Colorectal cancer, MSI-high" | cancer=CRC, msi=MSI-H |
| Resistance query | "NSCLC, TMB 2, STK11 loss, PD-L1 <1%" | cancer=NSCLC, tmb=2, mutations=[STK11 loss], pdl1=0 |
| ICI selection | "Which ICI for NSCLC PD-L1 90%?" | cancer=NSCLC, pdl1=90, query_type=drug_selection |
Cancer Type Normalization
Common aliases to resolve:
- NSCLC -> non-small cell lung carcinoma
- SCLC -> small cell lung carcinoma
- CRC -> colorectal cancer
- RCC -> renal cell carcinoma
- HNSCC -> head and neck squamous cell carcinoma
- UC / bladder -> urothelial carcinoma
- HCC -> hepatocellular carcinoma
- TNBC -> triple-negative breast cancer
- GEJ -> gastroesophageal junction cancer
Gene Symbol Normalization
- PD-L1 -> CD274
- PD-1 -> PDCD1
- CTLA-4 -> CTLA4
- HER2 -> ERBB2
- MSH2/MLH1/MSH6/PMS2 -> MMR genes
Mutation Parsing
Parse each mutation into structured format:
"BRAF V600E" -> {gene: "BRAF", variant: "V600E", type: "missense"}
"TP53 R273H" -> {gene: "TP53", variant: "R273H", type: "missense"}
"STK11 loss" -> {gene: "STK11", variant: "loss of function", type: "loss"}Report Template: Immunotherapy Response Prediction
Save report as immunotherapy_response_prediction_{cancer_type}.md
# Immunotherapy Response Prediction Report
## Executive Summary
[2-3 sentence summary: cancer type, ICI Response Score, recommendation]
## ICI Response Score: XX/100
**Response Likelihood: [HIGH/MODERATE/LOW]**
**Confidence: [HIGH/MODERATE/LOW]**
**Expected ORR: XX-XX%**
### Score Breakdown
| Component | Value | Score | Max |
|-----------|-------|-------|-----|
| TMB | XX mut/Mb | XX | 30 |
| MSI Status | MSI-H/MSS | XX | 25 |
| PD-L1 | XX% | XX | 20 |
| Neoantigen Load | XX est. | XX | 15 |
| Sensitivity Bonus | +XX | XX | 10 |
| Resistance Penalty | -XX | XX | -20 |
| **TOTAL** | | **XX** | **100** |
## Patient Profile
- **Cancer Type**: [cancer]
- **Mutations**: [list]
- **TMB**: XX mut/Mb [classification]
- **MSI Status**: [MSI-H/MSS/Unknown]
- **PD-L1**: XX% [scoring method]
## Biomarker Analysis
### TMB Analysis
[TMB classification, cancer-specific context, FDA TMB-H status]
### MSI/MMR Status
[MSI status, MMR gene mutations, FDA MSI-H approvals]
### PD-L1 Expression
[PD-L1 level, cancer-specific thresholds, scoring method]
### Neoantigen Burden
[Estimated neoantigen count, quality assessment, mutation types]
## Mutation Analysis
### Driver Mutations
[Analysis of each mutation - oncogenic role, ICI implications]
### Resistance Mutations
[Any STK11, PTEN, JAK1/2, B2M, KEAP1 etc. with penalties]
### Sensitivity Mutations
[Any POLE, PBRM1, DDR genes with bonuses]
## Immune Microenvironment
[Hot/cold classification, immune gene expression data]
## ICI Drug Recommendation
### Primary Recommendation
**[Drug name]** - [monotherapy/combination]
- Evidence: [FDA approval, trial data]
- Expected response: XX-XX%
- Key trial: [trial name/NCT#]
### Alternative Options
1. [Alternative 1] - [rationale]
2. [Alternative 2] - [rationale]
### Combination Strategies
[ICI+ICI, ICI+chemo, ICI+targeted recommendations]
## Clinical Evidence
[Key trials, response rates, PFS/OS data for this cancer + biomarker profile]
## Resistance Risk
- **Risk Level**: [LOW/MODERATE/HIGH]
- **Key Factors**: [list resistance mutations/mechanisms]
- **Mitigation**: [combination strategies]
## Monitoring Plan
- **Response assessment**: [schedule]
- **Biomarkers to track**: [ctDNA, imaging, labs]
- **irAE monitoring**: [schedule]
- **Resistance monitoring**: [when to suspect progression]
## Alternative Strategies (if ICI unlikely effective)
[Targeted therapy, chemotherapy, clinical trials]
## Evidence Grading
| Finding | Evidence Tier | Source |
|---------|-------------|--------|
| [finding 1] | T1 (FDA/Guidelines) | [source] |
| [finding 2] | T2 (Clinical trial) | [source] |
## Data Completeness
| Biomarker | Status | Impact |
|-----------|--------|--------|
| TMB | Provided/Estimated/Unknown | XX points |
| MSI | Provided/Unknown | XX points |
| PD-L1 | Provided/Unknown | XX points |
| Neoantigen | Estimated | XX points |
| Mutations | X provided | +/-XX points |
## Missing Data Recommendations
[What additional tests would improve prediction accuracy]
---
*Generated by ToolUniverse Immunotherapy Response Prediction Skill*
*Sources: OpenTargets, CIViC, FDA, DrugBank, PubMed, IEDB, HPA, cBioPortal*Use Case Examples
Use Case 1: NSCLC with High TMB
Input: "NSCLC, TMB 25, PD-L1 80%, no STK11 mutation" Expected: ICI Score 70-85, HIGH response, pembrolizumab monotherapy recommended
Use Case 2: Melanoma with BRAF
Input: "Melanoma, BRAF V600E, TMB 15, PD-L1 50%" Expected: ICI Score 50-65, MODERATE response, discuss ICI vs BRAF-targeted
Use Case 3: MSI-H Colorectal
Input: "Colorectal cancer, MSI-high, TMB 40" Expected: ICI Score 80-95, HIGH response, pembrolizumab first-line
Use Case 4: Low Biomarker NSCLC
Input: "NSCLC, TMB 2, PD-L1 <1%, STK11 mutation" Expected: ICI Score 5-20, LOW response, chemotherapy preferred
Use Case 5: Bladder Cancer
Input: "Bladder cancer, TMB 12, PD-L1 10%, no resistance mutations" Expected: ICI Score 45-55, MODERATE response, ICI+chemo or maintenance
Use Case 6: Checkpoint Inhibitor Selection
Input: "Which ICI for NSCLC with PD-L1 90%?" Expected: Pembrolizumab monotherapy first-line, evidence from KEYNOTE-024
Completeness Checklist
- [ ] Cancer type resolved to EFO ID
- [ ] All mutations parsed and genes resolved
- [ ] TMB classified with cancer-specific context
- [ ] MSI/MMR status assessed
- [ ] PD-L1 integrated (or flagged as unknown)
- [ ] Neoantigen burden estimated
- [ ] Resistance mutations checked (STK11, PTEN, JAK1/2, B2M, KEAP1)
- [ ] Sensitivity mutations checked (POLE, PBRM1, DDR)
- [ ] FDA-approved ICIs identified for this cancer
- [ ] Clinical trial evidence retrieved
- [ ] ICI Response Score calculated with component breakdown
- [ ] Drug recommendation provided with evidence
- [ ] Monitoring plan included
- [ ] Alternative strategies for low responders
- [ ] Evidence grading applied to all findings
- [ ] Data completeness documented
- [ ] Missing data recommendations provided
- [ ] Report saved to file
Scoring Tables: Immunotherapy Response Prediction
Cancer-Specific ICI Context
| Cancer Type | EFO ID | Baseline ICI ORR | Key Biomarkers | FDA-Approved ICIs |
|---|---|---|---|---|
| Melanoma | EFO_0000756 | 30-45% | TMB, PD-L1 | pembro, nivo, ipi, nivo+ipi, nivo+rela |
| NSCLC | EFO_0003060 | 15-50% (PD-L1 dependent) | PD-L1, TMB, STK11 | pembro, nivo, atezo, durva, cemiplimab |
| Bladder/UC | EFO_0000292 | 15-25% | PD-L1, TMB | pembro, nivo, atezo, avelumab, durva |
| RCC | EFO_0000681 | 25-40% | PD-L1 | nivo, pembro, nivo+ipi, nivo+cabo, pembro+axitinib |
| HNSCC | EFO_0000181 | 15-20% | PD-L1 CPS | pembro, nivo |
| MSI-H (any) | N/A | 30-50% | MSI, dMMR | pembro (tissue-agnostic) |
| TMB-H (any) | N/A | 20-30% | TMB >=10 | pembro (tissue-agnostic) |
| CRC (MSI-H) | EFO_0000365 | 30-50% | MSI, dMMR | pembro, nivo, nivo+ipi |
| CRC (MSS) | EFO_0000365 | <5% | Generally poor | Generally not recommended |
| HCC | EFO_0000182 | 15-20% | PD-L1 | atezo+bev, durva+treme, nivo+ipi |
| TNBC | EFO_0005537 | 10-20% | PD-L1 CPS | pembro+chemo |
| Gastric/GEJ | EFO_0000178 | 10-20% | PD-L1 CPS, MSI | pembro, nivo |
TMB Classification & Scoring
| TMB Range | Classification | ICI Score Component |
|---|---|---|
| >= 20 mut/Mb | TMB-High | 30 points |
| 10-19.9 mut/Mb | TMB-Intermediate | 20 points |
| 5-9.9 mut/Mb | TMB-Low | 10 points |
| < 5 mut/Mb | TMB-Very-Low | 5 points |
Cancer-Specific TMB Thresholds
| Cancer Type | Typical TMB Range | High-TMB Threshold | Notes |
|---|---|---|---|
| Melanoma | 5-50+ | >20 | High baseline TMB; UV-induced |
| NSCLC | 2-30 | >10 | Smoking-related; FDA cutoff 10 |
| Bladder | 5-25 | >10 | Moderate baseline |
| CRC (MSI-H) | 20-100+ | >10 | Very high in MSI-H |
| CRC (MSS) | 2-10 | >10 | Generally low |
| RCC | 1-8 | >10 | Low TMB but ICI-responsive |
| HNSCC | 2-15 | >10 | Moderate |
MSI Status Scoring
| MSI Status | Classification | Score Component |
|---|---|---|
| MSI-H / dMMR | MSI-High | 25 points |
| MSS / pMMR | Microsatellite Stable | 5 points |
| Unknown | Not tested | 10 points (neutral) |
PD-L1 Scoring
| PD-L1 Level | Classification | Score Component |
|---|---|---|
| >= 50% (TPS) | PD-L1 High | 20 points |
| 1-49% (TPS) | PD-L1 Positive | 12 points |
| < 1% (TPS) | PD-L1 Negative | 5 points |
| Unknown | Not tested | 10 points (neutral) |
Cancer-Specific PD-L1 Thresholds
| Cancer | Scoring Method | Key Thresholds | ICI Monotherapy Recommended? |
|---|---|---|---|
| NSCLC | TPS | >=50%: first-line mono; >=1%: after chemo | Yes at >=50%, combo at >=1% |
| Melanoma | Not routinely required | N/A | Yes regardless of PD-L1 |
| Bladder | CPS or IC | CPS>=10 preferred | Yes with PD-L1 positive |
| HNSCC | CPS | CPS>=1: pembro; CPS>=20: mono preferred | CPS>=20 for monotherapy |
| Gastric | CPS | CPS>=1 | Pembro+chemo |
| TNBC | CPS | CPS>=10 | Pembro+chemo |
Neoantigen Score Component
| Estimated Neoantigen Load | Classification | Score |
|---|---|---|
| >50 neoantigens | High | 15 points |
| 20-50 neoantigens | Moderate | 10 points |
| <20 neoantigens | Low | 5 points |
ICI-Resistance Mutations (Penalties)
| Gene | Mutation | Cancer Context | Mechanism | Penalty |
|---|---|---|---|---|
| STK11/LKB1 | Loss/inactivation | NSCLC (esp. KRAS+) | Immune exclusion, cold TME | -10 points |
| PTEN | Loss/deletion | Multiple | Reduced T cell infiltration | -5 points |
| JAK1 | Loss of function | Multiple | IFN-g signaling loss | -10 points |
| JAK2 | Loss of function | Multiple | IFN-g signaling loss | -10 points |
| B2M | Loss/mutation | Multiple | MHC-I loss, immune escape | -15 points |
| KEAP1 | Loss/mutation | NSCLC | Oxidative stress, cold TME | -5 points |
| MDM2 | Amplification | Multiple | Hyperprogression risk | -5 points |
| MDM4 | Amplification | Multiple | Hyperprogression risk | -5 points |
| EGFR | Activating mutation | NSCLC | Low TMB, cold TME | -5 points |
ICI-Sensitivity Mutations (Bonuses)
| Gene | Mutation | Cancer Context | Mechanism | Bonus |
|---|---|---|---|---|
| POLE | Exonuclease domain | Any | Ultramutation, high neoantigens | +10 points |
| POLD1 | Proofreading domain | Any | Ultramutation | +5 points |
| BRCA1/2 | Loss of function | Multiple | Genomic instability | +3 points |
| ARID1A | Loss of function | Multiple | Chromatin remodeling, TME | +3 points |
| PBRM1 | Loss of function | RCC | ICI response in RCC | +5 points (RCC only) |
Pathway-Level Resistance
| Pathway | Resistance Mechanism | Genes |
|---|---|---|
| IFN-g signaling | Loss of IFN-g response | JAK1, JAK2, STAT1, IRF1 |
| Antigen presentation | MHC-I downregulation | B2M, TAP1, TAP2, HLA-A/B/C |
| WNT/b-catenin | T cell exclusion | CTNNB1 activating mutations |
| MAPK pathway | Immune suppression | MEK, ERK hyperactivation |
| PI3K/AKT/mTOR | Immune suppression | PTEN loss, PIK3CA |
ICI Drug Profiles
| Drug | Target | Type | Key Indications |
|---|---|---|---|
| Pembrolizumab (Keytruda) | PD-1 | IgG4 mAb | Melanoma, NSCLC, HNSCC, Bladder, MSI-H, TMB-H, many others |
| Nivolumab (Opdivo) | PD-1 | IgG4 mAb | Melanoma, NSCLC, RCC, CRC (MSI-H), HCC, HNSCC |
| Atezolizumab (Tecentriq) | PD-L1 | IgG1 mAb | NSCLC, Bladder, HCC, Melanoma |
| Durvalumab (Imfinzi) | PD-L1 | IgG1 mAb | NSCLC (Stage III), Bladder, HCC, BTC |
| Ipilimumab (Yervoy) | CTLA-4 | IgG1 mAb | Melanoma, RCC (combo), CRC (MSI-H combo) |
| Avelumab (Bavencio) | PD-L1 | IgG1 mAb | Merkel cell, Bladder (maintenance) |
| Cemiplimab (Libtayo) | PD-1 | IgG4 mAb | CSCC, NSCLC, Basal cell |
| Dostarlimab (Jemperli) | PD-1 | IgG4 mAb | dMMR endometrial, dMMR solid tumors |
| Tremelimumab (Imjudo) | CTLA-4 | IgG2 mAb | HCC (combo with durva) |
Key ICI ChEMBL IDs
| Drug | ChEMBL ID |
|---|---|
| Pembrolizumab | CHEMBL3137343 |
| Nivolumab | CHEMBL2108738 |
| Atezolizumab | CHEMBL3707227 |
| Durvalumab | CHEMBL3301587 |
| Ipilimumab | CHEMBL1789844 |
| Avelumab | CHEMBL3833373 |
| Cemiplimab | CHEMBL4297723 |
ICI Drug Selection Algorithm
IF MSI-H:
-> Pembrolizumab (tissue-agnostic FDA approval)
-> Nivolumab (CRC-specific)
-> Consider nivo+ipi combination
IF TMB-H (>=10) and not MSI-H:
-> Pembrolizumab (tissue-agnostic for TMB-H)
IF Cancer = Melanoma:
IF PD-L1 >= 1%: pembrolizumab or nivolumab monotherapy
ELSE: nivolumab + ipilimumab combination
IF BRAF V600E: consider targeted therapy first if rapid response needed
IF Cancer = NSCLC:
IF PD-L1 >= 50% and no STK11/EGFR: pembrolizumab monotherapy
IF PD-L1 1-49%: pembrolizumab + chemotherapy
IF PD-L1 < 1%: ICI + chemotherapy combination
IF STK11 loss: ICI less likely effective
IF EGFR/ALK positive: targeted therapy preferred over ICI
IF Cancer = RCC:
-> Nivolumab + ipilimumab (IMDC intermediate/poor risk)
-> Pembrolizumab + axitinib (all risk)
IF Cancer = Bladder:
-> Pembrolizumab or atezolizumab (2L)
-> Avelumab maintenance post-platinum#!/usr/bin/env python3
"""
Comprehensive Test Suite for Immunotherapy Response Prediction Skill
Tests all 11 phases with real data across multiple cancer types and biomarker profiles.
"""
import json
import time
import traceback
from typing import Any
# Test tracking
TESTS_RUN = 0
TESTS_PASSED = 0
TESTS_FAILED = 0
FAILURES = []
def log_test(name: str, passed: bool, details: str = ""):
global TESTS_RUN, TESTS_PASSED, TESTS_FAILED
TESTS_RUN += 1
status = "PASS" if passed else "FAIL"
if passed:
TESTS_PASSED += 1
else:
TESTS_FAILED += 1
FAILURES.append(f"{name}: {details}")
print(f" [{status}] {name}" + (f" - {details}" if details and not passed else ""))
def init_tu():
"""Initialize ToolUniverse once."""
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
return tu
# ============================================================
# PHASE 1: Input Standardization & Cancer Context
# ============================================================
def test_phase1_cancer_resolution(tu):
"""Test cancer type resolution to EFO IDs."""
print("\n=== Phase 1: Cancer Resolution ===")
cancer_types = {
'melanoma': 'EFO_0000756',
'non-small cell lung carcinoma': 'EFO_0003060',
'colorectal cancer': 'EFO_0000365',
'bladder carcinoma': None, # Just check it returns something
'renal cell carcinoma': None,
'head and neck squamous cell carcinoma': None,
}
for cancer, expected_efo in cancer_types.items():
try:
result = tu.tools.OpenTargets_get_disease_id_description_by_name(diseaseName=cancer)
hits = result.get('data', {}).get('search', {}).get('hits', [])
found = len(hits) > 0
if expected_efo:
# Check specific EFO match
efo_match = any(h.get('id') == expected_efo for h in hits)
log_test(f"Cancer resolution: {cancer}", found and efo_match,
f"Expected {expected_efo}, got {hits[0].get('id') if hits else 'none'}")
else:
log_test(f"Cancer resolution: {cancer}", found,
f"No hits found" if not found else "")
except Exception as e:
log_test(f"Cancer resolution: {cancer}", False, str(e)[:100])
def test_phase1_gene_resolution(tu):
"""Test gene symbol to Ensembl/Entrez ID resolution."""
print("\n=== Phase 1: Gene Resolution ===")
genes = {
'BRAF': {'ensembl': 'ENSG00000157764', 'entrez': '673'},
'STK11': {'ensembl': 'ENSG00000118046', 'entrez': '6794'},
'PTEN': {'ensembl': 'ENSG00000284792', 'entrez': '5728'},
'PDCD1': {'ensembl': 'ENSG00000188389', 'entrez': '5133'},
'CD274': {'ensembl': 'ENSG00000120217', 'entrez': '29126'},
'JAK1': {'ensembl': 'ENSG00000162434', 'entrez': '3716'},
'JAK2': {'ensembl': 'ENSG00000096968', 'entrez': '3717'},
'B2M': {'ensembl': 'ENSG00000166710', 'entrez': '567'},
'POLE': {'ensembl': 'ENSG00000177084', 'entrez': '5426'},
'MLH1': {'ensembl': 'ENSG00000076242', 'entrez': '4292'},
}
for gene, expected in genes.items():
try:
result = tu.tools.MyGene_query_genes(query=gene)
hits = result.get('hits', []) if isinstance(result, dict) else []
if hits:
hit = hits[0]
ensembl_id = hit.get('ensembl', {})
if isinstance(ensembl_id, dict):
ensembl_id = ensembl_id.get('gene', '')
elif isinstance(ensembl_id, list):
ensembl_id = ensembl_id[0].get('gene', '') if ensembl_id else ''
entrez_id = str(hit.get('_id', ''))
symbol = hit.get('symbol', '')
passed = (symbol == gene and
ensembl_id == expected['ensembl'] and
entrez_id == expected['entrez'])
log_test(f"Gene resolution: {gene}", passed,
f"Got symbol={symbol}, ensembl={ensembl_id}, entrez={entrez_id}")
else:
log_test(f"Gene resolution: {gene}", False, "No hits")
except Exception as e:
log_test(f"Gene resolution: {gene}", False, str(e)[:100])
def test_phase1_ensembl_lookup(tu):
"""Test Ensembl gene lookup."""
print("\n=== Phase 1: Ensembl Lookup ===")
genes = {
'BRAF': 'ENSG00000157764',
'PDCD1': 'ENSG00000188389',
'CD274': 'ENSG00000120217',
}
for symbol, ensembl_id in genes.items():
try:
result = tu.tools.ensembl_lookup_gene(gene_id=symbol, species='homo_sapiens')
data = result.get('data', result)
got_id = data.get('id', '')
got_name = data.get('display_name', '')
passed = got_id == ensembl_id and got_name == symbol
log_test(f"Ensembl lookup: {symbol}", passed,
f"Got id={got_id}, name={got_name}")
except Exception as e:
log_test(f"Ensembl lookup: {symbol}", False, str(e)[:100])
# ============================================================
# PHASE 2: TMB Analysis
# ============================================================
def test_phase2_tmb_classification(tu):
"""Test TMB classification logic."""
print("\n=== Phase 2: TMB Classification ===")
# Test TMB classification logic (no tool call needed - hardcoded thresholds)
test_cases = [
(25, 'TMB-High', 30),
(15, 'TMB-Intermediate', 20),
(7, 'TMB-Low', 10),
(3, 'TMB-Very-Low', 5),
(10, 'TMB-Intermediate', 20),
(20, 'TMB-High', 30),
(0.5, 'TMB-Very-Low', 5),
]
for tmb, expected_class, expected_score in test_cases:
if tmb >= 20:
classification = 'TMB-High'
score = 30
elif tmb >= 10:
classification = 'TMB-Intermediate'
score = 20
elif tmb >= 5:
classification = 'TMB-Low'
score = 10
else:
classification = 'TMB-Very-Low'
score = 5
passed = classification == expected_class and score == expected_score
log_test(f"TMB classification: {tmb} mut/Mb", passed,
f"Expected {expected_class}/{expected_score}, got {classification}/{score}")
def test_phase2_fda_tmb_biomarker(tu):
"""Test FDA TMB-H biomarker lookup."""
print("\n=== Phase 2: FDA TMB-H Biomarker ===")
try:
result = tu.tools.fda_pharmacogenomic_biomarkers(drug_name='pembrolizumab', limit=100)
results = result.get('results', [])
tmb_found = any('Tumor Mutational Burden' in r.get('Biomarker', '') for r in results)
log_test("FDA TMB-H biomarker for pembrolizumab", tmb_found,
f"Found {len(results)} biomarkers" if results else "No results")
except Exception as e:
log_test("FDA TMB-H biomarker for pembrolizumab", False, str(e)[:100])
# ============================================================
# PHASE 3: Neoantigen Analysis
# ============================================================
def test_phase3_neoantigen_estimation(tu):
"""Test neoantigen burden estimation logic."""
print("\n=== Phase 3: Neoantigen Estimation ===")
# Test neoantigen estimation from mutation types
test_cases = [
# (missense_count, frameshift_count, expected_range_low, expected_range_high)
(10, 2, 5, 10), # 10*0.3 + 2*1.5 = 6
(50, 5, 20, 30), # 50*0.3 + 5*1.5 = 22.5
(100, 10, 40, 60), # 100*0.3 + 10*1.5 = 45
(2, 0, 0, 2), # 2*0.3 + 0*1.5 = 0.6
]
for missense, frameshift, exp_low, exp_high in test_cases:
estimate = missense * 0.3 + frameshift * 1.5
passed = exp_low <= estimate <= exp_high
log_test(f"Neoantigen estimate: {missense} missense + {frameshift} frameshift", passed,
f"Estimated {estimate:.1f}, expected {exp_low}-{exp_high}")
def test_phase3_protein_function(tu):
"""Test UniProt protein function retrieval for neoantigen quality."""
print("\n=== Phase 3: Protein Function (Neoantigen Quality) ===")
proteins = {
'P15056': 'BRAF', # BRAF
'Q15831': 'STK11', # STK11
}
for accession, gene in proteins.items():
try:
result = tu.tools.UniProt_get_function_by_accession(accession=accession)
has_data = isinstance(result, list) and len(result) > 0
log_test(f"UniProt function: {gene} ({accession})", has_data,
f"Got {len(result)} entries" if isinstance(result, list) else str(type(result)))
except Exception as e:
log_test(f"UniProt function: {gene} ({accession})", False, str(e)[:100])
def test_phase3_iedb_epitopes(tu):
"""Test IEDB epitope search."""
print("\n=== Phase 3: IEDB Epitope Search ===")
try:
result = tu.tools.iedb_search_epitopes(organism_name='homo sapiens', source_antigen_name='BRAF')
has_data = result.get('status') == 'success' and result.get('count', 0) > 0
log_test("IEDB epitopes: BRAF", has_data,
f"Found {result.get('count', 0)} epitopes")
except Exception as e:
log_test("IEDB epitopes: BRAF", False, str(e)[:100])
# ============================================================
# PHASE 4: MSI/MMR Status
# ============================================================
def test_phase4_msi_scoring(tu):
"""Test MSI status scoring logic."""
print("\n=== Phase 4: MSI Scoring ===")
test_cases = [
('MSI-H', 25),
('MSI-high', 25),
('dMMR', 25),
('MSS', 5),
('pMMR', 5),
('unknown', 10),
(None, 10),
]
for msi_status, expected_score in test_cases:
status_lower = (msi_status or '').lower().strip()
if status_lower in ('msi-h', 'msi-high', 'msih', 'dmmr', 'msi high'):
score = 25
elif status_lower in ('mss', 'pmmr', 'microsatellite stable'):
score = 5
else:
score = 10
passed = score == expected_score
log_test(f"MSI scoring: {msi_status}", passed,
f"Expected {expected_score}, got {score}")
def test_phase4_fda_msi_biomarker(tu):
"""Test FDA MSI-H biomarker approvals."""
print("\n=== Phase 4: FDA MSI-H Biomarker ===")
try:
result = tu.tools.fda_pharmacogenomic_biomarkers(biomarker='Microsatellite Instability', limit=100)
results = result.get('results', [])
has_data = len(results) > 0
drugs_with_msi = set()
for r in results:
drug = r.get('Drug', '')
if drug:
drugs_with_msi.add(drug.split('(')[0].strip())
log_test("FDA MSI-H biomarker approvals", has_data,
f"Found {len(results)} entries, drugs: {', '.join(list(drugs_with_msi)[:5])}")
except Exception as e:
log_test("FDA MSI-H biomarker approvals", False, str(e)[:100])
# ============================================================
# PHASE 5: PD-L1 Expression
# ============================================================
def test_phase5_pdl1_scoring(tu):
"""Test PD-L1 level scoring logic."""
print("\n=== Phase 5: PD-L1 Scoring ===")
test_cases = [
(90, 20),
(50, 20),
(25, 12),
(1, 12),
(0, 5),
(None, 10),
]
for pdl1, expected_score in test_cases:
if pdl1 is None:
score = 10
elif pdl1 >= 50:
score = 20
elif pdl1 >= 1:
score = 12
else:
score = 5
passed = score == expected_score
log_test(f"PD-L1 scoring: {pdl1}%", passed,
f"Expected {expected_score}, got {score}")
def test_phase5_pdl1_prognostics(tu):
"""Test PD-L1 gene cancer prognostics from HPA."""
print("\n=== Phase 5: PD-L1 (CD274) Prognostics ===")
try:
result = tu.tools.HPA_get_cancer_prognostics_by_gene(gene_name='CD274')
has_data = result is not None
if isinstance(result, dict):
data = result.get('data', result)
log_test("HPA PD-L1 prognostics", has_data,
f"Type: {type(data).__name__}")
elif isinstance(result, list):
log_test("HPA PD-L1 prognostics", len(result) > 0,
f"Found {len(result)} entries")
else:
log_test("HPA PD-L1 prognostics", has_data, f"Type: {type(result).__name__}")
except Exception as e:
log_test("HPA PD-L1 prognostics", False, str(e)[:100])
# ============================================================
# PHASE 6: Immune Microenvironment
# ============================================================
def test_phase6_immune_gene_prognostics(tu):
"""Test immune checkpoint gene prognostics."""
print("\n=== Phase 6: Immune Gene Prognostics ===")
immune_genes = ['CD274', 'PDCD1', 'CTLA4', 'CD8A', 'IFNG']
for gene in immune_genes:
try:
result = tu.tools.HPA_get_cancer_prognostics_by_gene(gene_name=gene)
has_data = result is not None
log_test(f"HPA prognostics: {gene}", has_data)
except Exception as e:
log_test(f"HPA prognostics: {gene}", False, str(e)[:100])
def test_phase6_pathway_enrichment(tu):
"""Test immune pathway enrichment analysis."""
print("\n=== Phase 6: Immune Pathway Enrichment ===")
try:
result = tu.tools.enrichr_gene_enrichment_analysis(
gene_list=['CD274', 'PDCD1', 'CTLA4', 'IFNG', 'CD8A', 'GZMA', 'PRF1'],
libs=['KEGG_2021_Human']
)
has_data = result is not None and not (isinstance(result, dict) and 'error' in result)
if isinstance(result, dict):
log_test("Enrichr immune pathway analysis", has_data,
f"Keys: {list(result.keys())[:5]}")
else:
log_test("Enrichr immune pathway analysis", has_data, f"Type: {type(result).__name__}")
except Exception as e:
log_test("Enrichr immune pathway analysis", False, str(e)[:100])
# ============================================================
# PHASE 7: Mutation-Based Predictors
# ============================================================
def test_phase7_resistance_scoring(tu):
"""Test resistance mutation scoring logic."""
print("\n=== Phase 7: Resistance Mutation Scoring ===")
# Resistance mutations and their penalties
resistance_mutations = {
'STK11': -10,
'PTEN': -5,
'JAK1': -10,
'JAK2': -10,
'B2M': -15,
'KEAP1': -5,
'MDM2': -5,
}
# Test individual mutations
for gene, penalty in resistance_mutations.items():
log_test(f"Resistance penalty: {gene}", True, f"Penalty: {penalty}")
# Test combined scenario: STK11 + KEAP1
combined = resistance_mutations['STK11'] + resistance_mutations['KEAP1']
log_test("Combined resistance: STK11 + KEAP1", combined == -15,
f"Expected -15, got {combined}")
def test_phase7_sensitivity_scoring(tu):
"""Test sensitivity mutation scoring logic."""
print("\n=== Phase 7: Sensitivity Mutation Scoring ===")
sensitivity_mutations = {
'POLE': 10,
'POLD1': 5,
'BRCA1': 3,
'BRCA2': 3,
'ARID1A': 3,
}
for gene, bonus in sensitivity_mutations.items():
log_test(f"Sensitivity bonus: {gene}", True, f"Bonus: +{bonus}")
def test_phase7_cbio_mutations(tu):
"""Test cBioPortal mutation retrieval."""
print("\n=== Phase 7: cBioPortal Mutation Data ===")
try:
result = tu.tools.cBioPortal_get_mutations(study_id='mel_dfci_2019', gene_list='BRAF')
if isinstance(result, dict):
data = result.get('data', result)
if isinstance(data, list):
has_v600e = any('V600E' in str(m.get('proteinChange', '')) for m in data)
log_test("cBioPortal BRAF mutations in melanoma", len(data) > 0 and has_v600e,
f"Found {len(data)} mutations, V600E present: {has_v600e}")
else:
log_test("cBioPortal BRAF mutations in melanoma", False,
f"Unexpected data type: {type(data).__name__}")
else:
log_test("cBioPortal BRAF mutations in melanoma", False, "No dict returned")
except Exception as e:
log_test("cBioPortal BRAF mutations in melanoma", False, str(e)[:100])
# ============================================================
# PHASE 8: Clinical Evidence & ICI Options
# ============================================================
def test_phase8_fda_indications(tu):
"""Test FDA indication retrieval for ICIs."""
print("\n=== Phase 8: FDA ICI Indications ===")
ici_drugs = ['pembrolizumab', 'nivolumab', 'atezolizumab', 'ipilimumab']
for drug in ici_drugs:
try:
result = tu.tools.FDA_get_indications_by_drug_name(drug_name=drug, limit=3)
has_data = isinstance(result, dict) and 'results' in result and len(result['results']) > 0
if has_data:
total = result.get('meta', {}).get('total', 0)
log_test(f"FDA indications: {drug}", True, f"Total: {total}")
else:
log_test(f"FDA indications: {drug}", False, "No results")
except Exception as e:
log_test(f"FDA indications: {drug}", False, str(e)[:100])
def test_phase8_ot_drug_lookup(tu):
"""Test OpenTargets drug ID lookup for ICIs."""
print("\n=== Phase 8: OpenTargets ICI Drug Lookup ===")
ici_drugs = {
'pembrolizumab': 'CHEMBL3137343',
'nivolumab': 'CHEMBL2108738',
'ipilimumab': 'CHEMBL1789844',
'atezolizumab': 'CHEMBL3707227',
}
for drug, expected_chembl in ici_drugs.items():
try:
result = tu.tools.OpenTargets_get_drug_id_description_by_name(drugName=drug)
hits = result.get('data', {}).get('search', {}).get('hits', [])
if hits:
got_id = hits[0].get('id', '')
passed = got_id == expected_chembl
log_test(f"OT drug lookup: {drug}", passed,
f"Expected {expected_chembl}, got {got_id}")
else:
log_test(f"OT drug lookup: {drug}", False, "No hits")
except Exception as e:
log_test(f"OT drug lookup: {drug}", False, str(e)[:100])
def test_phase8_drug_moa(tu):
"""Test drug mechanism of action retrieval."""
print("\n=== Phase 8: Drug Mechanism of Action ===")
try:
result = tu.tools.OpenTargets_get_drug_mechanisms_of_action_by_chemblId(chemblId='CHEMBL3137343')
rows = result.get('data', {}).get('drug', {}).get('mechanismsOfAction', {}).get('rows', [])
has_pd1 = any('PD' in str(r.get('mechanismOfAction', '')) or 'Programmed' in str(r.get('targetName', ''))
for r in rows)
log_test("OT MOA: pembrolizumab", has_pd1,
f"Found {len(rows)} MOA rows, PD-1 related: {has_pd1}")
except Exception as e:
log_test("OT MOA: pembrolizumab", False, str(e)[:100])
def test_phase8_drugs_for_melanoma(tu):
"""Test OpenTargets drugs for melanoma."""
print("\n=== Phase 8: OT Drugs for Melanoma ===")
try:
result = tu.tools.OpenTargets_get_associated_drugs_by_disease_efoId(efoId='EFO_0000756', size=50)
known_drugs = result.get('data', {}).get('disease', {}).get('knownDrugs', {})
count = known_drugs.get('count', 0)
rows = known_drugs.get('rows', [])
# Check if ICIs appear
ici_names = ['PEMBROLIZUMAB', 'NIVOLUMAB', 'IPILIMUMAB', 'ATEZOLIZUMAB']
found_icis = []
for row in rows:
drug_name = row.get('drug', {}).get('name', '').upper()
if any(ici in drug_name for ici in ici_names):
found_icis.append(drug_name)
log_test("OT drugs for melanoma", count > 0 and len(found_icis) > 0,
f"Total: {count}, ICIs found: {', '.join(list(set(found_icis))[:5])}")
except Exception as e:
log_test("OT drugs for melanoma", False, str(e)[:100])
def test_phase8_drugbank_info(tu):
"""Test DrugBank ICI drug info."""
print("\n=== Phase 8: DrugBank ICI Info ===")
try:
result = tu.tools.drugbank_get_drug_basic_info_by_drug_name_or_id(
query='pembrolizumab', case_sensitive=False, exact_match=True, limit=5)
if isinstance(result, dict):
results = result.get('results', [])
if results:
drug = results[0]
name = drug.get('drug_name', '')
db_id = drug.get('drugbank_id', '')
passed = 'pembrolizumab' in name.lower() and db_id.startswith('DB')
log_test("DrugBank: pembrolizumab", passed,
f"Name: {name}, ID: {db_id}")
else:
log_test("DrugBank: pembrolizumab", False, "No results")
else:
log_test("DrugBank: pembrolizumab", False, f"Type: {type(result).__name__}")
except Exception as e:
log_test("DrugBank: pembrolizumab", False, str(e)[:100])
def test_phase8_clinical_trials(tu):
"""Test clinical trial search for ICI."""
print("\n=== Phase 8: Clinical Trials ===")
cancer_ici_pairs = [
('melanoma', 'pembrolizumab'),
('lung cancer', 'nivolumab'),
('colorectal cancer', 'pembrolizumab'),
]
for cancer, drug in cancer_ici_pairs:
try:
result = tu.tools.ClinicalTrials_search_studies(
action='search_studies', condition=cancer, intervention=drug, limit=5)
if isinstance(result, dict) and 'studies' in result:
studies = result['studies']
log_test(f"Clinical trials: {drug} in {cancer}", len(studies) > 0,
f"Found {len(studies)} studies")
else:
log_test(f"Clinical trials: {drug} in {cancer}", False,
f"Unexpected response: {str(result)[:100]}")
except Exception as e:
log_test(f"Clinical trials: {drug} in {cancer}", False, str(e)[:100])
def test_phase8_pubmed_evidence(tu):
"""Test PubMed literature search for ICI evidence."""
print("\n=== Phase 8: PubMed Evidence ===")
queries = [
'pembrolizumab melanoma TMB response',
'nivolumab ipilimumab melanoma overall survival',
'immunotherapy MSI-H colorectal cancer',
]
for query in queries:
try:
result = tu.tools.PubMed_search_articles(query=query, max_results=5)
if isinstance(result, list):
has_data = len(result) > 0
log_test(f"PubMed: {query[:50]}", has_data,
f"Found {len(result)} articles")
else:
log_test(f"PubMed: {query[:50]}", False, f"Type: {type(result).__name__}")
except Exception as e:
log_test(f"PubMed: {query[:50]}", False, str(e)[:100])
# ============================================================
# PHASE 9: Resistance Risk Assessment
# ============================================================
def test_phase9_civic_evidence(tu):
"""Test CIViC evidence retrieval for ICI therapy."""
print("\n=== Phase 9: CIViC ICI Evidence ===")
try:
result = tu.tools.civic_search_evidence_items(therapy_name='pembrolizumab')
nodes = result.get('data', {}).get('evidenceItems', {}).get('nodes', [])
has_data = len(nodes) > 0
# Check evidence types
ev_types = set(n.get('evidenceType', '') for n in nodes[:20])
log_test("CIViC evidence: pembrolizumab", has_data,
f"Found {len(nodes)} items, types: {', '.join(ev_types)}")
except Exception as e:
log_test("CIViC evidence: pembrolizumab", False, str(e)[:100])
def test_phase9_gene_constraints(tu):
"""Test gnomAD gene constraint data for resistance genes."""
print("\n=== Phase 9: Gene Constraints (Resistance Genes) ===")
resistance_genes = ['STK11', 'PTEN', 'B2M']
for gene in resistance_genes:
try:
result = tu.tools.gnomad_get_gene_constraints(gene_symbol=gene)
if isinstance(result, dict) and result.get('status') == 'error':
error_msg = result.get('error', '')
# gnomAD is often overloaded - treat as soft pass
if 'overloaded' in error_msg.lower() or 'timeout' in error_msg.lower():
log_test(f"gnomAD constraints: {gene}", True,
f"Service overloaded (transient) - soft pass")
else:
log_test(f"gnomAD constraints: {gene}", False, error_msg[:100])
else:
log_test(f"gnomAD constraints: {gene}", True)
except Exception as e:
log_test(f"gnomAD constraints: {gene}", False, str(e)[:100])
# ============================================================
# PHASE 10: Multi-Biomarker Score Integration
# ============================================================
def test_phase10_score_calculation(tu):
"""Test ICI Response Score calculation for all use cases."""
print("\n=== Phase 10: ICI Response Score Calculation ===")
def calculate_score(tmb=None, msi=None, pdl1=None, neoantigen_est=None,
resistance_genes=None, sensitivity_genes=None):
"""Calculate ICI Response Score."""
score = 0
# TMB component (0-30)
if tmb is not None:
if tmb >= 20:
score += 30
elif tmb >= 10:
score += 20
elif tmb >= 5:
score += 10
else:
score += 5
else:
score += 15 # neutral
# MSI component (0-25)
if msi is not None:
msi_lower = msi.lower().strip()
if msi_lower in ('msi-h', 'msi-high', 'dmmr'):
score += 25
elif msi_lower in ('mss', 'pmmr'):
score += 5
else:
score += 10
else:
score += 10
# PD-L1 component (0-20)
if pdl1 is not None:
if pdl1 >= 50:
score += 20
elif pdl1 >= 1:
score += 12
else:
score += 5
else:
score += 10
# Neoantigen component (0-15)
if neoantigen_est is not None:
if neoantigen_est > 50:
score += 15
elif neoantigen_est >= 20:
score += 10
else:
score += 5
else:
score += 8 # neutral
# Resistance penalties
resistance_penalties = {
'STK11': -10, 'PTEN': -5, 'JAK1': -10, 'JAK2': -10,
'B2M': -15, 'KEAP1': -5, 'MDM2': -5, 'MDM4': -5, 'EGFR': -5
}
if resistance_genes:
for gene in resistance_genes:
score += resistance_penalties.get(gene.upper(), 0)
# Sensitivity bonuses
sensitivity_bonuses = {
'POLE': 10, 'POLD1': 5, 'BRCA1': 3, 'BRCA2': 3,
'ARID1A': 3, 'PBRM1': 5
}
if sensitivity_genes:
for gene in sensitivity_genes:
score += sensitivity_bonuses.get(gene.upper(), 0)
# Floor/cap
return max(0, min(100, score))
# Use Case 1: NSCLC high TMB (30+10+20+8 = 68 with unknowns)
score1 = calculate_score(tmb=25, pdl1=80)
tier1 = 'HIGH' if score1 >= 70 else 'MODERATE' if score1 >= 40 else 'LOW'
log_test("Score UC1: NSCLC high TMB+PD-L1", 60 <= score1 <= 85,
f"Score: {score1}, Tier: {tier1}")
# Use Case 2: Melanoma BRAF V600E
score2 = calculate_score(tmb=15, msi='MSS', pdl1=50, neoantigen_est=15)
tier2 = 'HIGH' if score2 >= 70 else 'MODERATE' if score2 >= 40 else 'LOW'
log_test("Score UC2: Melanoma BRAF", 40 <= score2 <= 69,
f"Score: {score2}, Tier: {tier2}")
# Use Case 3: MSI-H CRC
score3 = calculate_score(tmb=40, msi='MSI-H', neoantigen_est=80)
tier3 = 'HIGH' if score3 >= 70 else 'MODERATE' if score3 >= 40 else 'LOW'
log_test("Score UC3: MSI-H CRC", score3 >= 80,
f"Score: {score3}, Tier: {tier3}")
# Use Case 4: Low biomarker NSCLC with STK11
score4 = calculate_score(tmb=2, pdl1=0, neoantigen_est=5, resistance_genes=['STK11'])
tier4 = 'HIGH' if score4 >= 70 else 'MODERATE' if score4 >= 40 else 'LOW'
log_test("Score UC4: Low NSCLC + STK11", score4 < 40,
f"Score: {score4}, Tier: {tier4}")
# Use Case 5: Bladder moderate
score5 = calculate_score(tmb=12, pdl1=10, neoantigen_est=25)
tier5 = 'HIGH' if score5 >= 70 else 'MODERATE' if score5 >= 40 else 'LOW'
log_test("Score UC5: Bladder moderate", 40 <= score5 <= 69,
f"Score: {score5}, Tier: {tier5}")
# Use Case 6: Multiple resistance
score6 = calculate_score(tmb=30, pdl1=1, resistance_genes=['STK11', 'KEAP1', 'B2M'])
tier6 = 'HIGH' if score6 >= 70 else 'MODERATE' if score6 >= 40 else 'LOW'
log_test("Score UC6: High TMB + multiple resistance", score6 < 70,
f"Score: {score6}, Tier: {tier6}")
# Use Case 7: POLE mutation (ultramutator) - MSS reduces score: 30+5+12+15+10=72
score7 = calculate_score(tmb=100, msi='MSS', pdl1=10, neoantigen_est=200,
sensitivity_genes=['POLE'])
tier7 = 'HIGH' if score7 >= 70 else 'MODERATE' if score7 >= 40 else 'LOW'
log_test("Score UC7: POLE ultramutator", score7 >= 70,
f"Score: {score7}, Tier: {tier7}")
# Edge: All unknown
score8 = calculate_score()
log_test("Score edge: All unknown", 35 <= score8 <= 55,
f"Score: {score8} (neutral baseline)")
# ============================================================
# PHASE 11: Clinical Recommendations
# ============================================================
def test_phase11_ici_selection_nsclc(tu):
"""Test ICI selection logic for NSCLC."""
print("\n=== Phase 11: ICI Selection Logic ===")
# NSCLC PD-L1 >= 50%: pembrolizumab monotherapy
test_cases = [
('NSCLC', 50, None, False, False, 'pembrolizumab monotherapy'),
('NSCLC', 25, None, False, False, 'pembrolizumab + chemotherapy'),
('NSCLC', 0, None, False, False, 'ICI + chemotherapy'),
('NSCLC', 80, None, True, False, 'targeted therapy preferred'), # EGFR+
('melanoma', None, None, False, False, 'pembrolizumab or nivolumab'),
('CRC', None, 'MSI-H', False, False, 'pembrolizumab'),
]
for cancer, pdl1, msi, egfr_pos, stk11, expected in test_cases:
desc = f"{cancer}, PD-L1={pdl1}, MSI={msi}, EGFR={egfr_pos}"
# Simple logic check
if cancer == 'NSCLC' and egfr_pos:
recommendation = 'targeted therapy preferred'
elif msi and msi.upper() in ('MSI-H', 'DMMR'):
recommendation = 'pembrolizumab'
elif cancer == 'melanoma':
recommendation = 'pembrolizumab or nivolumab'
elif cancer == 'NSCLC':
if pdl1 is not None and pdl1 >= 50:
recommendation = 'pembrolizumab monotherapy'
elif pdl1 is not None and pdl1 >= 1:
recommendation = 'pembrolizumab + chemotherapy'
else:
recommendation = 'ICI + chemotherapy'
else:
recommendation = 'pembrolizumab'
passed = recommendation == expected
log_test(f"ICI selection: {desc}", passed,
f"Expected: {expected}, Got: {recommendation}")
# ============================================================
# INTEGRATION TESTS: Full Use Cases
# ============================================================
def test_integration_nsclc_high(tu):
"""Integration test: High-biomarker NSCLC."""
print("\n=== Integration: NSCLC High Biomarker ===")
# Step 1: Cancer resolution
try:
result = tu.tools.OpenTargets_get_disease_id_description_by_name(diseaseName='non-small cell lung carcinoma')
hits = result.get('data', {}).get('search', {}).get('hits', [])
cancer_resolved = len(hits) > 0
log_test("Integration NSCLC: cancer resolved", cancer_resolved)
except Exception as e:
log_test("Integration NSCLC: cancer resolved", False, str(e)[:100])
return
# Step 2: FDA biomarker check
try:
result = tu.tools.fda_pharmacogenomic_biomarkers(drug_name='pembrolizumab', limit=100)
results = result.get('results', [])
has_tmb = any('Tumor Mutational Burden' in r.get('Biomarker', '') for r in results)
has_pdl1 = any('PD-L1' in r.get('Biomarker', '') for r in results)
log_test("Integration NSCLC: biomarkers confirmed", has_tmb and has_pdl1)
except Exception as e:
log_test("Integration NSCLC: biomarkers confirmed", False, str(e)[:100])
# Step 3: Clinical trials
try:
result = tu.tools.ClinicalTrials_search_studies(
action='search_studies', condition='NSCLC', intervention='pembrolizumab', limit=3)
has_trials = isinstance(result, dict) and len(result.get('studies', [])) > 0
log_test("Integration NSCLC: clinical trials found", has_trials)
except Exception as e:
log_test("Integration NSCLC: clinical trials found", False, str(e)[:100])
# Step 4: Score calculation
score = max(0, min(100, 30 + 10 + 20 + 10)) # TMB-high + unknown MSI + PD-L1 high + moderate neoantigen
tier = 'HIGH' if score >= 70 else 'MODERATE'
log_test("Integration NSCLC: score >= 70", score >= 70, f"Score: {score}, Tier: {tier}")
def test_integration_melanoma_braf(tu):
"""Integration test: Melanoma with BRAF V600E."""
print("\n=== Integration: Melanoma BRAF V600E ===")
# Step 1: Gene resolution
try:
result = tu.tools.MyGene_query_genes(query='BRAF')
hits = result.get('hits', [])
braf_hit = next((h for h in hits if h.get('symbol') == 'BRAF'), None)
log_test("Integration melanoma: BRAF resolved",
braf_hit is not None, f"Ensembl: {braf_hit.get('ensembl', {}).get('gene', 'N/A')}" if braf_hit else "")
except Exception as e:
log_test("Integration melanoma: BRAF resolved", False, str(e)[:100])
# Step 2: cBioPortal V600E prevalence
try:
result = tu.tools.cBioPortal_get_mutations(study_id='mel_dfci_2019', gene_list='BRAF')
data = result.get('data', []) if isinstance(result, dict) else []
v600e_count = sum(1 for m in data if 'V600E' in str(m.get('proteinChange', '')))
log_test("Integration melanoma: V600E prevalence",
v600e_count > 0, f"{v600e_count}/{len(data)} BRAF mutations are V600E")
except Exception as e:
log_test("Integration melanoma: V600E prevalence", False, str(e)[:100])
# Step 3: ICI drugs for melanoma
try:
result = tu.tools.OpenTargets_get_associated_drugs_by_disease_efoId(efoId='EFO_0000756', size=50)
rows = result.get('data', {}).get('disease', {}).get('knownDrugs', {}).get('rows', [])
ici_found = [r.get('drug', {}).get('name', '') for r in rows
if any(x in r.get('drug', {}).get('name', '').upper()
for x in ['PEMBROLIZUMAB', 'NIVOLUMAB', 'IPILIMUMAB'])]
log_test("Integration melanoma: ICIs available",
len(ici_found) > 0, f"ICIs: {', '.join(list(set(ici_found))[:3])}")
except Exception as e:
log_test("Integration melanoma: ICIs available", False, str(e)[:100])
# Step 4: Score
score = max(0, min(100, 20 + 5 + 20 + 10)) # TMB-intermediate + MSS + PD-L1 high + moderate neoantigen
tier = 'MODERATE'
log_test("Integration melanoma: moderate score", 40 <= score <= 69,
f"Score: {score}, Tier: {tier}")
def test_integration_msih_crc(tu):
"""Integration test: MSI-H colorectal cancer."""
print("\n=== Integration: MSI-H CRC ===")
# Step 1: CRC resolution
try:
result = tu.tools.OpenTargets_get_disease_id_description_by_name(diseaseName='colorectal cancer')
hits = result.get('data', {}).get('search', {}).get('hits', [])
log_test("Integration MSI-H CRC: cancer resolved", len(hits) > 0)
except Exception as e:
log_test("Integration MSI-H CRC: cancer resolved", False, str(e)[:100])
# Step 2: MSI-H FDA approval
try:
result = tu.tools.fda_pharmacogenomic_biomarkers(biomarker='Microsatellite Instability', limit=100)
results = result.get('results', [])
pembro_msi = any('Pembrolizumab' in r.get('Drug', '') for r in results)
log_test("Integration MSI-H CRC: FDA MSI-H approval", pembro_msi)
except Exception as e:
log_test("Integration MSI-H CRC: FDA MSI-H approval", False, str(e)[:100])
# Step 3: Score
score = max(0, min(100, 30 + 25 + 10 + 15 + 5)) # TMB-high + MSI-H + unknown PD-L1 + high neoantigen + bonus
log_test("Integration MSI-H CRC: high score", score >= 80, f"Score: {score}")
def test_integration_low_nsclc_stk11(tu):
"""Integration test: Low-biomarker NSCLC with STK11."""
print("\n=== Integration: Low NSCLC + STK11 ===")
# Step 1: STK11 gene resolution
try:
result = tu.tools.MyGene_query_genes(query='STK11')
hits = result.get('hits', [])
stk11_hit = next((h for h in hits if h.get('symbol') == 'STK11'), None)
log_test("Integration low NSCLC: STK11 resolved", stk11_hit is not None)
except Exception as e:
log_test("Integration low NSCLC: STK11 resolved", False, str(e)[:100])
# Step 2: PubMed evidence for STK11 + ICI resistance
try:
result = tu.tools.PubMed_search_articles(
query='STK11 NSCLC immunotherapy resistance', max_results=5)
has_articles = isinstance(result, list) and len(result) > 0
log_test("Integration low NSCLC: resistance literature", has_articles,
f"Found {len(result) if isinstance(result, list) else 0} articles")
except Exception as e:
log_test("Integration low NSCLC: resistance literature", False, str(e)[:100])
# Step 3: Score
score = max(0, min(100, 5 + 10 + 5 + 5 + (-10))) # TMB-very-low + unknown MSI + PD-L1 neg + low neoantigen + STK11
log_test("Integration low NSCLC: low score", score < 40, f"Score: {score}")
def test_integration_bladder(tu):
"""Integration test: Bladder cancer moderate."""
print("\n=== Integration: Bladder Cancer ===")
# Step 1: Bladder resolution
try:
result = tu.tools.OpenTargets_get_disease_id_description_by_name(diseaseName='urothelial carcinoma')
hits = result.get('data', {}).get('search', {}).get('hits', [])
log_test("Integration bladder: cancer resolved", len(hits) > 0)
except Exception as e:
log_test("Integration bladder: cancer resolved", False, str(e)[:100])
# Step 2: ICI drugs for bladder
try:
result = tu.tools.ClinicalTrials_search_studies(
action='search_studies', condition='bladder cancer', intervention='pembrolizumab', limit=3)
has_trials = isinstance(result, dict) and len(result.get('studies', [])) > 0
log_test("Integration bladder: trials found", has_trials)
except Exception as e:
log_test("Integration bladder: trials found", False, str(e)[:100])
# Step 3: Score
score = max(0, min(100, 20 + 10 + 12 + 10)) # TMB-intermediate + unknown MSI + PD-L1 positive + moderate neoantigen
log_test("Integration bladder: moderate score", 40 <= score <= 69, f"Score: {score}")
# ============================================================
# EDGE CASE TESTS
# ============================================================
def test_edge_no_biomarkers(tu):
"""Test with no biomarkers - only cancer type."""
print("\n=== Edge Case: No Biomarkers ===")
score = max(0, min(100, 15 + 10 + 10 + 8)) # All neutral/unknown
tier = 'MODERATE' if score >= 40 else 'LOW'
log_test("Edge: no biomarkers score", 35 <= score <= 55,
f"Score: {score}, Tier: {tier}")
def test_edge_conflicting_biomarkers(tu):
"""Test with conflicting biomarkers (high TMB + resistance)."""
print("\n=== Edge Case: Conflicting Biomarkers ===")
# High TMB but JAK2 resistance
score = max(0, min(100, 30 + 10 + 5 + 12 + (-10))) # TMB-high + unknown MSI + PD-L1 neg + moderate neoantigen + JAK2
log_test("Edge: high TMB + JAK2", 40 <= score <= 55,
f"Score: {score}")
def test_edge_score_floor_cap(tu):
"""Test score floor (0) and cap (100)."""
print("\n=== Edge Case: Score Floor/Cap ===")
# Extreme low: multiple resistance
extreme_low = max(0, min(100, 5 + 5 + 5 + 5 + (-10) + (-15) + (-10) + (-5)))
log_test("Edge: extreme resistance floor", extreme_low == 0,
f"Score: {extreme_low} (should be 0)")
# Extreme high: all maxed
extreme_high = max(0, min(100, 30 + 25 + 20 + 15 + 10))
log_test("Edge: all maxed cap", extreme_high == 100,
f"Score: {extreme_high} (should be 100)")
def test_edge_rare_cancer(tu):
"""Test with rare cancer type."""
print("\n=== Edge Case: Rare Cancer ===")
try:
result = tu.tools.OpenTargets_get_disease_id_description_by_name(diseaseName='cholangiocarcinoma')
hits = result.get('data', {}).get('search', {}).get('hits', [])
log_test("Edge: rare cancer resolution", len(hits) > 0,
f"Found {len(hits)} hits")
except Exception as e:
log_test("Edge: rare cancer resolution", False, str(e)[:100])
# ============================================================
# ADDITIONAL TOOL TESTS
# ============================================================
def test_fda_mechanism_of_action(tu):
"""Test FDA mechanism of action for ICI drugs."""
print("\n=== Additional: FDA Mechanism of Action ===")
try:
result = tu.tools.FDA_get_mechanism_of_action_by_drug_name(drug_name='pembrolizumab', limit=3)
has_data = isinstance(result, dict) and 'results' in result and len(result['results']) > 0
if has_data:
moa_text = str(result['results'][0])[:200]
has_pd1 = 'PD-1' in moa_text or 'programmed death' in moa_text.lower() or 'PD' in moa_text
log_test("FDA MOA: pembrolizumab", has_pd1, f"Contains PD-1 reference")
else:
log_test("FDA MOA: pembrolizumab", False, "No results")
except Exception as e:
log_test("FDA MOA: pembrolizumab", False, str(e)[:100])
def test_drugbank_targets(tu):
"""Test DrugBank target retrieval for ICIs."""
print("\n=== Additional: DrugBank Targets ===")
try:
result = tu.tools.drugbank_get_targets_by_drug_name_or_drugbank_id(
query='pembrolizumab', case_sensitive=False, exact_match=True, limit=5)
has_data = isinstance(result, dict) and 'results' in result
if has_data:
results = result['results']
log_test("DrugBank targets: pembrolizumab", len(results) > 0,
f"Found {len(results)} target entries")
else:
log_test("DrugBank targets: pembrolizumab", False, "No results")
except Exception as e:
log_test("DrugBank targets: pembrolizumab", False, str(e)[:100])
def test_vep_annotation(tu):
"""Test VEP annotation for BRAF V600E."""
print("\n=== Additional: VEP Annotation ===")
try:
result = tu.tools.EnsemblVEP_annotate_rsid(variant_id='rs113488022')
# BRAF V600E rsid
if isinstance(result, dict):
has_braf = 'BRAF' in str(result)
has_consequence = 'missense_variant' in str(result)
log_test("VEP annotation: BRAF V600E (rs113488022)", has_braf and has_consequence,
f"BRAF found: {has_braf}, missense: {has_consequence}")
else:
log_test("VEP annotation: BRAF V600E", False, f"Type: {type(result).__name__}")
except Exception as e:
log_test("VEP annotation: BRAF V600E", False, str(e)[:100])
# ============================================================
# MAIN
# ============================================================
def main():
global TESTS_RUN, TESTS_PASSED, TESTS_FAILED, FAILURES
print("=" * 70)
print("IMMUNOTHERAPY RESPONSE PREDICTION SKILL - TEST SUITE")
print("=" * 70)
tu = init_tu()
# Phase 1: Input Standardization
test_phase1_cancer_resolution(tu)
test_phase1_gene_resolution(tu)
test_phase1_ensembl_lookup(tu)
# Phase 2: TMB Analysis
test_phase2_tmb_classification(tu)
test_phase2_fda_tmb_biomarker(tu)
# Phase 3: Neoantigen Analysis
test_phase3_neoantigen_estimation(tu)
test_phase3_protein_function(tu)
test_phase3_iedb_epitopes(tu)
# Phase 4: MSI/MMR Status
test_phase4_msi_scoring(tu)
test_phase4_fda_msi_biomarker(tu)
# Phase 5: PD-L1 Expression
test_phase5_pdl1_scoring(tu)
test_phase5_pdl1_prognostics(tu)
# Phase 6: Immune Microenvironment
test_phase6_immune_gene_prognostics(tu)
test_phase6_pathway_enrichment(tu)
# Phase 7: Mutation-Based Predictors
test_phase7_resistance_scoring(tu)
test_phase7_sensitivity_scoring(tu)
test_phase7_cbio_mutations(tu)
# Phase 8: Clinical Evidence & ICI Options
test_phase8_fda_indications(tu)
test_phase8_ot_drug_lookup(tu)
test_phase8_drug_moa(tu)
test_phase8_drugs_for_melanoma(tu)
test_phase8_drugbank_info(tu)
test_phase8_clinical_trials(tu)
test_phase8_pubmed_evidence(tu)
# Phase 9: Resistance Risk
test_phase9_civic_evidence(tu)
test_phase9_gene_constraints(tu)
# Phase 10: Score Integration
test_phase10_score_calculation(tu)
# Phase 11: Clinical Recommendations
test_phase11_ici_selection_nsclc(tu)
# Integration Tests
test_integration_nsclc_high(tu)
test_integration_melanoma_braf(tu)
test_integration_msih_crc(tu)
test_integration_low_nsclc_stk11(tu)
test_integration_bladder(tu)
# Edge Cases
test_edge_no_biomarkers(tu)
test_edge_conflicting_biomarkers(tu)
test_edge_score_floor_cap(tu)
test_edge_rare_cancer(tu)
# Additional Tool Tests
test_fda_mechanism_of_action(tu)
test_drugbank_targets(tu)
test_vep_annotation(tu)
# Summary
print("\n" + "=" * 70)
print("TEST SUMMARY")
print("=" * 70)
print(f"Total tests: {TESTS_RUN}")
print(f"Passed: {TESTS_PASSED}")
print(f"Failed: {TESTS_FAILED}")
print(f"Pass rate: {TESTS_PASSED/TESTS_RUN*100:.1f}%")
if FAILURES:
print(f"\nFailed tests ({len(FAILURES)}):")
for f in FAILURES:
print(f" - {f}")
print("=" * 70)
return TESTS_FAILED == 0
if __name__ == "__main__":
success = main()
exit(0 if success else 1)
Immunotherapy Response Prediction - Tools Reference
Tools Used by Phase
Phase 1: Input Standardization & Cancer Context
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
OpenTargets_get_disease_id_description_by_name | diseaseName | {data: {search: {hits: [{id, name, description}]}}} | Resolve cancer to EFO ID |
MyGene_query_genes | query | {hits: [{_id, symbol, name, ensembl: {gene}}]} | Resolve gene to Ensembl/Entrez IDs |
ensembl_lookup_gene | gene_id, species='homo_sapiens' | {data: {id, display_name, description, biotype}} | Gene details |
Phase 2: TMB Analysis
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
fda_pharmacogenomic_biomarkers | drug_name, biomarker, limit | {count, shown, results: [{Drug, Biomarker, TherapeuticArea, LabelingSection}]} | FDA TMB-H approvals |
Phase 3: Neoantigen Analysis
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
UniProt_get_function_by_accession | accession | List of strings | Protein function for neoantigen assessment |
iedb_search_epitopes | organism_name, source_antigen_name | {status, data, count} | Known epitopes |
EnsemblVEP_annotate_rsid | variant_id | VEP annotation with SIFT/PolyPhen | Variant impact |
Phase 4: MSI/MMR Status
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
fda_pharmacogenomic_biomarkers | biomarker='Microsatellite Instability', limit | FDA MSI-H approvals | MSI-H drug approvals |
Phase 5: PD-L1 Expression
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
HPA_get_cancer_prognostics_by_gene | gene_name='CD274' | Cancer prognostic data | PD-L1 prognostic context |
HPA_get_rna_expression_by_source | gene_name, source_type, source_name (ALL 3 required) | Expression data | Baseline expression |
Phase 6: Immune Microenvironment
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
HPA_get_cancer_prognostics_by_gene | gene_name | Cancer prognostics | Immune gene prognostics |
enrichr_gene_enrichment_analysis | gene_list (array), libs (array, REQUIRED) | Enrichment results | Immune pathway analysis |
Phase 7: Mutation-Based Predictors
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
cBioPortal_get_mutations | study_id, gene_list (string!) | {data: [{proteinChange, mutationType, studyId, ...}]} | Mutation prevalence |
Phase 8: Clinical Evidence & ICI Options
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
FDA_get_indications_by_drug_name | drug_name, limit | {meta, results} | FDA-approved indications |
FDA_get_mechanism_of_action_by_drug_name | drug_name, limit | {meta, results} | Drug mechanism |
FDA_get_clinical_studies_info_by_drug_name | drug_name, limit | {meta, results} | Clinical study data |
OpenTargets_get_drug_mechanisms_of_action_by_chemblId | chemblId | {data: {drug: {mechanismsOfAction: {rows}}}} | Drug MOA |
OpenTargets_get_associated_drugs_by_disease_efoId | efoId, size | {data: {disease: {knownDrugs: {count, rows}}}} | Drugs for cancer |
OpenTargets_get_approved_indications_by_drug_chemblId | chemblId | Approved indications | Drug approvals |
drugbank_get_drug_basic_info_by_drug_name_or_id | query, case_sensitive, exact_match, limit (ALL 4) | Drug info | Drug details |
drugbank_get_targets_by_drug_name_or_drugbank_id | query, case_sensitive, exact_match, limit (ALL 4) | Drug targets | ICI targets |
drugbank_get_pharmacology_by_drug_name_or_drugbank_id | query, case_sensitive, exact_match, limit (ALL 4) | Pharmacology | Drug pharmacology |
search_clinical_trials | condition, intervention, query_term, pageSize | {total_count, studies} | Active ICI trials |
PubMed_search_articles | query, limit | {status, data, metadata} | Literature evidence |
Phase 9: Resistance Risk Assessment
| Tool | Parameters | Response | Purpose |
|---|---|---|---|
civic_search_evidence_items | therapy_name, disease_name | {data: {evidenceItems: {nodes}}} | Resistance evidence |
gnomad_get_gene_constraints | gene_symbol | Gene constraint metrics | Gene essentiality |
Key ICI Drug Reference
| Drug | ChEMBL ID | DrugBank ID | Target |
|---|---|---|---|
| Pembrolizumab | CHEMBL3137343 | DB09037 | PD-1 (PDCD1) |
| Nivolumab | CHEMBL2108738 | DB09035 | PD-1 (PDCD1) |
| Atezolizumab | CHEMBL3707227 | DB11595 | PD-L1 (CD274) |
| Durvalumab | CHEMBL3301587 | DB11714 | PD-L1 (CD274) |
| Ipilimumab | CHEMBL1789844 | DB06186 | CTLA-4 |
| Avelumab | CHEMBL3833373 | DB11945 | PD-L1 (CD274) |
| Cemiplimab | CHEMBL4297723 | DB14716 | PD-1 (PDCD1) |
Key Gene IDs
| Gene | Ensembl ID | Entrez ID | UniProt | Role |
|---|---|---|---|---|
| PDCD1 (PD-1) | ENSG00000188389 | 5133 | Q15116 | ICI target |
| CD274 (PD-L1) | ENSG00000120217 | 29126 | Q9NZQ7 | ICI target |
| CTLA4 | ENSG00000163599 | 1493 | P16410 | ICI target |
| BRAF | ENSG00000157764 | 673 | P15056 | Driver mutation |
| STK11 | ENSG00000118046 | 6794 | Q15831 | Resistance |
| PTEN | ENSG00000284792 | 5728 | P60484 | Resistance |
| JAK1 | ENSG00000162434 | 3716 | P23458 | Resistance |
| JAK2 | ENSG00000096968 | 3717 | O60674 | Resistance |
| B2M | ENSG00000166710 | 567 | P61769 | Resistance |
| KEAP1 | ENSG00000079999 | 9817 | Q14145 | Resistance |
| POLE | ENSG00000177084 | 5426 | Q07864 | Sensitivity |
| MLH1 | ENSG00000076242 | 4292 | P40692 | MMR |
| MSH2 | ENSG00000095002 | 4436 | P43246 | MMR |
| MSH6 | ENSG00000116062 | 2956 | P52701 | MMR |
| PMS2 | ENSG00000122512 | 5395 | P54278 | MMR |
Common Parameter Mistakes
| Wrong | Correct | Tool |
|---|---|---|
q | query | MyGene_query_genes |
rsid | variant_id | EnsemblVEP_annotate_rsid |
gene_list=['BRAF'] | gene_list='BRAF' | cBioPortal_get_mutations |
| 3 params | ALL 4 params required | All drugbank_* tools |
no species | species='homo_sapiens' | ensembl_lookup_gene |
genericName | drugName | OpenTargets_get_drug_id_description_by_name |
Related skills
FAQ
What inputs does tooluniverse-immunotherapy-response-prediction use?
tooluniverse-immunotherapy-response-prediction uses multi-omic and clinical features to estimate immunotherapy response likelihood. Developers apply it when designing stratified trials or selecting biomarker panels in oncology informatics pipelines.
Who should use the ToolUniverse immunotherapy skill?
tooluniverse-immunotherapy-response-prediction suits developers building computational oncology tools or research agents in the Harvard ToolUniverse ecosystem, not general-purpose application or frontend development tasks.