Skip to main content
Glama
ngs-qc-mcp

ngs-qc-mcp

by 5x5x5x5
README.md
# ngs-qc-triage

Sequencing-run QC triage agent, SOP clause retriever (RAG), MCP server, and cross-site transfer manifest generator.

Part of **Automate My Old Jobs — Stop 4 (Bioinformatics Software Engineer, Q² Solutions / Q² Genomics)**, based on four years supporting next-generation sequencing (NGS) QC and cross-site data transfers for a satellite Illumina lab in Beijing.

## What Is Automated vs. What Stays Human

| Automated by `ngs-qc-triage` | Stays Human (Bioinformatician / Wet-Lab Lead) |
|---|---|
| Parse Illumina `bcl2fastq` (`Stats.json`) and `FastQC` (`fastqc_data.txt`, `*_fastqc.zip`) into typed metrics | Resolving every `ESCALATE` flag (suspected GC contamination, Read 2 phasing drop, >20% undetermined reads, lane-wide defects, truncated files) |
| Run deterministic threshold, pool-dropout, and lane-coherence checks (zero LLM arithmetic) | Authorizing wet-lab re-sequencing or library-prep repeats |
| Apply assay-aware biological exceptions (`SOP-NGS-042 §4.2` for targeted panels, amplicons, RNA-seq) | Verifying whether LIMS `assay_type` metadata or sample labels were swapped upstream |
| Retrieve exact `SOP-NGS-042` clause citations for every decision | Granting sponsor waivers for out-of-spec clinical samples |
| Emit deterministic `transfer_manifest.csv`, `quarantine_manifest.csv`, Markdown report, and ops telemetry | External communication with the satellite wet-lab lead and study sponsor |

## Architecture

1. **Deterministic Parsers & Rule Engine (`parsers.py`, `rules.py`):** Reads real Illumina `bcl2fastq` `Stats.json` and `FastQC` archives. Arithmetic, `%PF`, `%Q30`, Read 2 phasing drops, lane medians, and lane-wide defect detection run in pure Python—never delegated to an LLM.
2. **SOP Retrieval (`sop_rag.py`):** Hybrid BM25 + character n-gram retriever over [`data/sops/SOP-NGS-042-qc-and-transfer.md`](data/sops/SOP-NGS-042-qc-and-transfer.md), returning verbatim clauses and exact section IDs (`SOP-NGS-042 §3.1`–`§7.1`).
3. **Tool-Using Triage Agent (`agent.py`):** Executes the structured tool trace (`parse_run_qc` → `evaluate_qc_rules` → `search_sop` → `emit_manifests`), records wall-clock latency, tool calls, token/cost estimates, and escalation rate. Runs keyless in `offline` mode by default or uses any OpenAI-compatible endpoint (`--llm-mode openai_compat`) for grounded narrative synthesis.
4. **MCP Server (`mcp_server.py`):** Exposes `inspect_run_qc`, `search_sop`, and `triage_sequencing_run` over the Model Context Protocol (`FastMCP`) so agent clients can inspect runs interactively.

## Benchmark: Naive Thresholds vs. SOP-RAG Tool Agent

Evaluated across **12 scenarios (45 samples)** combining real MIT-licensed Illumina `bcl2fastq` runs and `FastQC` archives from `MultiQC/test-data` with realistic satellite-lab edge cases (`evals/benchmark.py`):

| Metric | Naive Thresholds | SOP-RAG Tool Agent |
|---|---:|---:|
| Scenarios / Samples | 12 / 45 | 12 / 45 |
| Exact Triage Accuracy | 82.2% | **100.0%** |
| Transfer Manifest Accuracy | 82.2% | **100.0%** |
| **False-PASS Count (Critical)** | **6** (13.3%) | **0** (0.0%) |
| False-Quarantine Count | 2 | **0** |
| SOP Citation Recall | 41.7% | **100.0%** |
| Latency p50 / p95 (offline) | 0.17 ms / 0.58 ms | **0.52 ms / 3.92 ms** |

**What naive threshold scripts got wrong:**
- **False-PASS (6 critical errors):** Released human WGS with GC contamination (`§4.3`), a 14-point Read 2 phasing drop masked by 86% overall Q30 (`§3.2`), a lane with 26.5% undetermined reads (`§3.3`), a marginal `WARN` sample sitting on a defective lane (`§5.1`), and a truncated FastQC file (`§6.1`).
- **False-Quarantine (2 errors):** Failed valid `targeted_panel` and `amplicon` samples for expected FastQC `Sequence Duplication Levels` flags (`§4.2`).

### Real Public Runs Included

Sample outputs generated directly from real `MultiQC/test-data` Illumina runs:
- `170919_D00446_0258_BCBDHPANXX` (8 lanes, 25 samples): **PASS** — 25/25 cleared for transfer.
- `170303_ST-E00266_0192_BHGYKCALXX` Lane 8 (`illumina_real_run_b`): **FAIL** — caught real `%PF=53.9%`, `%Q30=71.9%`, and a 21.9-pt Read 2 drop (`82.9% → 61.0%`).
- `170303_ST-E00266_0192_BHGYKCALXX` Lanes 1–7 (`illumina_real_run_c`): **ESCALATE** — caught real 13.9–17.4 pt Read 2 phasing drops on Lanes 1–3 and lane-wide Q30 degradation across Lanes 4–7 (committed sample report in [`examples/hiseqx_run_c_output/triage_report.md`](examples/hiseqx_run_c_output/triage_report.md)).

### Where It Fails (Honest Limits)

1. **Upstream LIMS metadata errors:** If a lab mislabels a PCR-overamplified WGS sample as `targeted_panel` in `run_metadata.json`, the agent trusts the metadata and applies the `§4.2` duplication exemption.
2. **QC-invisible sample swaps:** If two human libraries with identical quality metrics are swapped on the plate, `Stats.json` and `FastQC` look clean—detecting swaps requires downstream alignment, sex-chromosome checks, or SNP fingerprinting.
3. **Novel failure modes outside `SOP-NGS-042`:** Unusual tile-edge optical artifacts or subtle adapter bleed below FastQC's fail threshold are only caught when humans inspect plots or downstream alignment metrics.

## Build Time

- **Hours to build (v0.1):** ~1.5 hours (domain SOP authoring, `bcl2fastq`/`FastQC` parsers, hybrid SOP retriever, deterministic rule engine, tool-calling agent + telemetry, MCP server, 12-scenario benchmark, and tests).

## Quickstart

```bash
uv sync --extra dev

# Triage a real public Illumina run and write manifests + Markdown report
uv run ngs-qc-triage triage data/public_runs/illumina_real_run_c --out out/run_c

# Search SOP-NGS-042 clauses directly
uv run ngs-qc-triage sop "targeted panel duplication exception"

# Run the 12-scenario benchmark (Naive vs. SOP-RAG Tool Agent)
uv run python -m evals.benchmark

# Run the test suite and linter
uv run pytest -v
uv run ruff check src tests evals

# Start the MCP server (stdio)
uv run ngs-qc-mcp
```

## Data & License

- Code: MIT License ([`LICENSE`](LICENSE)).
- Public Illumina `bcl2fastq` and `FastQC` sample data: [MultiQC/test-data](https://github.com/MultiQC/test-data), MIT License (see [`data/public_runs/ATTRIBUTION.md`](data/public_runs/ATTRIBUTION.md)). No proprietary or patient data is included.

TDQS

B3.2/5.0

Scored across 3 tools

Disambiguation4/5

search_sop (policy retrieval), inspect_run_qc (metric parsing), and triage_sequencing_run (end-to-end orchestration) each target a distinct step, but inspect_run_qc vs triage_sequencing_run overlap since triage almost certainly performs the same parsing internally. Descriptions do help an agent choose: inspect for raw metrics only, triage for decisions/citations/manifests.

Naming Consistency5/5

All three names follow a consistent snake_case verb_object pattern (search_sop, inspect_run_qc, triage_sequencing_run) with clear action verbs. No mixing of conventions or vague verbs like 'process' or 'run'.

Tool Count4/5

Three tools is on the lean side but matches a narrow, well-defined purpose: retrieve criteria, compute metrics, and produce triage. Each tool clearly earns its place with no padding.

Completeness3/5

The core triage workflow (retrieve SOP criteria, inspect metrics, emit decisions) is covered, but the surface is a dead end for related needs: search_sop only targets one hardcoded SOP, and there is no way to list discoverable runs, compare runs, or export/re-run triage results.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues