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).
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env julia
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reproducible validation against real datasets (not part of Pkg.test).
|
||||
#
|
||||
# julia --project=. test/real_datasets.jl /path/sample.imzML [/path/sample.mzML]
|
||||
#
|
||||
# Set JULIA_MSI_MCP_REAL_STREAMING=1 to also run the streaming pipeline.
|
||||
# Artifacts go to JULIA_MSI_MCP_ARTIFACTS (default: a temp directory).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
using JuliaMSI_MCP
|
||||
using JSON3
|
||||
using ModelContextProtocol
|
||||
|
||||
const J = JuliaMSI_MCP
|
||||
const ARTIFACTS = get(ENV, "JULIA_MSI_MCP_ARTIFACTS", mktempdir(prefix="juliamsi_real_"))
|
||||
ENV["JULIA_MSI_MCP_ARTIFACTS"] = ARTIFACTS
|
||||
|
||||
function call_tool(tool, args)
|
||||
result = tool.handler(args)
|
||||
if result isa ModelContextProtocol.CallToolResult
|
||||
return result.is_error, JSON3.read(result.content[1]["text"])
|
||||
end
|
||||
return false, JSON3.read(result.text)
|
||||
end
|
||||
|
||||
function wait_for(task_id; timeout=1800.0)
|
||||
t0 = time()
|
||||
while true
|
||||
status = J.task_status_payload(J.get_task(task_id))
|
||||
if status["status"] in ("completed", "failed", "cancelled") || time() - t0 > timeout
|
||||
return J.task_result_payload(J.get_task(task_id)), time() - t0
|
||||
end
|
||||
sleep(1)
|
||||
end
|
||||
end
|
||||
|
||||
function run_plan(plan; timeout=1800.0)
|
||||
executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=0)
|
||||
return wait_for(executed["task_id"]; timeout=timeout)
|
||||
end
|
||||
|
||||
function validate_imzml(path)
|
||||
println("=== imzML: ", path)
|
||||
t_open = @elapsed meta = J.open_dataset(path; cache_size=300, use_mmap=true,
|
||||
precompute_analytics=false)
|
||||
width, height = meta["image_dims"]
|
||||
println("open_seconds=", round(t_open, digits=2),
|
||||
" spectra=", meta["num_spectra"], " dims=", width, "x", height,
|
||||
" mmap=", meta["source"]["mmap_active"], " rss_mb=", J._rss_mb())
|
||||
|
||||
data = J.require_data()
|
||||
x, y = max(1, width ÷ 2), max(1, height ÷ 2)
|
||||
mz, intensity = J.MSI_src.GetSpectrum(data, x, y)
|
||||
base_mass = mz[argmax(intensity)]
|
||||
println("spectrum(", x, ",", y, ") points=", length(mz),
|
||||
" bpi=", maximum(intensity), " base_peak_mz=", base_mass)
|
||||
|
||||
analytics, t_an = run_plan(J.plan_analytics(Dict("include_rows" => 2)))
|
||||
println("analytics status=", analytics["status"], " wall_seconds=", round(t_an, digits=1),
|
||||
" mz_range=", analytics["mz_range"])
|
||||
|
||||
ion, t_ion = run_plan(J.plan_ion_image(Dict(
|
||||
"mass" => base_mass, "tolerance" => 0.15, "preview_max_dim" => 96)))
|
||||
st = ion["stats"]
|
||||
println("ion_image m/z=", base_mass, " status=", ion["status"],
|
||||
" wall_seconds=", round(t_ion, digits=1), " max=", st["max"],
|
||||
" nonzero=", st["nonzero"], " base_peak_coord=", st["base_peak_coord"])
|
||||
println(" artifact_csv=", ion["artifacts"]["csv"]["path"])
|
||||
|
||||
min_mz, max_mz = analytics["mz_range"]
|
||||
masses = unique([base_mass, min_mz + 0.2 * (max_mz - min_mz),
|
||||
min_mz + 0.5 * (max_mz - min_mz),
|
||||
min_mz + 0.8 * (max_mz - min_mz)])
|
||||
multi, t_multi = run_plan(J.plan_multiple_slices(Dict(
|
||||
"masses" => masses, "tolerance" => 0.15, "preview_max_dim" => 64)))
|
||||
println("multiple_slices n=", multi["num_slices"], " wall_seconds=", round(t_multi, digits=1))
|
||||
for slice in multi["slices"]
|
||||
s = slice["stats"]
|
||||
println(" m/z=", slice["mass"], " max=", s["max"], " nonzero=", s["nonzero"])
|
||||
end
|
||||
|
||||
if get(ENV, "JULIA_MSI_MCP_REAL_STREAMING", "0") == "1"
|
||||
stream, t_stream = run_plan(J.plan_preprocessing(Dict(
|
||||
"steps" => [
|
||||
Dict("name" => "smoothing", "params" => Dict("method" => "savitzky_golay", "window" => 5, "order" => 2)),
|
||||
Dict("name" => "baseline_correction", "params" => Dict("method" => "snip", "iterations" => 20)),
|
||||
Dict("name" => "normalization", "params" => Dict("method" => "tic")),
|
||||
Dict("name" => "peak_picking", "params" => Dict("method" => "profile", "snr_threshold" => 3.0)),
|
||||
],
|
||||
"num_bins" => 500, "min_peaks_per_bin" => 1, "frequency_threshold" => 0.02)))
|
||||
println("streaming status=", stream["status"], " wall_seconds=", round(t_stream, digits=1),
|
||||
" shape=", stream["matrix_shape"], " nonzeros=", stream["nonzeros"])
|
||||
println(" mtx=", stream["artifacts"]["matrix_mtx"]["path"])
|
||||
end
|
||||
|
||||
J.close_dataset()
|
||||
println("closed rss_mb=", J._rss_mb())
|
||||
end
|
||||
|
||||
function validate_mzml(path)
|
||||
println("=== mzML: ", path)
|
||||
t_open = @elapsed meta = J.open_dataset(path; cache_size=50, use_mmap=true)
|
||||
println("open_seconds=", round(t_open, digits=2), " spectra=", meta["num_spectra"],
|
||||
" mmap=", meta["source"]["mmap_active"])
|
||||
|
||||
iserr, spec = call_tool(J.GET_SPECTRUM_BY_INDEX_TOOL,
|
||||
Dict("index" => 1, "max_points" => 50))
|
||||
iserr && error("spectrum query failed: $(spec)")
|
||||
println("spectrum(1) points=", spec["num_points"], " bpi=", spec["bpi"],
|
||||
" base_peak_mz=", spec["base_peak_mz"])
|
||||
|
||||
analytics, t_an = run_plan(J.plan_analytics(Dict("include_rows" => 1)), timeout=600)
|
||||
println("analytics status=", analytics["status"], " wall_seconds=", round(t_an, digits=1),
|
||||
" mz_range=", analytics["mz_range"])
|
||||
|
||||
iserr, err = call_tool(J.GET_MZ_SLICE_TOOL, Dict("mass" => spec["base_peak_mz"], "tolerance" => 0.1))
|
||||
println("ion_image_rejected=", iserr, iserr ? " type=" * err["error"]["type"] : "")
|
||||
J.close_dataset()
|
||||
end
|
||||
|
||||
function main(args)
|
||||
isempty(args) && error("usage: julia --project=. test/real_datasets.jl <file.imzML|file.mzML> ...")
|
||||
for path in args
|
||||
isfile(path) || error("file not found: $(path)")
|
||||
if endswith(lowercase(path), ".imzml")
|
||||
validate_imzml(path)
|
||||
elseif endswith(lowercase(path), ".mzml")
|
||||
validate_mzml(path)
|
||||
else
|
||||
@warn "Skipping unsupported file" path
|
||||
end
|
||||
end
|
||||
println("Artifacts: ", ARTIFACTS)
|
||||
end
|
||||
|
||||
main(ARGS)
|
||||
Reference in New Issue
Block a user