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)