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)
|
||||
@@ -0,0 +1,312 @@
|
||||
using Test
|
||||
using JSON3
|
||||
using ModelContextProtocol
|
||||
using JuliaMSI_MCP
|
||||
|
||||
const J = JuliaMSI_MCP
|
||||
|
||||
include("synthetic.jl")
|
||||
|
||||
# Keep generated artifacts inside a disposable directory.
|
||||
const TEST_ARTIFACTS = mktempdir()
|
||||
ENV["JULIA_MSI_MCP_ARTIFACTS"] = TEST_ARTIFACTS
|
||||
|
||||
"""Call a tool handler and return `(is_error, payload)`."""
|
||||
function call_tool(tool, args::AbstractDict)
|
||||
result = tool.handler(args)
|
||||
if result isa ModelContextProtocol.CallToolResult
|
||||
text = result.content[1]["text"]
|
||||
return result.is_error, JSON3.read(text)
|
||||
else
|
||||
return false, JSON3.read(result.text)
|
||||
end
|
||||
end
|
||||
|
||||
@testset "JuliaMSI_MCP" begin
|
||||
|
||||
@testset "utilities" begin
|
||||
@test J.canonical_json(Dict("b" => 2, "a" => 1)) ==
|
||||
J.canonical_json(Dict("a" => 1, "b" => 2))
|
||||
@test J.canonical_json(Dict("x" => [1.0, 2.0])) ==
|
||||
"{\"x\":[1.0,2.0]}"
|
||||
@test J.jsonable(Dict("bad" => NaN))["bad"] === nothing
|
||||
@test J.short_hash("abc") == J.short_hash("abc")
|
||||
@test J.short_hash("abc") != J.short_hash("abd")
|
||||
|
||||
m = [0.0 4.0; 2.0 8.0]
|
||||
ds = J.downsample_matrix(m; max_dim=1)
|
||||
@test size(ds) == (1, 1)
|
||||
@test ds[1, 1] ≈ 3.5
|
||||
st = J.matrix_stats(m)
|
||||
@test st["max"] == 8.0
|
||||
@test st["base_peak_coord"] == [2, 2]
|
||||
@test st["nonzero"] == 3
|
||||
end
|
||||
|
||||
@testset "dataset lifecycle, spectra and ion images" begin
|
||||
dir = mktempdir()
|
||||
path = write_synthetic_imzml(dir)
|
||||
|
||||
@testset "open and metadata" begin
|
||||
meta = open_dataset(path; precompute_analytics=true)
|
||||
@test meta["open"] == true
|
||||
@test meta["num_spectra"] == 12
|
||||
@test meta["image_dims"] == Any[4, 3]
|
||||
@test meta["mz_range"] == Any[100.0, 500.0]
|
||||
@test meta["analytics_ready"] == true
|
||||
@test meta["source"]["type"] == "imzML"
|
||||
@test meta["coordinate_map"] == true
|
||||
@test isfile(path * ".cache")
|
||||
@test J.session_metadata()["dataset_id"] == meta["dataset_id"]
|
||||
end
|
||||
|
||||
@testset "spectrum at coordinate" begin
|
||||
iserr, p = call_tool(J.GET_SPECTRUM_TOOL, Dict("x" => 2, "y" => 2))
|
||||
@test !iserr
|
||||
@test p["num_points"] == 5
|
||||
@test p["bpi"] == 1000.0
|
||||
@test p["base_peak_mz"] == 300.0
|
||||
@test p["coord"] == [2, 2]
|
||||
@test 1 <= length(p["points"]) <= 5
|
||||
iserr, prof = call_tool(J.GET_SPECTRUM_TOOL,
|
||||
Dict("x" => 2, "y" => 2, "representation" => "profile",
|
||||
"max_points" => 100))
|
||||
@test !iserr
|
||||
@test length(prof["points"]) == 5
|
||||
|
||||
iserr, p = call_tool(J.GET_SPECTRUM_BY_INDEX_TOOL,
|
||||
Dict("index" => 6, "representation" => "profile"))
|
||||
@test !iserr
|
||||
@test p["representation"] == "profile"
|
||||
|
||||
iserr, p = call_tool(J.GET_SPECTRUM_TOOL, Dict("x" => 99, "y" => 1))
|
||||
@test iserr
|
||||
@test p["error"]["type"] == "InvalidParams"
|
||||
end
|
||||
|
||||
@testset "synchronous ion image" begin
|
||||
iserr, p = call_tool(J.GET_MZ_SLICE_TOOL,
|
||||
Dict("mass" => 300.0, "tolerance" => 0.5,
|
||||
"include_matrix" => true))
|
||||
@test !iserr
|
||||
@test p["stats"]["max"] == 1000.0
|
||||
@test p["stats"]["base_peak_coord"] == [2, 2]
|
||||
@test p["preview"]["dims"] == [4, 3]
|
||||
@test p["matrix"][2][2] == 1000.0
|
||||
@test isfile(p["artifacts"]["csv"]["path"])
|
||||
@test isfile(p["artifacts"]["pgm"]["path"])
|
||||
|
||||
# ROI mask (A.10): only two pixels are selected.
|
||||
mask = zeros(Float64, 3, 4)
|
||||
mask[2, 2] = 1.0
|
||||
mask[2, 3] = 1.0
|
||||
mask_path = joinpath(dir, "mask.pgm")
|
||||
J.write_matrix_pgm(mask_path, mask)
|
||||
iserr, masked = call_tool(J.GET_MZ_SLICE_TOOL,
|
||||
Dict("mass" => 300.0, "tolerance" => 0.5, "mask_path" => mask_path))
|
||||
@test !iserr
|
||||
@test masked["stats"]["nonzero"] == 2
|
||||
@test masked["stats"]["base_peak_coord"] == [2, 2]
|
||||
end
|
||||
|
||||
@testset "synchronous multiple slices" begin
|
||||
iserr, p = call_tool(J.GET_MULTIPLE_SLICES_TOOL,
|
||||
Dict("masses" => [100.0, 300.0], "tolerance" => 0.5))
|
||||
@test !iserr
|
||||
@test p["num_slices"] == 2
|
||||
@test length(p["slices"]) == 2
|
||||
@test p["slices"][1]["mass"] == 100.0
|
||||
@test p["slices"][2]["stats"]["max"] == 1000.0
|
||||
end
|
||||
|
||||
@testset "planning validation" begin
|
||||
iserr, p = call_tool(J.PLAN_ION_IMAGE_TOOL, Dict("tolerance" => 0.5))
|
||||
@test iserr
|
||||
@test p["error"]["type"] == "InvalidParams"
|
||||
|
||||
plan = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5))
|
||||
@test plan["kind"] == "ion_image"
|
||||
@test plan["validation"]["checked"] == true
|
||||
@test J.get_runspec(plan["runspec_id"]).dataset_id == J.active_dataset_id()
|
||||
|
||||
# Same inputs -> same content hash; different tolerance -> different hash.
|
||||
plan2 = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5))
|
||||
@test plan2["runspec_id"] == plan["runspec_id"]
|
||||
plan3 = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.6))
|
||||
@test plan3["runspec_id"] != plan["runspec_id"]
|
||||
|
||||
# An empty mask path means "no mask", not the current directory.
|
||||
plan_blank = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5,
|
||||
"mask_path" => ""))
|
||||
@test plan_blank["params"]["mask_path"] === nothing
|
||||
|
||||
iserr, p = call_tool(J.PLAN_PREPROCESSING_TOOL,
|
||||
Dict("steps" => [Dict("name" => "nope")]))
|
||||
@test iserr
|
||||
end
|
||||
|
||||
@testset "asynchronous ion image + task tools" begin
|
||||
plan = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5))
|
||||
executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=30)
|
||||
@test executed["status"] == "completed"
|
||||
@test executed["reused"] == false
|
||||
|
||||
iserr, status = call_tool(J.TASK_STATUS_TOOL,
|
||||
Dict("task_id" => executed["task_id"]))
|
||||
@test !iserr
|
||||
@test status["status"] == "completed"
|
||||
@test status["progress"] == 1.0
|
||||
@test status["result_ready"] == true
|
||||
|
||||
iserr, result = call_tool(J.TASK_RESULT_TOOL,
|
||||
Dict("task_id" => executed["task_id"]))
|
||||
@test !iserr
|
||||
@test result["stats"]["max"] == 1000.0
|
||||
@test result["stats"]["base_peak_coord"] == [2, 2]
|
||||
|
||||
# Re-using the same RunSpec returns the existing task.
|
||||
again = J.submit_runspec(J.get_runspec(plan["runspec_id"]))
|
||||
@test again["reused"] == true
|
||||
@test again["task_id"] == executed["task_id"]
|
||||
|
||||
iserr, listed = call_tool(J.LIST_TASKS_TOOL, Dict("limit" => 5))
|
||||
@test !iserr
|
||||
@test listed["count"] >= 1
|
||||
end
|
||||
|
||||
@testset "analytics task" begin
|
||||
plan = J.plan_analytics(Dict("include_rows" => 3))
|
||||
executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=30)
|
||||
@test executed["status"] == "completed"
|
||||
res = J.task_result_payload(J.get_task(executed["task_id"]))
|
||||
@test res["num_spectra"] == 12
|
||||
@test length(res["rows"]) == 3
|
||||
@test res["aggregate"]["TIC"]["max"] > 0
|
||||
@test isfile(res["artifacts"]["spectrum_stats_csv"]["path"])
|
||||
end
|
||||
|
||||
@testset "streaming preprocessing task" begin
|
||||
plan = J.plan_preprocessing(Dict(
|
||||
"smoothing_window" => 5,
|
||||
"baseline_iterations" => 10,
|
||||
"normalization" => "tic",
|
||||
"num_bins" => 50,
|
||||
"min_peaks_per_bin" => 1,
|
||||
"peak_picking" => true,
|
||||
))
|
||||
executed = J.submit_runspec(J.get_runspec(plan["runspec_id"]); wait_seconds=120)
|
||||
@test executed["status"] == "completed"
|
||||
res = J.task_result_payload(J.get_task(executed["task_id"]))
|
||||
@test res["matrix_shape"] == Any[50, 12]
|
||||
@test res["nonzeros"] >= 1
|
||||
@test isfile(res["artifacts"]["matrix_mtx"]["path"])
|
||||
@test isfile(res["artifacts"]["bin_centers_csv"]["path"])
|
||||
@test !isempty(res["top_bins"])
|
||||
end
|
||||
|
||||
@testset "resources and prompts" begin
|
||||
meta = J.DATASET_METADATA_RESOURCE.data_provider()
|
||||
@test meta["open"] == true
|
||||
stats = J.DATASET_STATS_RESOURCE.data_provider()
|
||||
@test stats["analytics_ready"] == true
|
||||
@test stats["rows_returned"] > 0
|
||||
|
||||
tasks = J.list_tasks(limit=1)
|
||||
if !isempty(tasks)
|
||||
t = first(tasks)
|
||||
st = J.TASK_STATUS_TEMPLATE.data_provider(
|
||||
"msi://tasks/$(t.id)/status", Dict("task_id" => t.id))
|
||||
@test st["task_id"] == t.id
|
||||
rs = J.TASK_RESULT_TEMPLATE.data_provider(
|
||||
"msi://tasks/$(t.id)/result", Dict("task_id" => t.id))
|
||||
@test rs["task_id"] == t.id
|
||||
end
|
||||
@test length(J.ALL_TOOLS) == 20
|
||||
@test length(J.ALL_RESOURCES) == 2
|
||||
@test length(J.ALL_PROMPTS) == 3
|
||||
@test J.build_server() isa ModelContextProtocol.Server
|
||||
end
|
||||
|
||||
@testset "close" begin
|
||||
previous = J.close_dataset()
|
||||
@test previous["open"] == true
|
||||
@test J.session_metadata()["open"] == false
|
||||
|
||||
iserr, p = call_tool(J.DATASET_INFO_TOOL, Dict())
|
||||
@test !iserr
|
||||
@test p["open"] == false
|
||||
|
||||
iserr, p = call_tool(J.GET_SPECTRUM_TOOL, Dict("x" => 1, "y" => 1))
|
||||
@test iserr
|
||||
@test p["error"]["type"] == "SessionError"
|
||||
end
|
||||
|
||||
rm(dir; recursive=true, force=true)
|
||||
end
|
||||
|
||||
@testset "non-mmap I/O (Float32) regression" begin
|
||||
dir = mktempdir()
|
||||
path = write_synthetic_imzml(dir; width=3, height=2)
|
||||
meta = open_dataset(path; use_mmap=false, precompute_analytics=true)
|
||||
@test meta["source"]["mmap_active"] == false
|
||||
@test meta["mz_range"] == Any[100.0, 500.0]
|
||||
@test meta["analytics_ready"] == true
|
||||
iserr, p = call_tool(J.GET_MZ_SLICE_TOOL,
|
||||
Dict("mass" => 300.0, "tolerance" => 0.5))
|
||||
@test !iserr
|
||||
@test p["stats"]["max"] == 1000.0
|
||||
J.close_dataset()
|
||||
rm(dir; recursive=true, force=true)
|
||||
end
|
||||
|
||||
@testset "dataset switching invalidates plans" begin
|
||||
dir1 = mktempdir()
|
||||
dir2 = mktempdir()
|
||||
p1 = write_synthetic_imzml(dir1; width=2, height=2)
|
||||
p2 = write_synthetic_imzml(dir2; width=3, height=3)
|
||||
open_dataset(p1; precompute_analytics=false)
|
||||
plan = J.plan_ion_image(Dict("mass" => 300.0, "tolerance" => 0.5))
|
||||
rs = J.get_runspec(plan["runspec_id"])
|
||||
open_dataset(p2; precompute_analytics=false)
|
||||
@test_throws J.MCPToolError J.submit_runspec(rs)
|
||||
J.close_dataset()
|
||||
rm(dir1; recursive=true, force=true)
|
||||
rm(dir2; recursive=true, force=true)
|
||||
end
|
||||
|
||||
@testset "artifact retention" begin
|
||||
root = TEST_ARTIFACTS
|
||||
old_dir = joinpath(root, "old_task_0000")
|
||||
new_dir = joinpath(root, "new_task_0000")
|
||||
mkpath(old_dir)
|
||||
mkpath(new_dir)
|
||||
write(joinpath(old_dir, "a.csv"), "x"^1000)
|
||||
write(joinpath(new_dir, "b.csv"), "y"^1000)
|
||||
|
||||
# Backdate the old directory's mtime so age pruning can see it.
|
||||
t = round(Int64, time() - 10 * 86400)
|
||||
buf = zeros(Int64, 2)
|
||||
buf[1] = t
|
||||
buf[2] = t
|
||||
ccall(:utime, Cint, (Cstring, Ptr{Int64}), old_dir, buf)
|
||||
|
||||
# dry_run removes nothing
|
||||
dry = J.prune_artifacts!(max_age_days=1.0, max_total_bytes=0.0, dry_run=true)
|
||||
@test dry["dry_run"] == true
|
||||
@test isdir(old_dir) && isdir(new_dir)
|
||||
|
||||
# age pruning removes only the old directory
|
||||
age = J.prune_artifacts!(max_age_days=1.0, max_total_bytes=0.0)
|
||||
@test age["removed"] == 1
|
||||
@test !isdir(old_dir)
|
||||
@test isdir(new_dir)
|
||||
|
||||
# size budget trims the rest
|
||||
size_budget = J.prune_artifacts!(max_age_days=0.0, max_total_bytes=10.0)
|
||||
@test size_budget["removed"] >= 1
|
||||
@test !isdir(new_dir)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
rm(TEST_ARTIFACTS; recursive=true, force=true)
|
||||
@@ -0,0 +1,239 @@
|
||||
#!/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)
|
||||
@@ -0,0 +1,111 @@
|
||||
# test/synthetic.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Minimal, valid imzML + ibd generator used by the integration tests.
|
||||
#
|
||||
# Layout: `width` × `height` spectra, Float32, uncompressed, centroided, five
|
||||
# peaks per spectrum. One pixel is given a very strong peak at 300.0 Da so the
|
||||
# tests can assert that ion-image extraction actually finds signal.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function write_synthetic_imzml(dir::AbstractString;
|
||||
width::Int=4, height::Int=3,
|
||||
mzs::Vector{Float64}=[100.0, 200.0, 300.0, 400.0, 500.0])
|
||||
mkpath(dir)
|
||||
base = joinpath(dir, "synthetic")
|
||||
imzml_path = base * ".imzML"
|
||||
ibd_path = base * ".ibd"
|
||||
|
||||
n = width * height
|
||||
offsets = Vector{Tuple{Int64,Int64,Int64,Int64}}(undef, n) # mz_off, mz_len, int_off, int_len
|
||||
|
||||
open(ibd_path, "w") do io
|
||||
# JuliaMSI's parser ignores arrays whose external offset is 0 (it uses 0
|
||||
# as the "unset" sentinel), so keep a small pad at the start of the ibd.
|
||||
write(io, zeros(UInt8, 16))
|
||||
for k in 1:n
|
||||
x = ((k - 1) % width) + 1
|
||||
y = ((k - 1) ÷ width) + 1
|
||||
intensities = Float64[10.0 + x, 20.0 + y, 30.0, 40.0, 50.0]
|
||||
if (x, y) == (2, 2)
|
||||
intensities[3] = 1000.0
|
||||
elseif (x, y) == (4, 3)
|
||||
intensities[1] = 2000.0
|
||||
end
|
||||
mz_bytes = reinterpret(UInt8, Float32.(mzs))
|
||||
int_bytes = reinterpret(UInt8, Float32.(intensities))
|
||||
mz_off = position(io)
|
||||
write(io, mz_bytes)
|
||||
int_off = position(io)
|
||||
write(io, int_bytes)
|
||||
offsets[k] = (Int64(mz_off), Int64(length(mzs)), Int64(int_off), Int64(length(mzs)))
|
||||
end
|
||||
end
|
||||
|
||||
open(imzml_path, "w") do io
|
||||
write(io, """<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
<mzML xmlns="http://psi.hupo.org/ms/mzml" version="1.1.0">
|
||||
<cvList count="1"><cv id="MS" fullName="Mass spectrometry ontology" URI="https://raw.githubusercontent.com/HUPO-PSI/psi-ms-CV/master/psi-ms.obo"/></cvList>
|
||||
<fileDescription><fileContent><cvParam cvRef="MS" accession="MS:1000579" name="MS1 spectrum" value=""/></fileContent></fileDescription>
|
||||
<referenceableParamGroupList count="2">
|
||||
<referenceableParamGroup id="mzArray">
|
||||
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" value=""/>
|
||||
<cvParam cvRef="MS" accession="MS:1000521" name="32-bit float" value=""/>
|
||||
<cvParam cvRef="MS" accession="MS:1000127" name="centroid spectrum" value=""/>
|
||||
</referenceableParamGroup>
|
||||
<referenceableParamGroup id="intensityArray">
|
||||
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value=""/>
|
||||
<cvParam cvRef="MS" accession="MS:1000521" name="32-bit float" value=""/>
|
||||
</referenceableParamGroup>
|
||||
</referenceableParamGroupList>
|
||||
<softwareList count="1"><software id="synthetic" version="1.0"/></softwareList>
|
||||
<scanSettingsList count="1">
|
||||
<scanSettings id="scansettings1">
|
||||
<cvParam cvRef="IMS" accession="IMS:1000042" name="max count of pixels x" value="$(width)"/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000043" name="max count of pixels y" value="$(height)"/>
|
||||
</scanSettings>
|
||||
</scanSettingsList>
|
||||
<instrumentConfigurationList count="1">
|
||||
<instrumentConfiguration id="ic1"><cvParam cvRef="MS" accession="MS:1000031" name="instrument model" value="Synthetic-MS"/></instrumentConfiguration>
|
||||
</instrumentConfigurationList>
|
||||
<dataProcessingList count="1"><dataProcessing id="dp1"><processingMethod order="1" softwareRef="synthetic"><cvParam cvRef="MS" accession="MS:1000592" name="external calibration" value=""/></processingMethod></dataProcessing></dataProcessingList>
|
||||
<run id="run1" defaultInstrumentConfigurationRef="ic1">
|
||||
<spectrumList count="$(n)" defaultDataProcessingRef="dp1">
|
||||
""")
|
||||
for k in 1:n
|
||||
x = ((k - 1) % width) + 1
|
||||
y = ((k - 1) ÷ width) + 1
|
||||
mz_off, mz_len, int_off, int_len = offsets[k]
|
||||
write(io, """ <spectrum id="spectrum=$(k)" index="$(k-1)" defaultArrayLength="$(mz_len)">
|
||||
<cvParam cvRef="MS" accession="MS:1000511" name="ms level" value="1"/>
|
||||
<cvParam cvRef="MS" accession="MS:1000127" name="centroid spectrum" value=""/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000050" name="position x" value="$(x)"/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000051" name="position y" value="$(y)"/>
|
||||
<binaryDataArrayList count="2">
|
||||
<binaryDataArray encodedLength="$(mz_len * 4)">
|
||||
<cvParam cvRef="MS" accession="MS:1000514" name="m/z array" value=""/>
|
||||
<cvParam cvRef="MS" accession="MS:1000521" name="32-bit float" value=""/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000101" name="external encoded length" value="$(mz_len * 4)"/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000102" name="external data" value=""/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000103" name="external offset" value="$(mz_off)"/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000104" name="external array length" value="$(mz_len)"/>
|
||||
</binaryDataArray>
|
||||
<binaryDataArray encodedLength="$(int_len * 4)">
|
||||
<cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value=""/>
|
||||
<cvParam cvRef="MS" accession="MS:1000521" name="32-bit float" value=""/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000101" name="external encoded length" value="$(int_len * 4)"/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000102" name="external data" value=""/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000103" name="external offset" value="$(int_off)"/>
|
||||
<cvParam cvRef="IMS" accession="IMS:1000104" name="external array length" value="$(int_len)"/>
|
||||
</binaryDataArray>
|
||||
</binaryDataArrayList>
|
||||
</spectrum>
|
||||
""")
|
||||
end
|
||||
write(io, """ </spectrumList>
|
||||
</run>
|
||||
</mzML>
|
||||
""")
|
||||
end
|
||||
|
||||
return imzml_path
|
||||
end
|
||||
Reference in New Issue
Block a user