# JuliaMSI_MCP A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server for the **Mass Spectrometry Imaging** engine [JuliaMSI](../JuliaMSI). It exposes the persistent session, ion-image extraction, streaming preprocessing pipeline and random-access spectrum queries as tools that an LLM (Claude Desktop, VS Code/Copilot, OpenCode, etc.) can invoke reproducibly. > Status: **Phases 1–3 of the plan implemented and tested** (persistent session, > planning + async execution layer, full tools/resources/prompts catalog). Phase 4 > (Streamable HTTP + memory resilience) is also integrated; production hardening > (TLS, native task notifications) is the remaining polish. --- ## 1. Architecture ``` ┌───────────────────────────────────────────────────────────────────────────┐ │ LLM client (MCP host) │ │ Claude Desktop · VS Code · OpenCode · Cursor │ └───────────────────────────────────┬───────────────────────────────────────┘ │ JSON-RPC 2.0 (stdio or Streamable HTTP) ┌───────────────────────────────────▼───────────────────────────────────────┐ │ MCP server — JuliaMSI_MCP │ │ │ │ SessionState (logical Ref) RunSpec registry Task registry │ │ ─ persistent MSIData ─ content hash ─ Threads.@spawn │ │ ─ lock + dataset_id ─ validation ─ polling/cancel │ │ │ │ Sync tools · Planning tools · Execution tools │ │ Resources msi:// · Workflow prompts │ └───────────────────────────────────┬───────────────────────────────────────┘ │ direct in-process calls (no IPC) ┌───────────────────────────────────▼───────────────────────────────────────┐ │ JuliaMSI engine (JuliaMSI src/) │ │ imzML + binary .cache · mmap + madvise · Bloom filters · LRU │ │ get_mz_slice · get_multiple_mz_slices · process_dataset! │ └───────────────────────────────────────────────────────────────────────────┘ ``` ### The four layers | Layer | File | Responsibility | |-------|------|----------------| | **Session** | `src/session.jl` | Open/close `MSIData`, keep it alive between calls, compute `dataset_id`, return memory to the OS (`GC.gc(true)` + `malloc_trim`). | | **Planning** | `src/runspec.jl` | Validate arguments and mint an immutable `RunSpec` with a deterministic SHA-256 hash, bound to the `dataset_id`. No computation runs here. | | **Execution** | `src/tasks.jl` | Launch the RunSpec in a `Threads.@spawn`, track state/progress, cooperative cancellation, polling and results. | | **Artifacts** | `src/artifacts.jl` | Full matrices go to disk (CSV, PGM, Matrix Market); the LLM receives statistics and a downsampled *preview*. | ### Key design decisions - **Clean `stdout` for stdio.** The JuliaMSI engine prints debug traces with `println`; the server redirects the global `stdout` to `stderr` and hands the transport the original `stdout` handle (`install_output_guard`), so the JSON-RPC channel is never corrupted. - **One dataset at a time.** This is the natural `MSIData` model; opening another one closes and cleans the previous. Plans are bound to the `dataset_id` and rejected if the dataset changes. - **Plan ≠ execute.** The LLM receives an auditable `runspec_id`; re-running the same plan reuses the existing task unless `force=true`. - **Bounded results.** A 2000×2000 matrix is ~32 MB of JSON. Results carry `stats`, `preview` (≤256 px) and artifact paths instead; `include_matrix` is opt-in and capped. - **Memory.** `msi_close_dataset` and the streaming/analytics tasks run `GC.gc(true/false)` + `malloc_trim(0)` on Linux to return glibc arenas to the kernel. --- ## 2. Requirements - Julia **1.11+** (tested on 1.11.7). - A JuliaMSI engine checkout with its `Project.toml` (default `../JuliaMSI`). - JuliaMSI dependencies installed (resolved by `Pkg`). The integration uses a path dependency (`[sources] MSI_src = {path = "../JuliaMSI"}`), so the engine code is **not copied**: changes in JuliaMSI take effect when the server is restarted. --- ## 3. Installation ```bash cd /path/to/JuliaMSI_MCP # Option A: default sibling layout (../JuliaMSI) julia --project=. scripts/setup.jl # Option B: explicit path to the engine checkout JULIA_MSI_PATH=/path/to/JuliaMSI julia --project=. scripts/setup.jl ``` `scripts/setup.jl` runs `Pkg.develop(path=...)`, `instantiate` and `precompile`. ### Self-contained project (optional) The integration uses the local engine checkout (`../JuliaMSI`) so engine changes are reflected without duplicating ~10,000 lines. To distribute the server without the rest of the engine repo: ```bash mkdir -p vendor/JuliaMSI cp -r ../JuliaMSI/src ../JuliaMSI/Project.toml vendor/JuliaMSI/ # edit [sources] in Project.toml: # MSI_src = {path = "vendor/JuliaMSI"} julia --project=. -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()' ``` You can also point at any engine remote with `Pkg.add(url="https://github.com/Pixelguy14/Julia_msi_GUI")` (or the Codeberg mirror) and use the `MSI_src` name in `[deps]`, though the path dependency is the most convenient during development. ### Recommended patches for JuliaMSI Three engine bugs surfaced during validation (including real datasets). The patches live in `patches/` and are **already applied** to the local `../JuliaMSI` checkout: 1. **`juliamsi-fix-nonmmap.patch`** — non-mmap reading: - `load_imzml_lazy` built a temporary `MSIData` to write the cache while sharing the real handle vector; its finalizer closed the dataset's handles (`Bad file descriptor`). It now uses `IO[]` for the temporary object. - `_iterate_uncompressed_fast` read into `Vector{Float64}` buffers even when the `.ibd` was Float32, consuming twice the bytes. It now uses the source's real type. 2. **`juliamsi-fix-mask-io.patch`** — ROI masks: - `load_and_prepare_mask` called `Gray.(img)` and failed on TIFFs that load as `TiffImages.WidePixel` (e.g. the HR2MSI optical reference image). It now uses the embedded color channel. - `process_image_pipeline` built an even-sized structuring element from the default `smoothing=2`, which ImageMorphology rejects (`connectivity must be odd-sized`). It now normalizes to an odd size ≥ 3. **Upstream status (Nov 2026):** all three fixes are part of engine commit `bc71b9c`, present on the `rel/Windows_Mac_Recompatibility` branch (Codeberg, GitHub, nube-gran) and on **GitHub** `main`. **Codeberg** `main` and **nube-gran** `main` do not include them yet, so the patches remain useful as a fallback for those default branches: ```bash cd /path/to/JuliaMSI git apply /path/to/JuliaMSI_MCP/patches/juliamsi-fix-nonmmap.patch git apply /path/to/JuliaMSI_MCP/patches/juliamsi-fix-mask-io.patch ``` Recommendation: merge `rel/Windows_Mac_Recompatibility` into `main` on Codeberg and nube-gran so the `patches/` folder can eventually be removed. The mmap path (default) is unaffected by the first patch. Quick check: ```bash julia --project=. -e 'using JuliaMSI_MCP; println(JuliaMSI_MCP.SERVER_VERSION)' ``` --- ## 4. Running ### stdio (recommended for desktop) ```bash julia --project=. --threads=auto bin/run_server.jl ``` `--threads=auto` matters: the engine parallelizes spectra and the server launches background tasks. ### Streamable HTTP ```bash julia --project=. --threads=auto bin/run_server.jl --http --host 127.0.0.1 --port 3000 ``` By default it listens on localhost only, without authentication. To protect the endpoint, require a shared token: ```bash julia --project=. --threads=auto bin/run_server.jl --http --port 3000 --token S3CR3T # or: JULIA_MSI_MCP_TOKEN=S3CR3T ... --http ``` Clients must send `Authorization: Bearer S3CR3T`. To expose it beyond the machine, put a TLS reverse proxy in front (a shared token does **not** replace TLS). ### Fast startup with a sysimage (AOT, Phase 4) To eliminate the first-call JIT, build a system image: ```bash julia scripts/build_sysimage.jl # produces build/sys_mcp.so julia --project=. --threads=auto --sysimage=build/sys_mcp.so bin/run_server.jl ``` `scripts/build_sysimage.jl` creates a throwaway environment, develops the engine and `JuliaMSI_MCP`, and runs `scripts/sysimage_warmup.jl` (open, spectrum, slices, streaming, tool registration) to bake in the native code. The build takes several minutes and the `.so` is machine-specific. ### Client configuration (copy to the location each client expects): - `config/claude_desktop_config.json` → Claude Desktop (`mcpServers`). On Linux: `~/.config/Claude/claude_desktop_config.json`; on Windows: `%APPDATA%\Claude\claude_desktop_config.json`. - `config/vscode_mcp.json` → VS Code / Copilot. Copy it as `.vscode/mcp.json` in the workspace (or run *MCP: Add Server*). - `config/opencode.json` → OpenCode V2 (key `mcp.servers`). Copy it as `opencode.json` at the project root, or merge it into `~/.config/opencode/opencode.json` for global use. All assume this layout (adjust the absolute paths to your checkout): ``` julia --project=/path/to/JuliaMSI_MCP --threads=auto \ /path/to/JuliaMSI_MCP/bin/run_server.jl ``` Useful environment variables: | Variable | Effect | |----------|--------| | `JULIA_NUM_THREADS=auto` | Engine threads (also `--threads=auto`). | | `JULIA_MSI_MCP_ARTIFACTS=/path` | Artifact directory (default `/artifacts`). | | `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` | Artifact lifetime before pruning at startup (default 7). | | `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` | Total artifact budget in bytes (default 0 = unlimited). | | `JULIA_MSI_MCP_TOKEN` | Shared token for `--http` (same as `--token`). | | `JULIA_MSI_MCP_KEEP_STDOUT=1` | Disable the stdout redirect (local debugging only). | --- ## 5. Tool catalog ### Session and data | Tool | Type | Description | |------|------|-------------| | `msi_open_dataset` | sync | Open/switch an imzML/mzML dataset; creates or uses `.cache`; optional `precompute_analytics`. | | `msi_close_dataset` | sync | Closes handles, empties the cache and returns RAM to the OS. | | `msi_dataset_info` | sync | Session state (dimensions, m/z range, mmap, RSS, threads). | | `msi_get_dataset_stats` | sync | Per-spectrum statistics (TIC/BPI/NumPoints/m/z range). | ### Spectra | Tool | Type | Description | |------|------|-------------| | `msi_get_spectrum_at_coord` | sync | Spectrum at `(x, y)` via the LRU cache. `representation=peaks` or `profile`. | | `msi_get_spectrum_by_index` | sync | Spectrum by linear index (useful for non-imaging mzML). | ### Ion images | Tool | Type | Description | |------|------|-------------| | `msi_get_mz_slice` | sync | Immediate ion image for one mass. | | `msi_get_multiple_mz_slices` | sync | Up to 50 masses in a single pass (hierarchy inversion). | | `msi_plan_ion_image` | planning | Validates and mints a `runspec_id` for one mass. | | `msi_plan_multiple_slices` | planning | Mints a `runspec_id` for a panel of up to 5000 masses (1 I/O pass). | ### Preprocessing and analytics | Tool | Type | Description | |------|------|-------------| | `msi_plan_preprocessing` | planning | Streaming pipeline (`process_dataset!`) → sparse matrix. | | `msi_plan_streaming_pipeline` | planning | Alias of the above. | | `msi_plan_analytics` | planning | TIC/BPI/Bloom-filter scan in the background. | ### Async execution | Tool | Type | Description | |------|------|-------------| | `msi_execute_runspec` | execution | Launches the plan in the background and returns a `task_id` (reuses tasks unless `force`). | | `msi_get_task_status` | sync | State, progress, timings and summary. | | `msi_get_task_result` | sync | Full result (stats, preview, artifacts, opt-in matrices). | | `msi_cancel_task` | sync | Cooperative cancellation. | | `msi_list_tasks` | sync | List recent tasks (filter by status). | | `msi_list_plans` | sync | List recent RunSpecs. | ### Maintenance | Tool | Type | Description | |------|------|-------------| | `msi_clean_artifacts` | sync | Prune artifacts by age and/or byte budget (with `dry_run`). | ### Resources | URI | Content | |-----|---------| | `msi://dataset/metadata` | Active session metadata. | | `msi://dataset/stats` | Aggregates + first 100 rows (does not trigger the scan). | | `msi://tasks/{task_id}/status` | Task status. | | `msi://tasks/{task_id}/result` | Task result. | ### Prompts | Prompt | Use | |--------|-----| | `analyze_region_of_interest` | Forces confirmation of mass, tolerance and mask before planning. | | `standard_pipeline` | Open → plan → execute → poll → summarize workflow. | | `diagnose_task` | Interprets task states/errors and proposes corrective actions. | > Prompts (and their content) are in English, the project's primary language. Earlier > compendium names: `analizar_region_de_interes`, `pipeline_estandar`, > `diagnostico_de_tarea`. --- ## 6. Typical flow (what the LLM does) ```text msi_open_dataset(file_path="/data/sample.imzML", precompute_analytics=false) │ ├─(large dataset)─► msi_plan_analytics ─► msi_execute_runspec ─► poll │ msi_plan_ion_image(mass=756.55, tolerance=0.1, mask_path="/data/roi.png") │ → {"runspec_id": "a1b2…", "kind": "ion_image", …} ▼ msi_execute_runspec(runspec_id="a1b2…", wait_seconds=0) │ → {"task_id": "uuid", "status": "queued"} ▼ msi_get_task_status(task_id="uuid") # repeat until completed ▼ msi_get_task_result(task_id="uuid") │ → stats, preview, artifacts.csv/pgm ▼ msi_close_dataset() ``` Ion-image result (abridged): ```json { "kind": "ion_image", "mass": 756.55, "tolerance": 0.1, "shape": [200, 150], "stats": { "max": 14322.5, "mean": 812.4, "nonzero": 18450, "base_peak_coord": [87, 42], "centroid_coord": [91.2, 40.7] }, "preview": {"dims": [96, 72], "rows": [[...]]}, "artifacts": { "csv": {"path": ".../ion_mz_756.55.csv", "uri": "file://..."}, "pgm": {"path": ".../ion_mz_756.55.pgm", "uri": "file://..."} } } ``` --- ## 7. Error handling Handlers never crash the JSON-RPC loop: every exception becomes `CallToolResult(is_error=true)` with this body: ```json { "error": { "code": -32602, "type": "InvalidParams", "message": "Coordinates (99, 1) are outside the image bounds 4×3.", "suggested_action": "Validate coordinates before retrying.", "details": {"image_dims": [4, 3]} } } ``` | Type | Code | Typical origin | Suggested action | |------|------|----------------|------------------| | `InvalidParams` | `-32602` | mass/tolerance/mask/coordinates | fix arguments | | `SessionError` | `-32010` | no dataset open | `msi_open_dataset` | | `ResourceNotFound` | `-32002` | unknown task_id/URI | list tasks/plans | | `InternalError` | `-32603` | I/O, corrupt `.cache`, OOM | check stderr; delete `.cache`; use streaming | --- ## 8. Testing ```bash julia --project=. -e 'using Pkg; Pkg.test()' ``` The suite generates a **valid synthetic imzML** (4×3, Float32, 5 peaks/spectrum, one strong peak at 300 Da) and covers: - utilities (canonical hash, safe JSON, preview, statistics), - session open/close and `.cache`, - spectrum by coordinate and index, - synchronous single and multiple ion-image extraction, - plan validation and dataset binding, - the full async flow (plan → execute → status → result), - analytics and the streaming pipeline, - resources, prompts and dataset switching, - non-mmap I/O regression, and artifact retention. Current result: **107 tests OK** (~22 s on a dev machine). There is also an end-to-end stdio smoke test in `test/smoke_stdio.py` (generates the synthetic dataset, launches the server and walks initialize → tools → plan → execute → result). --- ## 9. Validation with real datasets Validated against the `Cinvestav_2025/Analisis` data (12 threads, 14 GB RAM, local disk; timings vary with page cache). ### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imaging) | Metric | Result | |--------|--------| | Spectra / dimensions | 34,840 / 260 × 134 | | Size | `.ibd` 815 MB, `.imzML` 56 MB (with `.cache`) | | Open | 2.0–3.5 s using the binary `.cache` | | Analytics scan | 6.8–12.9 s | | Spectrum `(130,67)` | 966 points, BPI 4,026.3, base peak 798.5387 | | Ion image `798.5387 ± 0.15` | 1.8 s, max 14,274.8, 21,920 pixels with signal, base peak (167,105) | | 4–5 masses in one pass | 2.2 s without mask / 3.7 s with mask | | ROI mask (optical → PGM) | 36% of the area; the optical TIFF directly gives ~43% after the patch | | Streaming (12,571 masked spectra) | 3.9 s; matrix 420 × 34,840; 1,424,362 nnz; `.mtx` 44 MB | | Streaming (34,840 spectra, no mask) | 5.75 s engine (10.3 s wall); matrix 500 × 34,840; 3,822,821 nnz (78.1%); ~61 MB RAM | | Most intense bins | 580.6, 443.8, 716.2 m/z | > The difference between "engine" and "wall" on the first run is mostly first-call JIT of > the analytics/streaming path plus 1 s polling granularity; later calls approach engine > time. That is the main argument for the Phase-4 AOT sysimage. The streaming pipeline keeps RAM bounded: even with 34,840 spectra, the engine keeps one spectrum per thread and assembles a `SparseMatrixCSC`. ### `mzML/` (non-imaging profiles) | File | Spectra | Open | Analytics | |------|--------:|-----:|----------:| | `T9_A1.mzML` | 10 | 0.06 s | 0.15–1.2 s | | `Cytochrome_C.mzML` | 32 | 0.07 s | 0.15 s | | `Col_1.mzML` | 800 | 0.17 s | 0.07 s | - `msi_get_spectrum_by_index` and `msi_get_dataset_stats` work correctly. - Imaging tools (`msi_get_mz_slice`, `msi_plan_ion_image`, …) are rejected with `InvalidParams` because the dataset has no `coordinate_map` and no spatial dimensions. ### Reproduce ```bash # Generic smoke test (auto-detects imaging vs. mzML) python3 test/smoke_stdio.py --dataset /path/file.imzML # Fuller validation (analytics + ion image + multiple masses + optional streaming) JULIA_MSI_MCP_REAL_STREAMING=1 julia --project=. test/real_datasets.jl \ /path/file.imzML /path/file.mzML ``` --- ## 10. Repository layout ``` JuliaMSI_MCP/ ├── Project.toml # deps + [sources] MSI_src → ../JuliaMSI ├── Manifest.toml ├── .github/workflows/ci.yml # CI (test + smoke) ├── bin/run_server.jl # entrypoint stdio / --http [--token] ├── scripts/ │ ├── setup.jl # Pkg.develop + instantiate + precompile │ ├── build_sysimage.jl # AOT system image (Phase 4) │ └── sysimage_warmup.jl # precompile workload ├── patches/ # fallback engine patches (see §3) ├── src/ │ ├── JuliaMSI_MCP.jl # module and includes │ ├── util.jl # safe JSON, hashes, previews │ ├── errors.jl # MCPToolError + JSON-RPC mapping │ ├── session.jl # persistent MSIData + cleanup │ ├── runspec.jl # planning and validation │ ├── tasks.jl # async execution + registry │ ├── artifacts.jl # CSV/PGM/MatrixMarket + retention │ ├── resources.jl # msi:// │ ├── prompts.jl # workflow prompts (English) │ ├── server.jl # build_server / run_stdio / run_http (+ token) │ └── tools/ # dataset, spectra, imaging, planning, tasks, maintenance ├── config/ # Claude Desktop, VS Code, OpenCode ├── test/ │ ├── synthetic.jl # test imzML generator │ ├── runtests.jl │ ├── smoke_stdio.py # end-to-end stdio smoke test │ └── real_datasets.jl # reproducible real-dataset validation ├── build/ # generated sysimage (git-ignored) └── artifacts/ # results (git-ignored) ``` --- ## 11. Relation to the architectural compendium | Compendium section | MCP implementation | |--------------------|--------------------| | A.1 `MSIData`, LRU, atomics | persistent session + `GetSpectrum` | | A.2 slices / hierarchy inversion | `msi_get_multiple_mz_slices`, `msi_plan_multiple_slices` | | A.3 dual parser + `.cache` | `msi_open_dataset` (delegated to the engine) | | A.4 handle pool | `--threads=auto`; the engine opens one handle per thread | | A.5 Bloom filters | rejection applied by `get_mz_slice` | | A.6 mmap + `madvise` | `use_mmap=true` and bounded `preview` | | A.7–A.8 preprocessing/streaming | `msi_plan_preprocessing`, `process_dataset!` | | A.10 ROI masks | `mask_path` in plans and slices | | A.11 AOT sysimage | `scripts/build_sysimage.jl` + `--sysimage` (see §4) | | A.12 `malloc_trim` | `release_os_memory!` on close and heavy tasks | | B.1 STDIO/HTTP | `run_stdio`, `run_http` (optional shared token) | | B.2 tools | 20 registered tools | | B.3 resources | `msi://dataset/*`, `msi://tasks/*` | | B.4 errors/cleanup | `errors.jl` + hooks + artifact retention | --- ## 12. Troubleshooting | Symptom | Cause / fix | |---------|-------------| | `GLMakie failed to precompile` on instantiate | GLMakie is a dependency of the engine's GUI project; the `MSI_src` core (and therefore the MCP server) no longer loads it thanks to `PlottingStubs.jl`. Harmless for the server. | | Server starts but the client sees no tools | Make sure the client launches `bin/run_server.jl` with `--project=...` and `--threads=auto`; startup logs go to `stderr`. | | `Dataset file not found` / `.ibd not found` | Use absolute paths and keep `.imzML` + `.ibd` with the same basename. | | First slice is slow | The analytics scan is running. Use `msi_plan_analytics` + `msi_execute_runspec` in the background. | | `.cache` corrupt after a crash | Delete `.imzML.cache`; the XML parser regenerates it. | | Permission error on open | The engine writes `.imzML.cache` next to the dataset; copy `.imzML`+`.ibd` to a writable directory. | | RSS does not drop after close | `msi_close_dataset` already calls `malloc_trim` on Linux; on musl/Alpine it does not exist and the kernel reclaims memory under pressure. | | `stdout` pollution while debugging | Don't `println` in the server process; use `stderr` or `@info`. `JULIA_MSI_MCP_KEEP_STDOUT=1` disables the guard (local only). | ## 13. Known limitations and next steps 1. **One dataset per process** (by engine design). Multiplexing datasets would need a session pool or one process per dataset. 2. **Cooperative cancellation**: an in-flight `pread`/disk pass cannot be interrupted; the task stops at the next checkpoint. 3. **`msi_get_dataset_stats` and sync slices can block** during the first analytics scan. For large datasets, use `msi_plan_analytics` + execution. 4. **Native MCP tasks (SEP-1686/2663)**: the server uses its own task registry, compatible with any client. `task_support=:optional` and `task_detach` can be added to publish state via the SDK's `tasks/get`. 5. **Baseline memory footprint**: `using MSI_src` no longer loads the plotting stack (CairoMakie/GLMakie) thanks to `PlottingStubs.jl`, but `Images` (for masks) still leaves the process at ~1.6 GB RSS. Splitting the data core from `ImageProcessing` would reduce startup and RAM. 6. **TLS**: the HTTP shared token protects the endpoint, but transport encryption still requires a TLS reverse proxy (Caddy/nginx). Resolved in Phase 4: artifact retention (`msi_clean_artifacts` + startup policy), HTTP shared-token auth, the AOT sysimage script (`scripts/build_sysimage.jl`) and CI (`.github/workflows/ci.yml`). Remaining roadmap: - [ ] Publish tasks/progress via the native MCP mechanism (`task_support=:optional`, `tasks/get`, `notifications/progress`). - [ ] `notifications/resources/updated` for `msi://tasks/{id}/status`. - [ ] Verify startup with `--sysimage=build/sys_mcp.so` and measure the TTFX improvement. - [ ] CI unit/integration on a real reference dataset (repo benchmarks). - [ ] `Dockerfile`/systemd for headless deployment.