Files
Pixelguy14 c3d5daeec5
CI / test (push) Has been cancelled
feat: JuliaMSI MCP server v0.1.0 — 20 tools ready for testing
Implements the Model Context Protocol server for the JuliaMSI mass
spectrometry imaging engine, covering phases 1–3 of the implementation
plan plus the main phase-4 items.

Tools (20):
  session/dataset:   msi_open_dataset, msi_close_dataset, msi_dataset_info,
                     msi_get_dataset_stats
  spectra:           msi_get_spectrum_at_coord, msi_get_spectrum_by_index
  ion images:        msi_get_mz_slice, msi_get_multiple_mz_slices,
                     msi_plan_ion_image, msi_plan_multiple_slices
  preprocessing:     msi_plan_preprocessing, msi_plan_streaming_pipeline,
                     msi_plan_analytics
  execution:         msi_execute_runspec, msi_list_plans,
                     msi_get_task_status, msi_get_task_result,
                     msi_cancel_task, msi_list_tasks
  maintenance:       msi_clean_artifacts

Resources (msi://): dataset/metadata, dataset/stats,
  tasks/{task_id}/status, tasks/{task_id}/result
Prompts: analyze_region_of_interest, standard_pipeline, diagnose_task

- Persistent session: one MSIData kept alive between tool calls
- Plan -> execute -> poll async core (SHA-256 RunSpecs + background tasks)
- Results as on-disk artifacts (CSV/PGM/MatrixMarket) with compact previews
- Structured JSON-RPC error mapping with suggested actions
- stdio and Streamable HTTP transports, optional shared-token auth
- Artifact retention (age + size budgets) and glibc malloc_trim cleanup
- 107 tests + end-to-end stdio smoke test; validated on HR2MSI bladder
  (imzML) and T9_A1/Col_1 (mzML)

Required JuliaMSI engine fixes are tracked in patches/ (already upstream
on the rel/Windows_Mac_Recompatibility branch and GitHub main).
2026-11-25 13:25:13 -06:00

240 lines
10 KiB
Python

#!/usr/bin/env python3
"""End-to-end smoke test for the JuliaMSI MCP server (stdio transport).
Generates a small synthetic .imzML dataset (unless --dataset is given), launches
the real server process, and exercises the full JSON-RPC surface: initialize,
discovery, dataset open, spectrum query, async analytics task, ion image
plan -> execute -> poll -> result, resources, prompts and close. Imaging vs.
non-imaging (mzML) datasets are detected automatically.
Usage:
python3 test/smoke_stdio.py [--dataset /path/to/file.imzML] [--keep]
Requires: Python 3.8+ and a Julia installation with the project instantiated.
"""
import argparse
import collections
import json
import os
import select
import shutil
import subprocess
import sys
import tempfile
import threading
import time
PROJECT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
JULIA = os.environ.get("JULIA", "julia")
class Client:
def __init__(self, dataset=None):
cmd = [JULIA, f"--project={PROJECT}", "--threads=auto",
os.path.join(PROJECT, "bin", "run_server.jl")]
env = dict(os.environ)
self.proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, bufsize=1, env=env)
self.stderr = collections.deque(maxlen=400)
self._reader = threading.Thread(target=self._drain_stderr, daemon=True)
self._reader.start()
def _drain_stderr(self):
for line in self.proc.stderr:
self.stderr.append(line.rstrip())
def send(self, message):
self.proc.stdin.write(json.dumps(message) + "\n")
self.proc.stdin.flush()
def recv(self, timeout=300):
deadline = time.time() + timeout
while time.time() < deadline:
ready, _, _ = select.select([self.proc.stdout], [], [], 1.0)
if ready:
line = self.proc.stdout.readline()
if not line:
raise RuntimeError("server closed stdout\n" + "\n".join(self.stderr))
return json.loads(line)
if self.proc.poll() is not None:
raise RuntimeError("server exited\n" + "\n".join(self.stderr))
raise TimeoutError("no JSON-RPC response within %ss" % timeout)
def call(self, request_id, method, params=None, timeout=300):
message = {"jsonrpc": "2.0", "id": request_id, "method": method}
if params is not None:
message["params"] = params
self.send(message)
while True:
response = self.recv(timeout)
if response.get("id") == request_id:
if "error" in response:
raise RuntimeError("JSON-RPC error: " + json.dumps(response["error"]))
return response["result"]
def tool(self, request_id, name, arguments):
result = self.call(request_id, "tools/call", {"name": name, "arguments": arguments})
body = result["content"][0]["text"]
if result.get("isError"):
raise RuntimeError("tool %s failed: %s" % (name, body))
return json.loads(body)
def tool_error(self, request_id, name, arguments):
result = self.call(request_id, "tools/call", {"name": name, "arguments": arguments})
if not result.get("isError"):
raise RuntimeError("tool %s unexpectedly succeeded" % name)
return json.loads(result["content"][0]["text"])
def close(self):
try:
self.proc.stdin.close()
except Exception:
pass
try:
self.proc.wait(timeout=30)
except subprocess.TimeoutExpired:
self.proc.kill()
def ensure_dataset(path):
if path:
return path, False
tmp = tempfile.mkdtemp(prefix="juliamsi_smoke_")
script = (
'include(joinpath(ENV["JULIA_MSI_MCP_PROJECT"], "test", "synthetic.jl")); '
'println(write_synthetic_imzml(ENV["JULIA_MSI_MCP_SMOKE_DIR"]))'
)
env = dict(os.environ, JULIA_MSI_MCP_PROJECT=PROJECT, JULIA_MSI_MCP_SMOKE_DIR=tmp)
out = subprocess.run([JULIA, f"--project={PROJECT}", "-e", script],
check=True, capture_output=True, text=True, env=env)
return out.stdout.strip().splitlines()[-1], tmp
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", help="existing .imzML (otherwise a synthetic one is generated)")
parser.add_argument("--keep", action="store_true", help="keep the temporary dataset")
args = parser.parse_args()
dataset, tmp = ensure_dataset(args.dataset)
created_artifacts = False
if not os.environ.get("JULIA_MSI_MCP_ARTIFACTS"):
os.environ["JULIA_MSI_MCP_ARTIFACTS"] = tempfile.mkdtemp(prefix="juliamsi_smoke_artifacts_")
created_artifacts = True
client = Client(dataset)
try:
print("[1] initialize")
init = client.call(1, "initialize", {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": {"name": "juliamsi-smoke", "version": "0.1"},
})
assert init["serverInfo"]["name"] == "juliamsi"
client.send({"jsonrpc": "2.0", "method": "notifications/initialized"})
print("[2] discovery")
tools = client.call(2, "tools/list")["tools"]
names = {t["name"] for t in tools}
for required in ("msi_open_dataset", "msi_plan_ion_image", "msi_execute_runspec",
"msi_get_task_status", "msi_get_task_result", "msi_close_dataset"):
assert required in names, "missing tool " + required
resources = client.call(3, "resources/list")["resources"]
assert any(r["uri"] == "msi://dataset/metadata" for r in resources)
templates = client.call(4, "resources/templates/list")["resourceTemplates"]
assert any("tasks" in t["uriTemplate"] for t in templates)
prompts = client.call(5, "prompts/list")["prompts"]
assert any(p["name"] == "analyze_region_of_interest" for p in prompts)
print("[3] open dataset:", dataset)
meta = client.tool(6, "msi_open_dataset",
{"file_path": dataset, "precompute_analytics": False})
num_spectra = meta["num_spectra"]
width, height = meta["image_dims"]
imaging = width > 0 and height > 0 and bool(meta.get("coordinate_map"))
assert num_spectra > 0
print(" spectra=%d dims=%dx%d imaging=%s" % (num_spectra, width, height, imaging))
if imaging:
x = max(1, width // 2)
y = max(1, height // 2)
print("[4] spectrum at (%d,%d)" % (x, y))
spec = client.tool(7, "msi_get_spectrum_at_coord", {"x": x, "y": y})
else:
print("[4] spectrum by index (non-imaging dataset)")
spec = client.tool(7, "msi_get_spectrum_by_index", {"index": 1})
assert spec["num_points"] > 0
assert spec["bpi"] > 0
assert len(spec["points"]) > 0
print("[5] async analytics task")
plan = client.tool(8, "msi_plan_analytics", {"include_rows": 1})
executed = client.tool(9, "msi_execute_runspec",
{"runspec_id": plan["runspec_id"], "wait_seconds": 300})
task_id = executed["task_id"]
status = client.tool(10, "msi_get_task_status", {"task_id": task_id})
assert status["status"] == "completed", status
analytics = client.tool(11, "msi_get_task_result", {"task_id": task_id})
assert analytics["num_spectra"] == num_spectra
assert analytics["aggregate"]["TIC"]["max"] > 0
print("[6] dataset stats and structured errors")
stats = client.tool(12, "msi_get_dataset_stats",
{"aggregate_only": True, "limit": 1})
assert stats["num_spectra"] == num_spectra
error_args = {"x": width + 10, "y": 1} if imaging else {"x": 1, "y": 1}
err = client.tool_error(13, "msi_get_spectrum_at_coord", error_args)
assert err["error"]["type"] == "InvalidParams"
if imaging:
print("[7] plan -> execute -> poll -> result (ion image)")
mass = spec["base_peak_mz"]
plan = client.tool(14, "msi_plan_ion_image", {"mass": mass, "tolerance": 0.5})
executed = client.tool(15, "msi_execute_runspec",
{"runspec_id": plan["runspec_id"], "wait_seconds": 300})
task_id = executed["task_id"]
status = client.tool(16, "msi_get_task_status", {"task_id": task_id})
assert status["status"] == "completed", status
result = client.tool(17, "msi_get_task_result", {"task_id": task_id})
assert result["stats"]["max"] > 0
bpc = result["stats"]["base_peak_coord"]
assert 1 <= bpc[0] <= width and 1 <= bpc[1] <= height
plans = client.tool(18, "msi_list_plans", {"limit": 5})
assert plans["count"] >= 1
else:
print("[7] ion-image tools correctly reject non-imaging data")
ionerr = client.tool_error(19, "msi_plan_ion_image",
{"mass": spec["base_peak_mz"], "tolerance": 0.5})
assert ionerr["error"]["type"] == "InvalidParams"
print("[8] resources and prompt rendering")
task_resource = client.call(20, "resources/read",
{"uri": "msi://tasks/%s/status" % task_id})
task_payload = json.loads(task_resource["contents"][0]["text"])
assert task_payload["status"] == "completed"
prompt = client.call(21, "prompts/get", {
"name": "analyze_region_of_interest",
"arguments": {"dataset_path": dataset, "region": "tumor tissue"},
})
text = prompt["messages"][0]["content"]["text"]
assert "tumor tissue" in text and "{region}" not in text
print("[9] close dataset")
closed = client.tool(22, "msi_close_dataset", {})
assert closed["closed"] is True
print("SMOKE TEST PASSED")
finally:
client.close()
if tmp and not args.keep:
shutil.rmtree(tmp, ignore_errors=True)
if created_artifacts:
shutil.rmtree(os.environ["JULIA_MSI_MCP_ARTIFACTS"], ignore_errors=True)
if __name__ == "__main__":
try:
main()
except Exception as exc:
print("SMOKE TEST FAILED:", exc, file=sys.stderr)
sys.exit(1)