Repository navigation
[WIP] Agentic/MCP skill wrapper pattern for MONAI Deploy operators #590
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| --- | ||
| name: monai-agent-lung-nodule | ||
| description: Agent-callable wrapper exposing a MONAI Deploy lung-nodule segmentation operator as an MCP-style tool, with structured, schema-validated output for downstream clinical review. Not for clinical interpretation. | ||
| license: Apache-2.0 | ||
| allowed-tools: Bash | ||
| metadata: | ||
| author: Khaled Younis | ||
| tags: | ||
| - MONAI Deploy | ||
| - agentic | ||
| - MCP | ||
| - thoracic | ||
| - segmentation | ||
| --- | ||
|
|
||
| # MONAI Agent: Lung Nodule Segmentation Tool | ||
|
|
||
| ## Purpose | ||
| - Exposes a MONAI Deploy lung-nodule segmentation operator (`SegResNet`-based) as a single agent-callable | ||
| tool, so an LLM or agent orchestrator can request "screen this CT for pulmonary nodules" without | ||
| reading operator source, notebooks, or manuals. | ||
| - Demonstrates the general pattern proposed for MONAI Deploy: any existing `Operator` can be wrapped this | ||
| way and registered in an MCP tool registry, discoverable and invocable by an agent at runtime instead of | ||
| being hardcoded into a fixed execution graph. | ||
| - Manifest I/O: inputs are `dicom_study_id` (or a local NIfTI/CT volume path) and an optional | ||
| `sensitivity_threshold`; outputs are a `result_json` evidence pack containing per-nodule findings and a | ||
| Fleischner Society follow-up recommendation per finding. | ||
| - Not for clinical interpretation, autonomous diagnosis, or regulatory submission. Every output is marked | ||
| `AI_Generated: true` and requires clinician sign-off before any clinical use. | ||
|
|
||
| ## Instructions | ||
| - Read `skill_manifest.yaml` before changing arguments, side effects, or validation gates. | ||
| - Run `scripts/run_agent_lung_nodule.py` through the documented command below. | ||
| - If a host agent exposes `run_script`, use | ||
| `run_script("scripts/run_agent_lung_nodule.py", args=[...])`; otherwise run the Python command shown below. | ||
| - Real inference requires `torch` and `monai` installed; when either is unavailable the script falls back | ||
| to a deterministic simulation mode so the tool contract and downstream verifier can still be exercised | ||
| without a GPU. | ||
| - Check the emitted `result_json` and the paired verifier's report before treating a run as evidence. | ||
|
|
||
| ## Available Scripts | ||
| | Script | Purpose | Arguments | | ||
| |---|---|---| | ||
| | `scripts/run_agent_lung_nodule.py` | Primary entrypoint declared by `skill_manifest.yaml`. | `--study-id ID [--sensitivity-threshold 0.0-1.0] [--output-dir OUT_DIR] [--mock]` | | ||
|
|
||
| ## Prerequisites | ||
| - Runtime requirements: Python 3.10+. Real mode additionally requires `torch` and `monai` (GPU/CUDA used | ||
| automatically when available; CPU fallback supported but slower). | ||
| - Side effects: writes `result_json` under a caller-provided `--output-dir`; downloads no external data — | ||
| the current implementation operates on a synthetic 3D tensor for architecture validation. A production | ||
| version would source the volume from `dicom_series_to_volume_operator` per MONAI Deploy convention. | ||
| - Run commands from the skill directory root unless otherwise noted. | ||
|
|
||
| ## Limitations | ||
| - This is a reference implementation for the agentic-wrapper pattern, not a validated clinical model. The | ||
| segmentation backbone is an untrained `SegResNet` instance; findings are architecturally real (real | ||
| forward pass, real tensor shapes, real timing) but not clinically meaningful until wired to a trained, | ||
| validated bundle (e.g. via `monai_bundle_inference_operator`, matching `ai_spleen_seg_app` convention). | ||
| - No PHI is read, stored, or transmitted by this skill. It operates on a synthetic volume or a caller- | ||
| supplied de-identified/public volume only (e.g. TCIA). See "Data governance" below. | ||
| - Device auto-detected (`cuda` if available, else `cpu`). | ||
| - Not for clinical deployment, clinical interpretation, autonomous diagnosis, or regulatory submission. | ||
|
|
||
| ## Data governance | ||
| This skill changes how an already-permitted operator is *invoked* — it does not change where inference | ||
| runs or where data goes. Two supported deployment modes: | ||
| 1. **Local / on-prem** — the MCP server and GPU inference run inside the institution's network, exactly as | ||
| any MONAI Deploy MAP does today; nothing crosses the boundary that wasn't already crossing it. | ||
| 2. **Public-dataset / research** — a hosted server operating on de-identified public data (e.g. TCIA); no | ||
| PHI in scope. | ||
|
|
||
| A real clinical PHI use case (a clinician sending live patient data through a hosted MCP server) is a | ||
| separate, harder problem requiring data-use agreements and a security review — this skill does not attempt | ||
| to solve that, and should not be represented as solving it. | ||
|
|
||
| ## Troubleshooting | ||
| | Error | Cause | Fix | | ||
| |---|---|---| | ||
| | `ImportError: No module named 'monai'` | Real mode requested without MONAI/PyTorch installed. | Install `monai` and `torch`, or omit `--mock`-forcing flags to use the auto-detected simulation fallback. | | ||
| | Empty or schema-invalid `result_json` | Wrong `--study-id`, or upstream operator failure. | Re-run with `--mock` against a known fixture and inspect stderr. | | ||
| | Validation gate failure | Output violated a declared invariant (e.g. missing `AI_Generated` flag, diameter/volume out of physical bounds). | Keep the failed evidence pack and use the paired verifier's gate message to repair inputs or wrapper code. | | ||
|
|
||
| ## Exact Runnable Surface | ||
| ```bash | ||
| python skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py \ | ||
| --study-id STUDY_CT_2026_0813 --sensitivity-threshold 0.80 --output-dir OUT_DIR | ||
| ``` | ||
| Add `--mock` to force the simulation path (no GPU/MONAI required) — useful for CI, where GPU is not | ||
| currently available (see `tests/`, which skip the real-mode assertions accordingly). | ||
|
|
||
| ## Usage | ||
| ```bash | ||
| python -m pip install torch monai # optional — real mode only | ||
| python skills/monai-agent-lung-nodule/scripts/run_agent_lung_nodule.py \ | ||
| --study-id STUDY_CT_2026_0813 --output-dir vista_lung_outputs | ||
| ``` | ||
| The findings' Fleischner Society follow-up category and per-class volume/diameter checks are audited by | ||
| `verifiers/agent_output_quality_v1`, which does not re-run inference — it grades the emitted evidence pack | ||
| for schema validity, physical plausibility, and reproducibility. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| # Copyright 2026 MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """ | ||
| run_agent_lung_nodule.py - MONAI Agent Lung Nodule Skill entrypoint | ||
| ===================================================================== | ||
| Reference implementation of an agent/MCP-callable wrapper around a MONAI Deploy | ||
| segmentation operator. See ../SKILL.md and ../skill_manifest.yaml for the | ||
| declared I/O contract and validation gates this script must satisfy. | ||
|
|
||
| Modes: | ||
| REAL MODE (auto-enabled when torch and monai are importable): | ||
| - Instantiates monai.networks.nets.SegResNet | ||
| - Executes a real PyTorch 3D forward pass on GPU (CUDA) or CPU | ||
| - Captures actual inference latency and voxel metrics | ||
| SIMULATION MODE (--mock, or auto-fallback when monai/torch unavailable): | ||
| - Deterministic clinical fixtures, no GPU/model dependency | ||
| - Used by CI, which currently has no GPU runner available (see tests/) | ||
|
|
||
| No PHI is read, stored, or transmitted by this script. See "Data governance" | ||
| in SKILL.md. | ||
| """ | ||
|
|
||
| import argparse | ||
| import json | ||
| import sys | ||
| import time | ||
| from pathlib import Path | ||
| from typing import Any, Dict, List | ||
|
|
||
| try: | ||
| import torch | ||
|
|
||
| from monai.networks.nets import SegResNet | ||
|
|
||
| MONAI_AVAILABLE = True | ||
| except ImportError: | ||
| MONAI_AVAILABLE = False | ||
|
|
||
|
|
||
| FLEISCHNER_ACTION_MM = 6.0 | ||
|
|
||
|
|
||
| def _fleischner_status(diameter_mm: float) -> str: | ||
| if diameter_mm >= FLEISCHNER_ACTION_MM: | ||
| return "ACTION REQUIRED: Follow-up CT at 6-12 months (solid nodule >= 6mm)" | ||
| return "BENIGN RANGE: No routine follow-up required (< 6mm)" | ||
|
|
||
|
|
||
| def run_real(study_id: str, sensitivity_threshold: float) -> Dict[str, Any]: | ||
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | ||
| model = SegResNet(spatial_dims=3, in_channels=1, out_channels=2).to(device) | ||
| model.eval() | ||
|
|
||
| start = time.time() | ||
| # Synthetic 3D CT volume tensor for architecture validation. A production | ||
| # wrapper sources this from dicom_series_to_volume_operator per MONAI | ||
| # Deploy convention instead of random data. | ||
| img_tensor = torch.rand((1, 1, 64, 64, 64), device=device) | ||
| with torch.no_grad(): | ||
| output = model(img_tensor) | ||
| inference_ms = int((time.time() - start) * 1000) | ||
|
|
||
| predicted_mask = output.argmax(dim=1) | ||
| volume_voxels = int((predicted_mask > 0).sum().item()) | ||
| diameter_mm = 7.2 # placeholder pending a trained, validated bundle | ||
|
|
||
| findings: List[Dict[str, Any]] = [] | ||
| if volume_voxels > 0: | ||
| findings.append( | ||
| { | ||
| "nodule_id": "REAL_N1", | ||
| "location_slice": 32, | ||
| "volume_voxels": volume_voxels, | ||
| "volume_mm3": round(volume_voxels * 0.85, 2), | ||
| "max_diameter_mm": diameter_mm, | ||
| "confidence_score": 0.93, | ||
| "fleischner_status": _fleischner_status(diameter_mm), | ||
| "AI_Generated": True, | ||
| "Verification_Status": "Pending", | ||
| } | ||
| ) | ||
|
|
||
| return { | ||
| "study_id": study_id, | ||
| "status": "success", | ||
| "nodules_detected": len(findings), | ||
| "findings": findings, | ||
| "execution_metadata": { | ||
| "mode": "real_monai", | ||
| "device": str(device), | ||
| "model_version": "monai.networks.nets.SegResNet (v1.3+)", | ||
| "sensitivity_threshold": sensitivity_threshold, | ||
| "inference_time_ms": inference_ms, | ||
| }, | ||
| } | ||
|
|
||
|
|
||
| def run_mock(study_id: str, sensitivity_threshold: float) -> Dict[str, Any]: | ||
| findings = [ | ||
| { | ||
| "nodule_id": "N1", | ||
| "location_slice": 42, | ||
| "volume_mm3": 310.5, | ||
| "max_diameter_mm": 8.4, | ||
| "confidence_score": 0.94, | ||
| "fleischner_status": _fleischner_status(8.4), | ||
| "AI_Generated": True, | ||
| "Verification_Status": "Pending", | ||
| }, | ||
| { | ||
| "nodule_id": "N2", | ||
| "location_slice": 88, | ||
| "volume_mm3": 45.2, | ||
| "max_diameter_mm": 3.1, | ||
| "confidence_score": 0.88, | ||
| "fleischner_status": _fleischner_status(3.1), | ||
| "AI_Generated": True, | ||
| "Verification_Status": "Pending", | ||
| }, | ||
| ] | ||
| return { | ||
| "study_id": study_id, | ||
| "status": "success", | ||
| "nodules_detected": len(findings), | ||
| "findings": findings, | ||
| "execution_metadata": { | ||
| "mode": "simulated_monai", | ||
| "device": "simulated_host", | ||
| "model_version": "monai-segresnet-v2.1-mock", | ||
| "sensitivity_threshold": sensitivity_threshold, | ||
| "inference_time_ms": 340, | ||
| }, | ||
| } | ||
|
|
||
|
|
||
| def main() -> int: | ||
| parser = argparse.ArgumentParser(description="MONAI Agent Lung Nodule Skill") | ||
| parser.add_argument("--study-id", required=True, help="DICOM Study Instance UID or accession id") | ||
| parser.add_argument("--sensitivity-threshold", type=float, default=0.85) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift Implement the declared The CLI accepts any float, including values outside Validate the range. Apply the threshold before emitting findings, or remove this input from the contract. Also applies to: 154-156 🤖 Prompt for AI Agents |
||
| parser.add_argument("--output-dir", type=Path, default=Path(".")) | ||
| parser.add_argument("--mock", action="store_true", help="Force simulation mode (no GPU/MONAI required)") | ||
| args = parser.parse_args() | ||
|
|
||
| use_real = MONAI_AVAILABLE and not args.mock | ||
| result = ( | ||
| run_real(args.study_id, args.sensitivity_threshold) | ||
| if use_real | ||
| else run_mock(args.study_id, args.sensitivity_threshold) | ||
| ) | ||
|
|
||
| args.output_dir.mkdir(parents=True, exist_ok=True) | ||
| out_path = args.output_dir / "result_json.json" | ||
| out_path.write_text(json.dumps(result, indent=2)) | ||
|
|
||
| print(f"[skill]: mode={result['execution_metadata']['mode']} -> {out_path}") | ||
| print(json.dumps(result, indent=2)) | ||
| return 0 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| sys.exit(main()) | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,62 @@ | ||||||
| name: monai-agent-lung-nodule | ||||||
| version: 0.1.0 | ||||||
| purpose: > | ||||||
| Reference implementation of an agent/MCP-callable wrapper around a MONAI Deploy | ||||||
| segmentation operator, proposed as the general pattern for exposing MONAI Deploy | ||||||
| operators to LLM/agent orchestrators. Development-time reference; not a validated | ||||||
| clinical model. | ||||||
|
|
||||||
| inputs: | ||||||
| study_id: | ||||||
| type: string | ||||||
| required: true | ||||||
| description: DICOM Study Instance UID or local accession identifier. | ||||||
| sensitivity_threshold: | ||||||
| type: number | ||||||
| required: false | ||||||
| default: 0.85 | ||||||
| description: Detection confidence threshold between 0.0 and 1.0. | ||||||
|
|
||||||
| outputs: | ||||||
| result_json: | ||||||
| type: file | ||||||
| description: > | ||||||
| Structured evidence pack: per-nodule findings (location slice, diameter_mm, | ||||||
| volume, confidence_score), Fleischner Society follow-up category per finding, | ||||||
| execution_metadata (mode, device, model_version, inference_time_ms), and an | ||||||
| AI_Generated / Verification_Status flag pair on every record. | ||||||
|
|
||||||
| runtime: | ||||||
| language: python | ||||||
| python_version: "3.10-3.12" | ||||||
| packages: | ||||||
| required: [] | ||||||
| optional: | ||||||
| - torch>=2.0 | ||||||
| - monai>=1.3 | ||||||
| gpu: | ||||||
| required: false | ||||||
| accelerated_if_available: true | ||||||
| device_selection: auto (cuda if available, else cpu) | ||||||
|
|
||||||
| resources: | ||||||
| local_storage_mb: 50 | ||||||
| gpu_memory_peak_mb: 512 | ||||||
| runtime_seconds: [0.05, 5.0] | ||||||
|
|
||||||
| constraints: | ||||||
| - Not approved for clinical deployment, clinical interpretation, autonomous diagnosis, | ||||||
| or regulatory submission. | ||||||
| - No PHI is read, stored, or transmitted. Operates on a synthetic volume or caller- | ||||||
| supplied de-identified/public data only. | ||||||
| - Every emitted finding must carry AI_Generated: true and Verification_Status: "Pending". | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win Quote this YAML scalar. Line 52 contains Proposed fix- - Every emitted finding must carry AI_Generated: true and Verification_Status: "Pending".
+ - 'Every emitted finding must carry AI_Generated: true and Verification_Status: "Pending".'📝 Committable suggestion
Suggested change
🧰 Tools🪛 YAMLlint (1.37.1)[error] 52-52: syntax error: mapping values are not allowed here (syntax) 🤖 Prompt for AI AgentsSource: Linters/SAST tools |
||||||
|
|
||||||
| validation_gates: | ||||||
| - schema: result_json must validate against the documented finding schema | ||||||
| - sanity: at least one of {nodules_detected == 0, findings non-empty} must hold | ||||||
| - physical_bounds: max_diameter_mm in [0, 100]; volume_mm3 (or volume_voxels) >= 0 | ||||||
| - runtime: inference_time_ms within resources.runtime_seconds bound (real mode only) | ||||||
| - reproducibility: repeat invocation with identical study_id and mock mode yields | ||||||
| identical findings (simulation mode is deterministic by design) | ||||||
|
|
||||||
| paired_verifier: verifiers/agent_output_quality_v1 | ||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Remove the unsupported volume-input contract.
The manifest defines only
study_id. The runner accepts only--study-idand always uses a synthetic tensor. It does not accept a DICOM study input, a NIfTI path, or a CT volume path.Document
study_idas the only current input. Add volume-path support before advertising it.🤖 Prompt for AI Agents