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,37 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# The MCP project links the engine at ../JuliaMSI via [sources]. Cloning it
|
||||
# as a sibling (rather than into the workspace) keeps the default layout and
|
||||
# avoids touching [sources] or the Manifest.
|
||||
- name: Clone JuliaMSI engine (sibling)
|
||||
run: |
|
||||
git clone --depth 1 https://github.com/Pixelguy14/Julia_msi_GUI ../JuliaMSI
|
||||
|
||||
- uses: julia-actions/setup-julia@v2
|
||||
with:
|
||||
version: "1.11"
|
||||
|
||||
- uses: julia-actions/cache@v2
|
||||
|
||||
- name: Instantiate
|
||||
run: |
|
||||
julia --project=. -e 'using Pkg; Pkg.instantiate()'
|
||||
|
||||
- name: Unit & integration tests
|
||||
run: |
|
||||
julia --project=. -e 'using Pkg; Pkg.test()'
|
||||
|
||||
- name: Smoke test (stdio, synthetic dataset)
|
||||
run: |
|
||||
python3 test/smoke_stdio.py
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
# Generated results
|
||||
artifacts/
|
||||
build/
|
||||
*.imzML.cache
|
||||
*.log
|
||||
*.so
|
||||
*.dll
|
||||
*.dylib
|
||||
|
||||
# Julia
|
||||
*.jl.cov
|
||||
*.jl.*.cov
|
||||
*.jl.mem
|
||||
|
||||
# Editors
|
||||
.vscode/
|
||||
.idea/
|
||||
.DS_Store
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
+2867
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,34 @@
|
||||
name = "JuliaMSI_MCP"
|
||||
uuid = "146f587d-e8c9-4fce-8feb-186b5b7e0eb5"
|
||||
authors = ["JuliaMSI"]
|
||||
version = "0.1.0"
|
||||
|
||||
[deps]
|
||||
CSV = "336ed68f-0bac-5ca0-87d4-7b16caf5d00b"
|
||||
DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
|
||||
Dates = "ade2ca70-3891-5945-98fb-dc099432e06a"
|
||||
JSON3 = "0f8b85d8-7281-11e9-16c2-39a750bddbf1"
|
||||
ModelContextProtocol = "c58f755f-f2a7-4f48-bf29-4e9659b78499"
|
||||
MSI_src = "8f395f85-3b9c-4f7f-bf7e-12345678abcd"
|
||||
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
|
||||
SHA = "ea8e919c-243c-51af-8825-aaa63cd721ce"
|
||||
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
|
||||
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
|
||||
UUIDs = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
|
||||
|
||||
[sources]
|
||||
MSI_src = {path = "../JuliaMSI"}
|
||||
|
||||
[compat]
|
||||
CSV = "0.10"
|
||||
DataFrames = "1.7"
|
||||
JSON3 = "1"
|
||||
ModelContextProtocol = "0.6"
|
||||
MSI_src = "0.1"
|
||||
julia = "1.11"
|
||||
|
||||
[extras]
|
||||
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
|
||||
|
||||
[targets]
|
||||
test = ["Test"]
|
||||
@@ -0,0 +1,557 @@
|
||||
# JuliaMSI_MCP
|
||||
|
||||
Servidor [Model Context Protocol](https://modelcontextprotocol.io) (MCP) para el motor de
|
||||
**Mass Spectrometry Imaging** [JuliaMSI](../JuliaMSI). Expone la sesión persistente, la
|
||||
extracción de imágenes iónicas, el pipeline de preprocesamiento streaming y el acceso
|
||||
aleatorio a espectros como herramientas que un LLM (Claude Desktop, VS Code/Copilot,
|
||||
OpenCode, etc.) puede invocar de forma reproducible.
|
||||
|
||||
> Estado: **Fase 1–3 del plan implementadas y probadas** (sesión persistente, capa de
|
||||
> planificación + ejecución asíncrona, catálogo completo de tools/resources/prompts).
|
||||
> La Fase 4 (Streamable HTTP + resiliencia de memoria) también está integrada; falta
|
||||
> endurecer autenticación y empaquetado AOT para producción.
|
||||
|
||||
---
|
||||
|
||||
## 1. Arquitectura
|
||||
|
||||
```
|
||||
┌───────────────────────────────────────────────────────────────────────────┐
|
||||
│ Cliente LLM (host MCP) │
|
||||
│ Claude Desktop · VS Code · OpenCode · Cursor │
|
||||
└───────────────────────────────────┬───────────────────────────────────────┘
|
||||
│ JSON-RPC 2.0 (stdio o Streamable HTTP)
|
||||
┌───────────────────────────────────▼───────────────────────────────────────┐
|
||||
│ Servidor MCP — JuliaMSI_MCP │
|
||||
│ │
|
||||
│ SessionState (Ref lógica) RunSpec registry Task registry │
|
||||
│ ─ MSIData persistente ─ hash de contenido ─ Threads.@spawn │
|
||||
│ ─ lock + dataset_id ─ validación ─ polling/cancel │
|
||||
│ │
|
||||
│ Tools síncronas · Tools de planificación · Tools de ejecución │
|
||||
│ Resources msi:// · Prompts de flujo │
|
||||
└───────────────────────────────────┬───────────────────────────────────────┘
|
||||
│ llamadas directas en proceso (sin IPC)
|
||||
┌───────────────────────────────────▼───────────────────────────────────────┐
|
||||
│ Motor JuliaMSI (src/ de JuliaMSI) │
|
||||
│ imzML + .cache binaria · mmap + madvise · Bloom filters · LRU │
|
||||
│ get_mz_slice · get_multiple_mz_slices · process_dataset! │
|
||||
└───────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### Las cuatro capas
|
||||
|
||||
| Capa | Archivo | Responsabilidad |
|
||||
|------|---------|-----------------|
|
||||
| **Sesión** | `src/session.jl` | Abrir/cerrar `MSIData`, conservarlo entre llamadas, calcular `dataset_id`, liberar memoria al SO (`GC.gc(true)` + `malloc_trim`). |
|
||||
| **Planificación** | `src/runspec.jl` | Validar parámetros y crear un `RunSpec` inmutable con hash SHA-256 determinista, ligado al `dataset_id`. No ejecuta cómputo. |
|
||||
| **Ejecución** | `src/tasks.jl` | Lanzar el RunSpec en una `Threads.@spawn`, registrar estado/progreso, cancelación cooperativa, polling y resultados. |
|
||||
| **Artefactos** | `src/artifacts.jl` | Las matrices completas van a disco (CSV, PGM, Matrix Market); al LLM se le devuelven estadísticas y un *preview* downsampleado. |
|
||||
|
||||
### Decisiones de diseño relevantes
|
||||
|
||||
- **`stdout` limpio para stdio.** El motor JuliaMSI imprime trazas de depuración con
|
||||
`println`; el servidor redirige el `stdout` global a `stderr` y entrega al transporte
|
||||
el handle original de `stdout` (`install_output_guard`). Así el canal JSON-RPC nunca
|
||||
se corrompe.
|
||||
- **Un dataset a la vez.** Es el modelo natural de `MSIData`; abrir otro cierra y limpia
|
||||
el anterior. Los planes quedan ligados al `dataset_id` y se rechazan si el dataset
|
||||
cambió.
|
||||
- **Planificar ≠ ejecutar.** El LLM recibe un `runspec_id` auditable; reejecutar el mismo
|
||||
plan reutiliza la tarea existente salvo `force=true`.
|
||||
- **Resultados acotados.** Una matriz 2000×2000 en JSON son ~32 MB. Por eso el resultado
|
||||
incluye `stats`, `preview` (≤256 px) y rutas a artefactos; `include_matrix` es opt-in y
|
||||
tiene topes de tamaño.
|
||||
- **Memoria.** `msi_close_dataset` y las tareas de streaming/analytics ejecutan
|
||||
`GC.gc(true/false)` + `malloc_trim(0)` en Linux para devolver arenas de glibc al kernel.
|
||||
|
||||
---
|
||||
|
||||
## 2. Requisitos
|
||||
|
||||
- Julia **1.11+** (probado con 1.11.7).
|
||||
- Un checkout del motor JuliaMSI con su `Project.toml` (por defecto `../JuliaMSI`).
|
||||
- Dependencias de JuliaMSI ya instaladas (el proyecto las resuelve vía `Pkg`).
|
||||
|
||||
La integración usa una dependencia de ruta (`[sources] MSI_src = {path = "../JuliaMSI"}`),
|
||||
así que **no se copia** el código del motor: los cambios en JuliaMSI se reflejan al
|
||||
reiniciar el servidor.
|
||||
|
||||
---
|
||||
|
||||
## 3. Instalación
|
||||
|
||||
```bash
|
||||
cd /home/pixel/Documents/2026/JuliaMSI_MCP
|
||||
|
||||
# Opción A: layout hermano por defecto (../JuliaMSI)
|
||||
julia --project=. scripts/setup.jl
|
||||
|
||||
# Opción B: ruta explícita al checkout del motor
|
||||
JULIA_MSI_PATH=/ruta/a/JuliaMSI julia --project=. scripts/setup.jl
|
||||
```
|
||||
|
||||
`scripts/setup.jl` hace `Pkg.develop(path=...)`, `instantiate` y `precompile`.
|
||||
|
||||
### Proyecto autocontenido (opcional)
|
||||
|
||||
La integración usa el checkout local del motor (`../JuliaMSI`) para que los cambios en
|
||||
JuliaMSI se reflejen sin duplicar 10 000 líneas. Si necesitas distribuir el servidor sin
|
||||
el resto del repo del motor:
|
||||
|
||||
```bash
|
||||
mkdir -p vendor/JuliaMSI
|
||||
cp -r ../JuliaMSI/src ../JuliaMSI/Project.toml vendor/JuliaMSI/
|
||||
# edita [sources] en Project.toml:
|
||||
# MSI_src = {path = "vendor/JuliaMSI"}
|
||||
julia --project=. -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
|
||||
```
|
||||
|
||||
También puedes apuntar a cualquiera de los remotos del motor con
|
||||
`Pkg.add(url="https://github.com/Pixelguy14/Julia_msi_GUI")` (o el mirror de Codeberg) y
|
||||
usar el nombre `MSI_src` en `[deps]`, aunque la dependencia de ruta es la más cómoda
|
||||
durante el desarrollo.
|
||||
|
||||
### Parches recomendados para JuliaMSI
|
||||
|
||||
Durante la validación (incluidos datasets reales) se encontraron tres bugs del motor.
|
||||
Los parches están en `patches/` y **ya están aplicados** al checkout local `../JuliaMSI`:
|
||||
|
||||
1. **`juliamsi-fix-nonmmap.patch`** — lectura sin mmap:
|
||||
- `load_imzml_lazy` creaba un `MSIData` temporal para escribir la caché compartiendo
|
||||
el vector de handles reales; su finalizador cerraba los handles del dataset
|
||||
(`Bad file descriptor`). Ahora el objeto temporal usa `IO[]`.
|
||||
- `_iterate_uncompressed_fast` leía en buffers `Vector{Float64}` aunque el `.ibd`
|
||||
fuera Float32, consumiendo el doble de bytes. Ahora usa el tipo real de la fuente.
|
||||
2. **`juliamsi-fix-mask-io.patch`** — máscaras ROI:
|
||||
- `load_and_prepare_mask` llamaba `Gray.(img)` y fallaba con TIFF que cargan como
|
||||
`TiffImages.WidePixel` (p. ej. la imagen óptica de referencia del dataset HR2MSI).
|
||||
Ahora usa el canal de color embebido.
|
||||
- `process_image_pipeline` creaba un elemento estructurante par con el valor por
|
||||
defecto `smoothing=2`, que ImageMorphology rechaza
|
||||
(`connectivity must be odd-sized`). Ahora normaliza a un tamaño impar ≥ 3.
|
||||
|
||||
**Estado upstream (nov 2026):** las tres correcciones ya están integradas en el commit
|
||||
`bc71b9c` del motor, presente en la rama `rel/Windows_Mac_Recompatibility` (Codeberg,
|
||||
GitHub y nube-gran) y en `main` de **GitHub**. `main` de **Codeberg** y de **nube-gran**
|
||||
todavía no las incluye, así que los parches siguen siendo útiles como respaldo para
|
||||
quien clone esas ramas por defecto:
|
||||
|
||||
```bash
|
||||
cd /ruta/a/JuliaMSI
|
||||
git apply /home/pixel/Documents/2026/JuliaMSI_MCP/patches/juliamsi-fix-nonmmap.patch
|
||||
git apply /home/pixel/Documents/2026/JuliaMSI_MCP/patches/juliamsi-fix-mask-io.patch
|
||||
```
|
||||
|
||||
Recomendación: fusionar `rel/Windows_Mac_Recompatibility` en `main` en Codeberg y
|
||||
nube-gran para poder eliminar la carpeta `patches/`. La ruta con mmap (por defecto) no
|
||||
se ve afectada por el primer parche.
|
||||
|
||||
Verificación rápida:
|
||||
|
||||
```bash
|
||||
julia --project=. -e 'using JuliaMSI_MCP; println(JuliaMSI_MCP.SERVER_VERSION)'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Ejecución
|
||||
|
||||
### stdio (recomendado para escritorio)
|
||||
|
||||
```bash
|
||||
julia --project=. --threads=auto bin/run_server.jl
|
||||
```
|
||||
|
||||
`--threads=auto` es importante: el motor paraleliza espectros y el servidor lanza tareas
|
||||
en segundo plano.
|
||||
|
||||
### Streamable HTTP
|
||||
|
||||
```bash
|
||||
julia --project=. --threads=auto bin/run_server.jl --http --host 127.0.0.1 --port 3000
|
||||
```
|
||||
|
||||
Por defecto escucha solo en localhost sin autenticación. Para proteger el endpoint se
|
||||
puede exigir un token compartido:
|
||||
|
||||
```bash
|
||||
julia --project=. --threads=auto bin/run_server.jl --http --port 3000 --token S3CR3T
|
||||
# o bien: JULIA_MSI_MCP_TOKEN=S3CR3T ... --http
|
||||
```
|
||||
|
||||
Los clientes deben enviar `Authorization: Bearer S3CR3T`. Para exponerlo fuera de la
|
||||
máquina, pon un reverse proxy con TLS delante (el token compartido **no** sustituye a TLS).
|
||||
|
||||
### Arranque rápido con sysimage (AOT, Fase 4)
|
||||
|
||||
Para eliminar el JIT de la primera llamada, compila una imagen de sistema:
|
||||
|
||||
```bash
|
||||
julia scripts/build_sysimage.jl # genera build/sys_mcp.so
|
||||
julia --project=. --threads=auto --sysimage=build/sys_mcp.so bin/run_server.jl
|
||||
```
|
||||
|
||||
`scripts/build_sysimage.jl` crea un entorno desechable, desarrolla el motor y
|
||||
`JuliaMSI_MCP`, y ejecuta `scripts/sysimage_warmup.jl` (apertura, espectro, slices,
|
||||
streaming y registro de tools) para precargar el código nativo. La construcción tarda
|
||||
varios minutos y el `.so` es específico de la máquina.
|
||||
|
||||
### Configuración de clientes (cópialas a la ubicación que espera cada cliente):
|
||||
|
||||
- `config/claude_desktop_config.json` → Claude Desktop (`mcpServers`). En Linux:
|
||||
`~/.config/Claude/claude_desktop_config.json`; en Windows:
|
||||
`%APPDATA%\Claude\claude_desktop_config.json`.
|
||||
- `config/vscode_mcp.json` → VS Code / Copilot. Cópialo como `.vscode/mcp.json` en el
|
||||
workspace (o ejecuta *MCP: Add Server*).
|
||||
- `config/opencode.json` → OpenCode V2 (clave `mcp.servers`). Cópialo como
|
||||
`opencode.json` en la raíz del proyecto, o fusiónalo con
|
||||
`~/.config/opencode/opencode.json` para uso global.
|
||||
|
||||
Todas asumen este layout:
|
||||
|
||||
```
|
||||
julia --project=/home/pixel/Documents/2026/JuliaMSI_MCP --threads=auto \
|
||||
/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl
|
||||
```
|
||||
|
||||
Variables de entorno útiles:
|
||||
|
||||
| Variable | Efecto |
|
||||
|----------|--------|
|
||||
| `JULIA_NUM_THREADS=auto` | Hilos del motor (también `--threads=auto`). |
|
||||
| `JULIA_MSI_MCP_ARTIFACTS=/ruta` | Directorio de artefactos (por defecto `<proyecto>/artifacts`). |
|
||||
| `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` | Días de vida de los artefactos antes de podarlos al arrancar (default 7). |
|
||||
| `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` | Presupuesto total de artefactos en bytes (default 0 = sin límite). |
|
||||
| `JULIA_MSI_MCP_TOKEN` | Token compartido para `--http` (equivale a `--token`). |
|
||||
| `JULIA_MSI_MCP_KEEP_STDOUT=1` | Desactiva la redirección de `stdout` (solo para depurar en local). |
|
||||
|
||||
---
|
||||
|
||||
## 5. Catálogo de herramientas
|
||||
|
||||
### Sesión y datos
|
||||
|
||||
| Tool | Tipo | Descripción |
|
||||
|------|------|-------------|
|
||||
| `msi_open_dataset` | síncrona | Abre/cambia dataset imzML/mzML; crea o usa `.cache`; opcional `precompute_analytics`. |
|
||||
| `msi_close_dataset` | síncrona | Cierra handles, vacía caché y devuelve RAM al SO. |
|
||||
| `msi_dataset_info` | síncrona | Estado de la sesión (dimensiones, rango m/z, mmap, RSS, hilos). |
|
||||
| `msi_get_dataset_stats` | síncrona | Estadísticas por espectro (TIC/BPI/NumPoints/rango m/z). |
|
||||
|
||||
### Espectros
|
||||
|
||||
| Tool | Tipo | Descripción |
|
||||
|------|------|-------------|
|
||||
| `msi_get_spectrum_at_coord` | síncrona | Espectro en `(x, y)` con caché LRU. `representation=peaks` o `profile`. |
|
||||
| `msi_get_spectrum_by_index` | síncrona | Espectro por índice lineal (útil para mzML no-imaging). |
|
||||
|
||||
### Imágenes iónicas
|
||||
|
||||
| Tool | Tipo | Descripción |
|
||||
|------|------|-------------|
|
||||
| `msi_get_mz_slice` | síncrona | Imagen iónica inmediata para una masa. |
|
||||
| `msi_get_multiple_mz_slices` | síncrona | Hasta 50 masas en una sola pasada (inversión de jerarquía). |
|
||||
| `msi_plan_ion_image` | planificación | Valida y genera `runspec_id` para una masa. |
|
||||
| `msi_plan_multiple_slices` | planificación | Genera `runspec_id` para un panel de hasta 5000 masas (1 pasada I/O). |
|
||||
|
||||
### Preprocesamiento y analíticas
|
||||
|
||||
| Tool | Tipo | Descripción |
|
||||
|------|------|-------------|
|
||||
| `msi_plan_preprocessing` | planificación | Pipeline streaming (`process_dataset!`) → matriz dispersa. |
|
||||
| `msi_plan_streaming_pipeline` | planificación | Alias del anterior. |
|
||||
| `msi_plan_analytics` | planificación | Escaneo TIC/BPI/Bloom filters en segundo plano. |
|
||||
|
||||
### Ejecución asíncrona
|
||||
|
||||
| Tool | Tipo | Descripción |
|
||||
|------|------|-------------|
|
||||
| `msi_execute_runspec` | ejecución | Lanza el plan en background y devuelve `task_id` (reutiliza tareas salvo `force`). |
|
||||
| `msi_get_task_status` | síncrona | Estado, progreso, tiempos y resumen. |
|
||||
| `msi_get_task_result` | síncrona | Resultado completo (stats, preview, artefactos, matrices opt-in). |
|
||||
| `msi_cancel_task` | síncrona | Cancelación cooperativa. |
|
||||
| `msi_list_tasks` | síncrona | Lista tareas recientes (filtro por estado). |
|
||||
| `msi_list_plans` | síncrona | Lista RunSpecs recientes. |
|
||||
|
||||
### Mantenimiento
|
||||
|
||||
| Tool | Tipo | Descripción |
|
||||
|------|------|-------------|
|
||||
| `msi_clean_artifacts` | síncrona | Poda artefactos por antigüedad y/o presupuesto de bytes (con `dry_run`). |
|
||||
|
||||
### Resources
|
||||
|
||||
| URI | Contenido |
|
||||
|-----|-----------|
|
||||
| `msi://dataset/metadata` | Metadatos de la sesión activa. |
|
||||
| `msi://dataset/stats` | Agregados + primeras 100 filas (no dispara el escaneo). |
|
||||
| `msi://tasks/{task_id}/status` | Estado de una tarea. |
|
||||
| `msi://tasks/{task_id}/result` | Resultado de una tarea. |
|
||||
|
||||
### Prompts
|
||||
|
||||
| Prompt | Uso |
|
||||
|--------|-----|
|
||||
| `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. |
|
||||
|
||||
> Los prompts y su contenido están en inglés (el idioma principal del proyecto). Nombres
|
||||
> anteriores del compendio: `analizar_region_de_interes`, `pipeline_estandar`,
|
||||
> `diagnostico_de_tarea`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Flujo típico (lo que hace el LLM)
|
||||
|
||||
```text
|
||||
msi_open_dataset(file_path="/datos/muestra.imzML", precompute_analytics=false)
|
||||
│
|
||||
├─(dataset grande)─► msi_plan_analytics ─► msi_execute_runspec ─► poll
|
||||
│
|
||||
msi_plan_ion_image(mass=756.55, tolerance=0.1, mask_path="/datos/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") # repetir hasta completed
|
||||
▼
|
||||
msi_get_task_result(task_id="uuid")
|
||||
│ → stats, preview, artifacts.csv/pgm
|
||||
▼
|
||||
msi_close_dataset()
|
||||
```
|
||||
|
||||
Resultado de una imagen iónica (resumido):
|
||||
|
||||
```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. Manejo de errores
|
||||
|
||||
Los handlers nunca tumban el bucle JSON-RPC: toda excepción se convierte en
|
||||
`CallToolResult(is_error=true)` con este cuerpo:
|
||||
|
||||
```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]}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Tipo | Código | Origen típico | Acción sugerida |
|
||||
|------|--------|---------------|-----------------|
|
||||
| `InvalidParams` | `-32602` | masa/tolerancia/máscara/coordenadas | corregir argumentos |
|
||||
| `SessionError` | `-32010` | no hay dataset abierto | `msi_open_dataset` |
|
||||
| `ResourceNotFound` | `-32002` | task_id/URI inexistente | listar tareas/planes |
|
||||
| `InternalError` | `-32603` | I/O, `.cache` corrupta, OOM | revisar stderr; borrar `.cache`; usar streaming |
|
||||
|
||||
---
|
||||
|
||||
## 8. Pruebas
|
||||
|
||||
```bash
|
||||
julia --project=. -e 'using Pkg; Pkg.test()'
|
||||
```
|
||||
|
||||
La suite genera un **imzML sintético válido** (4×3, Float32, 5 picos/espectro, un pico
|
||||
fuerte en 300 Da) y cubre:
|
||||
|
||||
- utilidades (hash canónico, JSON seguro, preview, estadísticas),
|
||||
- apertura/cierre de sesión y `.cache`,
|
||||
- espectro por coordenada e índice,
|
||||
- extracción iónica síncrona y múltiple,
|
||||
- validación de planes y binding al dataset,
|
||||
- flujo asíncrono completo (plan → execute → status → result),
|
||||
- analíticas y pipeline streaming,
|
||||
- resources, prompts y cambio de dataset.
|
||||
|
||||
Resultado actual: **107 tests OK** (~22 s en un equipo de desarrollo).
|
||||
|
||||
También hay un smoke test real por stdio en `test/smoke_stdio.py` (genera el dataset
|
||||
sintético, arranca el servidor y recorre initialize → tools → plan → execute → result).
|
||||
|
||||
---
|
||||
|
||||
## 9. Validación con datasets reales
|
||||
|
||||
Validado con los datos de `Cinvestav_2025/Analisis` (equipo de 12 hilos, 14 GB RAM,
|
||||
disco local; los tiempos varían con la caché de página).
|
||||
|
||||
### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imagen)
|
||||
|
||||
| Métrica | Resultado |
|
||||
|---------|-----------|
|
||||
| Espectros / dimensiones | 34 840 / 260 × 134 |
|
||||
| Tamaño | `.ibd` 815 MB, `.imzML` 56 MB (con `.cache`) |
|
||||
| Apertura | 2.0–3.5 s usando la `.cache` binaria |
|
||||
| Escaneo de analíticas | 6.8–12.9 s |
|
||||
| Espectro `(130,67)` | 966 puntos, BPI 4 026.3, pico base 798.5387 |
|
||||
| Ion image `798.5387 ± 0.15` | 1.8 s, máx 14 274.8, 21 920 píxeles con señal, pico base (167,105) |
|
||||
| 4–5 masas en una pasada | 2.2 s sin máscara / 3.7 s con máscara |
|
||||
| Máscara ROI (óptica → PGM) | 36 % del área; el TIFF óptico directo da ~43 % tras el parche |
|
||||
| Streaming (12 571 espectros enmascarados) | 3.9 s; matriz 420 × 34 840; 1 424 362 nnz; `.mtx` 44 MB |
|
||||
| Streaming (34 840 espectros, sin máscara) | 5.75 s de motor (10.3 s de pared); matriz 500 × 34 840; 3 822 821 nnz (78.1 %); ~61 MB RAM |
|
||||
| Bins más intensos | 580.6, 443.8, 716.2 m/z |
|
||||
|
||||
> La diferencia entre “motor” y “pared” en la primera corrida se debe sobre todo a la
|
||||
> compilación JIT de la ruta de analíticas/streaming y al polling cada 1 s; en llamadas
|
||||
> posteriores el tiempo de pared se acerca al del motor. Es el argumento principal para
|
||||
> el sysimage AOT de la Fase 4.
|
||||
|
||||
El pipeline streaming mantiene la RAM acotada: incluso con 34 840 espectros, el motor
|
||||
solo conserva un espectro por hilo y ensambla una `SparseMatrixCSC`.
|
||||
|
||||
### `mzML/` (perfiles no-imaging)
|
||||
|
||||
| Archivo | Espectros | Apertura | Analíticas |
|
||||
|---------|-----------|----------|------------|
|
||||
| `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` y `msi_get_dataset_stats` funcionan correctamente.
|
||||
- Las tools de imagen (`msi_get_mz_slice`, `msi_plan_ion_image`, …) se rechazan con
|
||||
`InvalidParams` porque el dataset no tiene `coordinate_map` ni dimensiones espaciales.
|
||||
|
||||
### Reproducir
|
||||
|
||||
```bash
|
||||
# Smoke test genérico (detecta imaging vs. mzML automáticamente)
|
||||
python3 test/smoke_stdio.py --dataset /ruta/archivo.imzML
|
||||
|
||||
# Validación más completa (analíticas + ion image + múltiples masas + streaming opcional)
|
||||
JULIA_MSI_MCP_REAL_STREAMING=1 julia --project=. test/real_datasets.jl \
|
||||
/ruta/archivo.imzML /ruta/archivo.mzML
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Estructura del repositorio
|
||||
|
||||
```
|
||||
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 # imagen de sistema AOT (Fase 4)
|
||||
│ └── sysimage_warmup.jl # workload de precompilación
|
||||
├── patches/ # parches de respaldo para el motor (ver §3)
|
||||
├── src/
|
||||
│ ├── JuliaMSI_MCP.jl # módulo e includes
|
||||
│ ├── util.jl # JSON seguro, hashes, previews
|
||||
│ ├── errors.jl # MCPToolError + mapeo JSON-RPC
|
||||
│ ├── session.jl # MSIData persistente + cleanup
|
||||
│ ├── runspec.jl # planificación y validación
|
||||
│ ├── tasks.jl # ejecución asíncrona + registro
|
||||
│ ├── artifacts.jl # CSV/PGM/MatrixMarket + retención
|
||||
│ ├── resources.jl # msi://
|
||||
│ ├── prompts.jl # flujos guiados (inglés)
|
||||
│ ├── 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 # generador imzML de prueba
|
||||
│ ├── runtests.jl
|
||||
│ ├── smoke_stdio.py # smoke test end-to-end por stdio
|
||||
│ └── real_datasets.jl # validación reproducible con datasets reales
|
||||
├── build/ # sysimage generado (ignorado por git)
|
||||
└── artifacts/ # resultados (ignorado por git)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Relación con el compendio arquitectónico
|
||||
|
||||
| Sección del compendio | Implementación MCP |
|
||||
|-----------------------|--------------------|
|
||||
| A.1 `MSIData`, LRU, atómicos | sesión persistente + `GetSpectrum` |
|
||||
| A.2 slices / inversión de jerarquía | `msi_get_multiple_mz_slices`, `msi_plan_multiple_slices` |
|
||||
| A.3 parser dual + `.cache` | `msi_open_dataset` (delegado al motor) |
|
||||
| A.4 handle pool | `--threads=auto`; el motor abre un handle por hilo |
|
||||
| A.5 Bloom filters | rechazo aplicado por `get_mz_slice` |
|
||||
| A.6 mmap + `madvise` | `use_mmap=true` y `preview` acotado |
|
||||
| A.7–A.8 preprocessing/streaming | `msi_plan_preprocessing`, `process_dataset!` |
|
||||
| A.10 máscaras ROI | `mask_path` en planes y slices |
|
||||
| A.11 sysimage AOT | `scripts/build_sysimage.jl` + `--sysimage` (ver §4) |
|
||||
| A.12 `malloc_trim` | `release_os_memory!` en cierre y tareas pesadas |
|
||||
| B.1 STDIO/HTTP | `run_stdio`, `run_http` (con token compartido opcional) |
|
||||
| B.2 tools | 20 tools registradas |
|
||||
| B.3 resources | `msi://dataset/*`, `msi://tasks/*` |
|
||||
| B.4 errores/cleanup | `errors.jl` + hooks + retención de artefactos |
|
||||
|
||||
---
|
||||
|
||||
## 12. Solución de problemas
|
||||
|
||||
| Síntoma | Causa / solución |
|
||||
|---------|------------------|
|
||||
| `GLMakie failed to precompile` al instanciar | GLMakie es una dependencia del proyecto GUI del motor; el núcleo `MSI_src` (y por tanto el servidor MCP) ya no lo carga gracias a `PlottingStubs.jl`. Es inofensivo para el servidor. |
|
||||
| El servidor arranca pero el cliente no ve tools | Revisa que el cliente lance `bin/run_server.jl` con `--project=...` y `--threads=auto`; los logs de arranque van a `stderr`. |
|
||||
| `Dataset file not found` / `.ibd not found` | Usa rutas absolutas y mantén `.imzML` + `.ibd` con el mismo basename. |
|
||||
| Primer slice tarda mucho | Se está ejecutando el escaneo de analíticas. Usa `msi_plan_analytics` + `msi_execute_runspec` en segundo plano. |
|
||||
| `.cache` corrupta tras un crash | Borra `<archivo>.imzML.cache`; el parser XML se regenera. |
|
||||
| Error de permisos al abrir | El motor escribe `<archivo>.imzML.cache` junto al dataset; copia el `.imzML`+`.ibd` a un directorio escribible. |
|
||||
| RSS no baja tras cerrar | `msi_close_dataset` ya llama a `malloc_trim` en Linux; si usas musl/Alpine no existe y la memoria la recupera el kernel por presión. |
|
||||
| `stdout` contaminado al depurar | No uses `println` en el proceso servidor; usa `stderr` o `@info`. `JULIA_MSI_MCP_KEEP_STDOUT=1` desactiva el guard (solo local). |
|
||||
|
||||
## 13. Limitaciones conocidas y próximos pasos
|
||||
|
||||
1. **Un dataset por proceso** (por diseño del motor). Para multiplexar datasets haría
|
||||
falta un pool de sesiones o un proceso por dataset.
|
||||
2. **Cancelación cooperativa**: no se puede interrumpir un `pread`/pasada de disco en
|
||||
curso; la tarea se detiene en el siguiente checkpoint.
|
||||
3. **`msi_get_dataset_stats` y slices síncronos pueden bloquear** durante el primer
|
||||
escaneo de analíticas. Para datasets grandes, usar `msi_plan_analytics` + ejecución.
|
||||
4. **Tasks MCP nativas (SEP-1686/2663)**: se usa un registro de tareas propio, compatible
|
||||
con cualquier cliente. Se puede añadir `task_support=:optional` y `task_detach` cuando
|
||||
se quiera publicar el estado por `tasks/get` del SDK.
|
||||
5. **Huella base de memoria**: `using MSI_src` ya no carga el stack de plotting
|
||||
(CairoMakie/GLMakie) gracias a `PlottingStubs.jl`, pero `Images` (para máscaras) sigue
|
||||
dejando el proceso en ~1.6 GB RSS. Separar el core de datos de `ImageProcessing`
|
||||
reduciría arranque y RAM.
|
||||
6. **TLS**: el token compartido de HTTP protege el endpoint, pero el cifrado en tránsito
|
||||
sigue dependiendo de un reverse proxy (Caddy/nginx) con TLS.
|
||||
|
||||
Resuelto en Fase 4: retención de artefactos (`msi_clean_artifacts` + política al
|
||||
arranque), autenticación HTTP por token compartido, script de sysimage AOT
|
||||
(`scripts/build_sysimage.jl`) y CI (`../.github/workflows/ci.yml`).
|
||||
|
||||
Roadmap sugerido (restante):
|
||||
|
||||
- [ ] Publicar tareas/progreso por el mecanismo nativo de MCP (`task_support=:optional`,
|
||||
`tasks/get`, `notifications/progress`).
|
||||
- [ ] Notificación `notifications/resources/updated` para `msi://tasks/{id}/status`.
|
||||
- [ ] Verificar el arranque con `--sysimage=build/sys_mcp.so` y medir la mejora de TTFX.
|
||||
- [ ] Unit/integration en CI sobre un dataset de referencia real (benchmarks del repo).
|
||||
- [ ] `Dockerfile`/systemd para despliegue headless.
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env julia
|
||||
# ---------------------------------------------------------------------------
|
||||
# JuliaMSI MCP server entry point.
|
||||
#
|
||||
# julia --project=/path/to/JuliaMSI_MCP --threads=auto bin/run_server.jl
|
||||
# julia --project=/path/to/JuliaMSI_MCP --threads=auto bin/run_server.jl --http --port 3000
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
using JuliaMSI_MCP
|
||||
|
||||
function usage()
|
||||
println(stderr, """
|
||||
JuliaMSI MCP server $(JuliaMSI_MCP.SERVER_VERSION)
|
||||
|
||||
Usage:
|
||||
julia --project=<project> --threads=auto bin/run_server.jl [options]
|
||||
|
||||
Options:
|
||||
--http Serve MCP over Streamable HTTP instead of stdio
|
||||
--host <addr> Bind address for --http (default 127.0.0.1)
|
||||
--port <n> Port for --http (default 3000)
|
||||
--token <value> Require `Authorization: Bearer <value>` (HTTP only;
|
||||
also JULIA_MSI_MCP_TOKEN)
|
||||
--version Print the version and exit
|
||||
-h, --help Show this help
|
||||
""")
|
||||
end
|
||||
|
||||
function main(args)
|
||||
http = false
|
||||
host = "127.0.0.1"
|
||||
port = 3000
|
||||
token = nothing
|
||||
i = 1
|
||||
while i <= length(args)
|
||||
a = args[i]
|
||||
if a == "--http"
|
||||
http = true
|
||||
elseif a == "--host"
|
||||
i += 1
|
||||
i <= length(args) || (usage(); return 2)
|
||||
host = args[i]
|
||||
elseif a == "--port"
|
||||
i += 1
|
||||
i <= length(args) || (usage(); return 2)
|
||||
port = try
|
||||
parse(Int, args[i])
|
||||
catch
|
||||
println(stderr, "Invalid --port value: $(args[i])")
|
||||
return 2
|
||||
end
|
||||
elseif a == "--token"
|
||||
i += 1
|
||||
i <= length(args) || (usage(); return 2)
|
||||
token = args[i]
|
||||
elseif a == "--version"
|
||||
println(JuliaMSI_MCP.SERVER_VERSION)
|
||||
return 0
|
||||
elseif a in ("-h", "--help")
|
||||
usage()
|
||||
return 0
|
||||
else
|
||||
println(stderr, "Unknown argument: $(a)")
|
||||
usage()
|
||||
return 2
|
||||
end
|
||||
i += 1
|
||||
end
|
||||
|
||||
if http
|
||||
run_http(host=host, port=port, token=token)
|
||||
else
|
||||
run_stdio()
|
||||
end
|
||||
return 0
|
||||
end
|
||||
|
||||
exit(main(ARGS))
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"juliamsi": {
|
||||
"command": "julia",
|
||||
"args": [
|
||||
"--project=/home/pixel/Documents/2026/JuliaMSI_MCP",
|
||||
"--threads=auto",
|
||||
"/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl"
|
||||
],
|
||||
"env": {
|
||||
"JULIA_NUM_THREADS": "auto",
|
||||
"JULIA_MSI_MCP_ARTIFACTS": "/home/pixel/Documents/2026/JuliaMSI_MCP/artifacts"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"juliamsi": {
|
||||
"type": "local",
|
||||
"command": [
|
||||
"julia",
|
||||
"--project=/home/pixel/Documents/2026/JuliaMSI_MCP",
|
||||
"--threads=auto",
|
||||
"/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl"
|
||||
],
|
||||
"cwd": "/home/pixel/Documents/2026/JuliaMSI_MCP",
|
||||
"environment": {
|
||||
"JULIA_NUM_THREADS": "auto",
|
||||
"JULIA_MSI_MCP_ARTIFACTS": "/home/pixel/Documents/2026/JuliaMSI_MCP/artifacts"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"servers": {
|
||||
"juliamsi": {
|
||||
"type": "stdio",
|
||||
"command": "julia",
|
||||
"args": [
|
||||
"--project=/home/pixel/Documents/2026/JuliaMSI_MCP",
|
||||
"--threads=auto",
|
||||
"/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl"
|
||||
],
|
||||
"env": {
|
||||
"JULIA_NUM_THREADS": "auto",
|
||||
"JULIA_MSI_MCP_ARTIFACTS": "/home/pixel/Documents/2026/JuliaMSI_MCP/artifacts"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
🗺️ Plan de Implementación por Fases
|
||||
Fase 1: Servidor MCP Mínimo con Sesión Persistente (1-2 semanas)
|
||||
|
||||
Objetivo: Validar el handshake y la comunicación básica, eliminando el TTFX de Julia mediante una sesión persistente.
|
||||
|
||||
Configurar el proyecto de Julia e instalar ModelContextProtocol.jl.
|
||||
|
||||
Implementar msi_open_dataset y msi_close_dataset. La sesión debe mantener una Ref{Union{MSIData, Nothing}} para conservar el dataset cargado entre llamadas.
|
||||
|
||||
Implementar msi_get_spectrum_at_coord como una tool síncrona de prueba.
|
||||
|
||||
Configurar el transporte stdio y verificar la conexión con Claude Desktop o VS Code. El objetivo es confirmar que el servidor arranca, negocia capacidades y responde a un tools/call.
|
||||
|
||||
Entregable: Un servidor que permite abrir un .imzML, consultar un espectro y cerrar la sesión sin recargar el dataset.
|
||||
Fase 2: Núcleo Asíncrono con Tasks (2-3 semanas)
|
||||
|
||||
Objetivo: Implementar el patrón de planificación/ejecución con tareas en segundo plano.
|
||||
|
||||
Definir la estructura RunSpec (inmutable, con un campo hash calculado a partir de los parámetros validados).
|
||||
|
||||
Implementar msi_plan_ion_image y msi_plan_preprocessing. Estas tools solo validan y generan el RunSpec; no ejecutan cómputo pesado.
|
||||
|
||||
Implementar msi_execute_runspec. Al recibir un runspec_hash, lanza una Task de Julia (Threads.@spawn) que ejecuta la función correspondiente (get_mz_slice o run_streaming_pipeline). Devuelve un task_id de inmediato.
|
||||
|
||||
Implementar msi_get_task_status. Consulta el estado de la Task usando el task_id. El SDK de Julia permite exponer el estado de las tareas a través de tasks/get.
|
||||
|
||||
Probar el flujo completo: planificar → ejecutar → polling → obtener resultado.
|
||||
|
||||
Entregable: Un servidor que puede lanzar la extracción de una imagen iónica de forma asíncrona y notificar al LLM cuando termina.
|
||||
Fase 3: Expansión del Catálogo (2-3 semanas)
|
||||
|
||||
Objetivo: Cubrir las capacidades principales del motor JuliaMSI.
|
||||
|
||||
Añadir msi_plan_multiple_slices para la inversión de jerarquía de búsqueda (A.2), que es computacionalmente más costosa.
|
||||
|
||||
Añadir msi_plan_streaming_pipeline para el motor de preprocesamiento streaming (A.8).
|
||||
|
||||
Implementar los Resources (msi://dataset/metadata, msi://dataset/stats, msi://tasks/{id}/status).
|
||||
|
||||
Registrar los Prompts (analyze_region_of_interest, standard_pipeline).
|
||||
|
||||
Entregable: Un servidor MCP con el conjunto completo de tools asíncronas, resources y prompts para flujos de trabajo de MSI.
|
||||
Fase 4: Transporte Remoto y Resiliencia (1-2 semanas)
|
||||
|
||||
Objetivo: Habilitar el acceso desde clientes remotos y garantizar la estabilidad en sesiones prolongadas.
|
||||
|
||||
Habilitar el transporte Streamable HTTP (soportado por el SDK) para conexiones desde la nube o clústeres HPC.
|
||||
|
||||
Integrar el hook de limpieza post-ejecución en msi_close_dataset y al finalizar cada Task pesada: GC.gc(true) + ccall(:malloc_trim, ...) (A.12) para devolver la memoria al SO.
|
||||
|
||||
Añadir manejo de errores estructurado: mapear excepciones de Julia (OutOfMemoryError, IOError) a códigos de error JSON-RPC y sugerir acciones al LLM (por ejemplo, "use el pipeline streaming en lugar de la matriz densa").
|
||||
|
||||
Entregable: Un servidor MCP listo para producción, estable en sesiones largas y accesible de forma remota.
|
||||
|
||||
---
|
||||
|
||||
## ✅ Estado de implementación (noviembre 2026)
|
||||
|
||||
| Fase | Estado | Evidencia |
|
||||
|------|--------|-----------|
|
||||
| 1. Sesión persistente + tools básicas | ✅ | `src/session.jl`, `msi_open_dataset`, `msi_close_dataset`, `msi_get_spectrum_at_coord`; pruebas en `test/runtests.jl`. |
|
||||
| 2. Núcleo asíncrono con Tasks | ✅ | `RunSpec` con hash SHA-256 (`src/runspec.jl`), `msi_plan_*`, `msi_execute_runspec`, `msi_get_task_status` (`src/tasks.jl`). |
|
||||
| 3. Catálogo completo | ✅ | 19 tools, 4 resources/plantillas (`msi://dataset/*`, `msi://tasks/*`) y 3 prompts (`src/resources.jl`, `src/prompts.jl`). |
|
||||
| 4. HTTP + resiliencia | 🟢 | Transporte Streamable HTTP (`run_http`) con token compartido opcional (`--token`/`JULIA_MSI_MCP_TOKEN`), `GC.gc(true)` + `malloc_trim` (`release_os_memory!`), errores estructurados (`src/errors.jl`), retención de artefactos (`msi_clean_artifacts` + política al arranque), script de sysimage AOT (`scripts/build_sysimage.jl`) y CI (`.github/workflows/ci.yml`). Pendiente: verificar el arranque con sysimage y publicar tareas/progreso por el mecanismo nativo de MCP. |
|
||||
|
||||
Extras no previstos en el plan original: `msi_get_dataset_stats`, `msi_get_spectrum_by_index`,
|
||||
`msi_plan_analytics`, `msi_list_plans`, `msi_list_tasks`, `msi_cancel_task`, generación
|
||||
de artefactos CSV/PGM/MatrixMarket y un smoke test end-to-end (`test/smoke_stdio.py`).
|
||||
|
||||
Verificación: `julia --project=. -e 'using Pkg; Pkg.test()'` → **100/100 tests OK**.
|
||||
|
||||
Durante la integración se detectaron y corrigieron tres bugs del motor: dos en la ruta
|
||||
sin mmap (handles cerrados por el finalizador del objeto temporal de caché y buffers
|
||||
Float64 sobre datos Float32) y uno en el procesamiento de máscaras (TIFF `WidePixel` y
|
||||
elemento estructurante par). Los parches están en `patches/juliamsi-fix-nonmmap.patch` y
|
||||
`patches/juliamsi-fix-mask-io.patch`, y ya están aplicados al checkout local `../JuliaMSI`.
|
||||
|
||||
Validación con datos reales de `Cinvestav_2025/Analisis`: HR2MSI bladder (34 840
|
||||
espectros, 260×134, analíticas en ~7 s, ion image ~2 s, 4–5 masas en una pasada ~2–4 s)
|
||||
y mzML (T9_A1, Cytochrome_C, Col_1) con rechazo correcto de las tools de imagen para
|
||||
datos no-imaging.
|
||||
|
||||
Última corrida completa (sin máscara, `--threads` por defecto):
|
||||
|
||||
- streaming de **34 840 espectros en 5.75 s**;
|
||||
- matriz **500 × 34 840**, **3 822 821 nnz** (78.1 % dispersa), ~61 MB de RAM;
|
||||
- `wall_seconds=10.3` (incluye overhead de polling y JIT del primer llamado).
|
||||
|
||||
**Posición en el plan:** Fases 1–3 completas; Fase 4 implementada (HTTP+token, retención de
|
||||
artefactos, script AOT y CI). Quedan como refinamiento: verificar el arranque con el
|
||||
sysimage generado, y publicar tareas/progreso por el mecanismo nativo de MCP
|
||||
(`task_support=:optional` / `tasks/get`).
|
||||
|
||||
Nota sobre los parches: las tres correcciones del motor ya están upstream en el commit
|
||||
`bc71b9c` (rama `rel/Windows_Mac_Recompatibility` y `main` de GitHub). `main` de Codeberg
|
||||
y de nube-gran aún no las incluyen, por lo que `patches/` se conserva como respaldo.
|
||||
@@ -0,0 +1,35 @@
|
||||
diff --git a/src/ImageProcessing.jl b/src/ImageProcessing.jl
|
||||
index d47ea6a..2518406 100644
|
||||
--- a/src/ImageProcessing.jl
|
||||
+++ b/src/ImageProcessing.jl
|
||||
@@ -31,8 +31,15 @@ function load_and_prepare_mask(mask_path::String, target_dims::Tuple{Int, Int})
|
||||
# Load the image
|
||||
img = Images.load(mask_path)
|
||||
|
||||
- # Convert to grayscale if it's a color image
|
||||
- gray_img = Gray.(img)
|
||||
+ # Convert to grayscale. Most images are already Colorant arrays, but TIFFs
|
||||
+ # with extra samples (e.g. the optical reference images shipped with MSI
|
||||
+ # datasets) load as TiffImages.WidePixel, for which Gray.(img) has no method.
|
||||
+ # Fall back to the embedded color channel in that case.
|
||||
+ gray_img = if eltype(img) <: Colorant
|
||||
+ Gray.(img)
|
||||
+ else
|
||||
+ Gray.([getproperty(p, :color) for p in img])
|
||||
+ end
|
||||
|
||||
# Binarize using Otsu's method - white regions become 'true'
|
||||
binary_img = binarize(gray_img, Otsu())
|
||||
@@ -101,7 +108,11 @@ function process_image_pipeline(gray_img;
|
||||
|
||||
# --- Step 4: Smooth Edges ---
|
||||
# A morphological closing with a small disk smooths outlines.
|
||||
- smoothing_kernel = ones(Bool, (smoothing, smoothing))
|
||||
+ # ImageMorphology requires odd-sized structuring elements; the historical
|
||||
+ # default smoothing=2 produced a 2×2 matrix and threw "connectivity must be
|
||||
+ # odd-sized". Normalize to the next odd size (minimum 3).
|
||||
+ smooth_size = max(3, isodd(smoothing) ? smoothing : smoothing + 1)
|
||||
+ smoothing_kernel = ones(Bool, (smooth_size, smooth_size))
|
||||
smoothed_img = closing(holes_filled_img, smoothing_kernel)
|
||||
|
||||
# --- Return all intermediate steps for visualization ---
|
||||
@@ -0,0 +1,40 @@
|
||||
diff --git a/src/MSIData.jl b/src/MSIData.jl
|
||||
index 1e88fa3..ed8851c 100644
|
||||
--- a/src/MSIData.jl
|
||||
+++ b/src/MSIData.jl
|
||||
@@ -1532,9 +1532,12 @@ end
|
||||
function _iterate_uncompressed_fast(f::Function, data::MSIData, source::ImzMLSource, indices_to_iterate::Union{AbstractVector{Int}, Nothing})
|
||||
spectrum_indices = (indices_to_iterate === nothing) ? (1:length(data.spectra_metadata)) : indices_to_iterate
|
||||
|
||||
- # Intialize local buffers for this thread's sequential iteration
|
||||
- mz_buf = Vector{Float64}()
|
||||
- int_buf = Vector{Float64}()
|
||||
+ # Initialize local buffers for this thread's sequential iteration.
|
||||
+ # IMPORTANT: the element type must match the on-disk format. Using Float64
|
||||
+ # buffers here made `read!` consume twice as many bytes for Float32 datasets
|
||||
+ # and misinterpret them as Float64 garbage (breaking use_mmap=false).
|
||||
+ mz_buf = Vector{source.mz_format}()
|
||||
+ int_buf = Vector{source.intensity_format}()
|
||||
|
||||
for i in spectrum_indices
|
||||
meta = data.spectra_metadata[i]
|
||||
diff --git a/src/imzML.jl b/src/imzML.jl
|
||||
index a144893..f8071e2 100644
|
||||
--- a/src/imzML.jl
|
||||
+++ b/src/imzML.jl
|
||||
@@ -559,8 +559,13 @@ function load_imzml_lazy(file_path::String; cache_size::Int=100, use_mmap::Bool=
|
||||
mz_is_compressed, int_is_compressed, global_mode)
|
||||
|
||||
@debug "Metadata parsing complete. Saving cache for next time..."
|
||||
- # We create a temporary MSIData just for save_metadata_cache
|
||||
- tmp_source = ImzMLSource(ibd_handles, default_mz_format, default_intensity_format, mmap_data, any_comp)
|
||||
+ # We create a temporary MSIData just for save_metadata_cache.
|
||||
+ # IMPORTANT: do NOT share the real `ibd_handles` vector here. MSIData
|
||||
+ # installs a finalizer that closes every handle in `source.ibd_handles`;
|
||||
+ # when this temporary object is garbage-collected it would close the
|
||||
+ # handles owned by the real dataset (breaking use_mmap=false reads with
|
||||
+ # "Bad file descriptor"). The cache writer only needs the formats.
|
||||
+ tmp_source = ImzMLSource(IO[], default_mz_format, default_intensity_format, nothing, any_comp)
|
||||
tmp_msi = MSIData(tmp_source, spectra_metadata, instrument_meta, (width, height), nothing, cache_size)
|
||||
save_metadata_cache(tmp_msi, cache_path)
|
||||
end
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env julia
|
||||
# ---------------------------------------------------------------------------
|
||||
# Build a custom system image (AOT) for the JuliaMSI MCP server.
|
||||
#
|
||||
# This bakes JuliaMSI_MCP + MSI_src (and their reachable code) into a native
|
||||
# shared object so the server starts without the first-call JIT latency.
|
||||
#
|
||||
# julia scripts/build_sysimage.jl
|
||||
#
|
||||
# Environment:
|
||||
# JULIA_MSI_PATH Path to the JuliaMSI engine checkout (default ../JuliaMSI)
|
||||
# JULIA_MSI_MCP_SYSIMAGE Output path (default build/sys_mcp.so)
|
||||
#
|
||||
# Run the server with the image afterwards:
|
||||
# julia --project=. --threads=auto --sysimage=build/sys_mcp.so bin/run_server.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
using Pkg
|
||||
|
||||
const MCP_DIR = normpath(joinpath(@__DIR__, ".."))
|
||||
const ENGINE = get(ENV, "JULIA_MSI_PATH", normpath(joinpath(MCP_DIR, "..", "JuliaMSI")))
|
||||
const EXT = Sys.iswindows() ? ".dll" : Sys.isapple() ? ".dylib" : ".so"
|
||||
const OUT = get(ENV, "JULIA_MSI_MCP_SYSIMAGE", joinpath(MCP_DIR, "build", "sys_mcp" * EXT))
|
||||
|
||||
isfile(joinpath(ENGINE, "Project.toml")) ||
|
||||
error("JuliaMSI engine not found at $(ENGINE). Set JULIA_MSI_PATH to the checkout.")
|
||||
|
||||
println("--- JuliaMSI_MCP system image build ---")
|
||||
println("engine : ", ENGINE)
|
||||
println("output : ", OUT)
|
||||
|
||||
mkpath(dirname(OUT))
|
||||
|
||||
# Use a throwaway environment so the runtime project stays lean. The engine is
|
||||
# developed first so its package name/uuid (MSI_src) resolves for JuliaMSI_MCP.
|
||||
Pkg.activate(; temp=true)
|
||||
Pkg.develop(PackageSpec(path=ENGINE))
|
||||
Pkg.develop(PackageSpec(path=MCP_DIR))
|
||||
Pkg.add("PackageCompiler")
|
||||
|
||||
using PackageCompiler
|
||||
|
||||
create_sysimage(
|
||||
[:JuliaMSI_MCP],
|
||||
sysimage_path = OUT,
|
||||
precompile_execution_file = joinpath(@__DIR__, "sysimage_warmup.jl"),
|
||||
incremental = true,
|
||||
)
|
||||
|
||||
println("--- System image written to: ", OUT, " ---")
|
||||
println("Run the server with:")
|
||||
println(" julia --project=$(MCP_DIR) --threads=auto --sysimage=$(OUT) $(joinpath(MCP_DIR, "bin", "run_server.jl"))")
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env julia
|
||||
# ---------------------------------------------------------------------------
|
||||
# One-time setup: point Pkg at the local JuliaMSI engine and instantiate.
|
||||
#
|
||||
# JULIA_MSI_PATH=/path/to/JuliaMSI julia scripts/setup.jl
|
||||
#
|
||||
# By default the sibling `../JuliaMSI` directory (relative to this project) is
|
||||
# used, matching the default layout of the development workspace.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
using Pkg
|
||||
|
||||
project_dir = dirname(@__DIR__)
|
||||
default_engine = normpath(joinpath(project_dir, "..", "JuliaMSI"))
|
||||
engine = get(ENV, "JULIA_MSI_PATH", default_engine)
|
||||
|
||||
if !isfile(joinpath(engine, "Project.toml"))
|
||||
error("JuliaMSI engine not found at $(engine). Set JULIA_MSI_PATH to the JuliaMSI checkout.")
|
||||
end
|
||||
|
||||
println("Using JuliaMSI engine at: $(abspath(engine))")
|
||||
Pkg.develop(PackageSpec(path=abspath(engine)))
|
||||
Pkg.instantiate()
|
||||
Pkg.precompile()
|
||||
println("Setup complete. Start the server with:")
|
||||
println(" julia --project=$(project_dir) --threads=auto $(joinpath(project_dir, "bin", "run_server.jl"))")
|
||||
@@ -0,0 +1,58 @@
|
||||
# scripts/sysimage_warmup.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Precompile warm-up workload for the JuliaMSI MCP server sysimage.
|
||||
#
|
||||
# This file is executed by PackageCompiler (scripts/build_sysimage.jl) inside a
|
||||
# subprocess that already has `JuliaMSI_MCP` baked in. It exercises every
|
||||
# engine/MCP code path the server uses, so the resulting system image contains
|
||||
# native code for them instead of paying JIT on first use.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
using JuliaMSI_MCP
|
||||
const J = JuliaMSI_MCP
|
||||
|
||||
tmp = mktempdir()
|
||||
ENV["JULIA_MSI_MCP_ARTIFACTS"] = joinpath(tmp, "artifacts")
|
||||
|
||||
include(joinpath(@__DIR__, "..", "test", "synthetic.jl"))
|
||||
imzml_path = write_synthetic_imzml(tmp; width=3, height=3)
|
||||
|
||||
# Persistent session + metadata.
|
||||
J.open_dataset(imzml_path; precompute_analytics=true)
|
||||
|
||||
# Random-access spectrum query.
|
||||
mz, intensity = J.MSI_src.GetSpectrum(J.require_data(), 1)
|
||||
|
||||
# Ion image (sync execution path).
|
||||
J._run_ion_image(
|
||||
J._sync_runspec(:ion_image, Dict(
|
||||
"mass" => 300.0, "tolerance" => 0.5, "mask_path" => nothing,
|
||||
"include_matrix" => true, "preview_max_dim" => 32, "output_name" => "warm")),
|
||||
J._sync_task(:ion_image), J.require_data())
|
||||
|
||||
# Multiple slices (hierarchy inversion).
|
||||
J._run_multiple_slices(
|
||||
J._sync_runspec(:multiple_slices, Dict(
|
||||
"masses" => [100.0, 300.0, 500.0], "tolerance" => 0.5, "mask_path" => nothing,
|
||||
"include_matrix" => false, "preview_max_dim" => 32, "output_name" => "warm")),
|
||||
J._sync_task(:multiple_slices), J.require_data())
|
||||
|
||||
# Streaming preprocessing (Sprint 2).
|
||||
J._run_streaming_pipeline(
|
||||
J._sync_runspec(:streaming_pipeline, Dict(
|
||||
"steps" => [
|
||||
Dict("name" => "smoothing", "params" => Dict("method" => "savitzky_golay", "window" => 5, "order" => 2)),
|
||||
Dict("name" => "normalization", "params" => Dict("method" => "tic")),
|
||||
Dict("name" => "peak_picking", "params" => Dict("method" => "profile", "snr_threshold" => 3.0)),
|
||||
],
|
||||
"num_bins" => 50, "min_peaks_per_bin" => 1, "frequency_threshold" => 0.0,
|
||||
"reference_peaks" => Float64[], "mask_path" => nothing,
|
||||
"include_matrix" => false, "output_name" => "warm")),
|
||||
J._sync_task(:streaming_pipeline), J.require_data())
|
||||
|
||||
J.close_dataset()
|
||||
|
||||
# Register tools/resources/prompts so the schema builders are compiled too.
|
||||
J.build_server()
|
||||
|
||||
println("sysimage warmup complete")
|
||||
@@ -0,0 +1,56 @@
|
||||
module JuliaMSI_MCP
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# JuliaMSI_MCP — Model Context Protocol server for the JuliaMSI engine.
|
||||
#
|
||||
# Layers:
|
||||
# * session : one persistent MSIData per server process
|
||||
# * planning : validated, content-addressed RunSpecs
|
||||
# * execution : background Julia tasks + polling
|
||||
# * artifacts : compact results + on-disk full data
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
using JSON3
|
||||
using SHA
|
||||
using Dates
|
||||
using Printf
|
||||
using Statistics
|
||||
using SparseArrays
|
||||
using CSV
|
||||
using DataFrames
|
||||
using UUIDs: uuid4
|
||||
|
||||
import MSI_src
|
||||
using ModelContextProtocol
|
||||
|
||||
include("util.jl")
|
||||
include("errors.jl")
|
||||
include("session.jl")
|
||||
include("artifacts.jl")
|
||||
include("runspec.jl")
|
||||
include("tasks.jl")
|
||||
|
||||
include("tools/dataset.jl")
|
||||
include("tools/spectra.jl")
|
||||
include("tools/imaging.jl")
|
||||
include("tools/planning.jl")
|
||||
include("tools/tasks.jl")
|
||||
include("tools/maintenance.jl")
|
||||
|
||||
include("resources.jl")
|
||||
include("prompts.jl")
|
||||
include("server.jl")
|
||||
|
||||
export build_server,
|
||||
run_stdio,
|
||||
run_http,
|
||||
open_dataset,
|
||||
close_dataset,
|
||||
session_metadata,
|
||||
release_os_memory!,
|
||||
RunSpec,
|
||||
EngineTask,
|
||||
SERVER_NAME,
|
||||
SERVER_VERSION
|
||||
|
||||
end # module
|
||||
@@ -0,0 +1,263 @@
|
||||
# src/artifacts.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Result persistence.
|
||||
#
|
||||
# Ion images and feature matrices must never be dumped into the JSON-RPC channel
|
||||
# verbatim: a 2000×2000 float matrix is ~32 MB of JSON and stalls the model.
|
||||
# Tools return compact statistics + a downsampled preview, and the full data is
|
||||
# written to disk under `artifacts/<task_id>/`.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const ARTIFACT_LOCK = ReentrantLock()
|
||||
|
||||
"""Root directory for generated files (override with `JULIA_MSI_MCP_ARTIFACTS`)."""
|
||||
function artifact_root()
|
||||
root = get(ENV, "JULIA_MSI_MCP_ARTIFACTS", "")
|
||||
if isempty(root)
|
||||
root = joinpath(pkgdir(@__MODULE__), "artifacts")
|
||||
end
|
||||
root = abspath(expanduser(root))
|
||||
lock(ARTIFACT_LOCK) do
|
||||
isdir(root) || mkpath(root)
|
||||
end
|
||||
return root
|
||||
end
|
||||
|
||||
function artifact_dir(task_id::AbstractString; label::AbstractString="")
|
||||
dir = joinpath(artifact_root(), safe_filename(task_id, "task"))
|
||||
if !isempty(label)
|
||||
dir = joinpath(dir, safe_filename(label, "output"))
|
||||
end
|
||||
lock(ARTIFACT_LOCK) do
|
||||
isdir(dir) || mkpath(dir)
|
||||
end
|
||||
return dir
|
||||
end
|
||||
|
||||
"""
|
||||
artifact_retention_config() -> (max_age_days, max_total_bytes)
|
||||
|
||||
Read the retention policy from the environment. Both knobs default to disabled:
|
||||
- `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` (default 7): remove task dirs older than this.
|
||||
- `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` (default 0): trim oldest dirs until the root is
|
||||
under this many bytes (0 disables the size budget).
|
||||
"""
|
||||
function artifact_retention_config()
|
||||
max_age_days = try
|
||||
parse(Float64, get(ENV, "JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS", "7"))
|
||||
catch
|
||||
7.0
|
||||
end
|
||||
max_total_bytes = try
|
||||
parse(Float64, get(ENV, "JULIA_MSI_MCP_ARTIFACT_MAX_BYTES", "0"))
|
||||
catch
|
||||
0.0
|
||||
end
|
||||
return max_age_days, max_total_bytes
|
||||
end
|
||||
|
||||
function _dir_size_bytes(path::AbstractString)
|
||||
total = 0
|
||||
try
|
||||
for (root, _dirs, files) in walkdir(path)
|
||||
for f in files
|
||||
p = joinpath(root, f)
|
||||
try
|
||||
total += filesize(p)
|
||||
catch
|
||||
end
|
||||
end
|
||||
end
|
||||
catch
|
||||
end
|
||||
return total
|
||||
end
|
||||
|
||||
"""
|
||||
prune_artifacts!(; max_age_days=0.0, max_total_bytes=0.0, dry_run=false)
|
||||
|
||||
Delete artifact task-directories older than `max_age_days` (0 disables age-based
|
||||
pruning) and, if `max_total_bytes > 0`, remove oldest-first until the artifact root
|
||||
fits the budget. Only top-level task directories (one per task) are considered.
|
||||
|
||||
Returns a summary dict with `removed`, `freed_bytes`, `remaining_bytes` and `dry_run`.
|
||||
"""
|
||||
function prune_artifacts!(; max_age_days::Real=0.0, max_total_bytes::Real=0.0,
|
||||
dry_run::Bool=false)
|
||||
root = artifact_root()
|
||||
removed = 0
|
||||
freed = 0
|
||||
|
||||
lock(ARTIFACT_LOCK) do
|
||||
entries = sort!([(mtime(p), p) for p in readdir(root; join=true) if isdir(p)];
|
||||
by=first) # oldest first
|
||||
handled = Set{String}()
|
||||
|
||||
# Age-based pruning.
|
||||
if max_age_days > 0
|
||||
for (mt, path) in entries
|
||||
if time() - mt > max_age_days * 86400
|
||||
freed += _dir_size_bytes(path)
|
||||
dry_run || rm(path; recursive=true, force=true)
|
||||
push!(handled, path)
|
||||
removed += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Size budget: oldest-first until the root fits.
|
||||
if max_total_bytes > 0
|
||||
for (_, path) in entries
|
||||
path in handled && continue
|
||||
_dir_size_bytes(root) <= max_total_bytes && break
|
||||
freed += _dir_size_bytes(path)
|
||||
dry_run || rm(path; recursive=true, force=true)
|
||||
push!(handled, path)
|
||||
removed += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
remaining_bytes = _dir_size_bytes(root)
|
||||
return Dict{String,Any}(
|
||||
"removed" => removed,
|
||||
"freed_bytes" => freed,
|
||||
"remaining_bytes" => remaining_bytes,
|
||||
"dry_run" => dry_run,
|
||||
"root" => root,
|
||||
)
|
||||
end
|
||||
|
||||
function artifact_record(path::AbstractString)
|
||||
isfile(path) || return nothing
|
||||
return Dict{String,Any}(
|
||||
"path" => String(path),
|
||||
"uri" => "file://" * String(path),
|
||||
"name" => basename(path),
|
||||
"bytes" => filesize(path),
|
||||
"mime_type" => if endswith(lowercase(path), ".csv")
|
||||
"text/csv"
|
||||
elseif endswith(lowercase(path), ".pgm")
|
||||
"image/x-portable-graymap"
|
||||
elseif endswith(lowercase(path), ".mtx")
|
||||
"text/plain"
|
||||
elseif endswith(lowercase(path), ".json")
|
||||
JSON_MIME
|
||||
else
|
||||
"application/octet-stream"
|
||||
end,
|
||||
)
|
||||
end
|
||||
|
||||
function write_json_file(path::AbstractString, payload)
|
||||
open(path, "w") do io
|
||||
JSON3.write(io, jsonable(payload))
|
||||
end
|
||||
return artifact_record(path)
|
||||
end
|
||||
|
||||
"""Write an intensity matrix as CSV with a `y\\x` header row."""
|
||||
function write_matrix_csv(path::AbstractString, mat::AbstractMatrix{<:Real})
|
||||
h, w = size(mat)
|
||||
open(path, "w") do io
|
||||
print(io, "y\\x")
|
||||
for x in 1:w
|
||||
print(io, ",", x)
|
||||
end
|
||||
println(io)
|
||||
for y in 1:h
|
||||
print(io, y)
|
||||
for x in 1:w
|
||||
v = Float64(mat[y, x])
|
||||
print(io, ",", isfinite(v) ? repr(v) : "0.0")
|
||||
end
|
||||
println(io)
|
||||
end
|
||||
end
|
||||
return artifact_record(path)
|
||||
end
|
||||
|
||||
"""Write a normalized 8-bit grayscale PGM (viewable in most image apps)."""
|
||||
function write_matrix_pgm(path::AbstractString, mat::AbstractMatrix{<:Real})
|
||||
h, w = size(mat)
|
||||
vmax = 0.0
|
||||
@inbounds for v in mat
|
||||
f = Float64(v)
|
||||
isfinite(f) && f > vmax && (vmax = f)
|
||||
end
|
||||
scale = vmax > 0 ? 255.0 / vmax : 0.0
|
||||
open(path, "w") do io
|
||||
write(io, "P5\n# JuliaMSI_MCP ion image (normalized to max)\n$(w) $(h)\n255\n")
|
||||
buf = Vector{UInt8}(undef, h * w)
|
||||
k = 1
|
||||
# PGM is row-major; Julia matrices are column-major.
|
||||
for y in 1:h, x in 1:w
|
||||
v = Float64(mat[y, x])
|
||||
buf[k] = (!isfinite(v) || v <= 0) ? 0x00 : round(UInt8, clamp(v * scale, 0.0, 255.0))
|
||||
k += 1
|
||||
end
|
||||
write(io, buf)
|
||||
end
|
||||
return artifact_record(path)
|
||||
end
|
||||
|
||||
"""Write a vector as a two-column CSV (`index,value`)."""
|
||||
function write_vector_csv(path::AbstractString, values::AbstractVector{<:Real};
|
||||
header::AbstractString="index,value")
|
||||
open(path, "w") do io
|
||||
println(io, header)
|
||||
for (i, v) in enumerate(values)
|
||||
println(io, i, ",", repr(Float64(v)))
|
||||
end
|
||||
end
|
||||
return artifact_record(path)
|
||||
end
|
||||
|
||||
"""Stream a `SparseMatrixCSC` to Matrix Market coordinate format."""
|
||||
function write_sparse_mtx(path::AbstractString, mat::SparseMatrixCSC)
|
||||
m, n = size(mat)
|
||||
open(path, "w") do io
|
||||
write(io, "%%MatrixMarket matrix coordinate real general\n")
|
||||
write(io, "$(m) $(n) $(SparseArrays.nnz(mat))\n")
|
||||
rows = SparseArrays.rowvals(mat)
|
||||
vals = SparseArrays.nonzeros(mat)
|
||||
@inbounds for j in 1:n
|
||||
for idx in SparseArrays.nzrange(mat, j)
|
||||
write(io, "$(rows[idx]) $(j) $(vals[idx])\n")
|
||||
end
|
||||
end
|
||||
end
|
||||
return artifact_record(path)
|
||||
end
|
||||
|
||||
"""Persist a single ion image (CSV + PGM + JSON sidecar) and return the paths."""
|
||||
function persist_ion_image(dir::AbstractString, label::AbstractString,
|
||||
mat::AbstractMatrix{<:Real}; extra=nothing)
|
||||
base = safe_filename(label, "ion_image")
|
||||
csv = write_matrix_csv(joinpath(dir, base * ".csv"), mat)
|
||||
pgm = write_matrix_pgm(joinpath(dir, base * ".pgm"), mat)
|
||||
sidecar = Dict{String,Any}(
|
||||
"label" => String(label),
|
||||
"stats" => matrix_stats(mat),
|
||||
"artifacts" => Dict{String,Any}("csv" => csv, "pgm" => pgm),
|
||||
)
|
||||
extra !== nothing && (sidecar["metadata"] = extra)
|
||||
meta = write_json_file(joinpath(dir, base * ".json"), sidecar)
|
||||
return Dict{String,Any}("csv" => csv, "pgm" => pgm, "metadata" => meta)
|
||||
end
|
||||
|
||||
"""Top-N bins by total intensity for a feature matrix."""
|
||||
function top_bins(mat::SparseMatrixCSC, bin_centers::AbstractVector{<:Real};
|
||||
n::Integer=20)
|
||||
totals = vec(sum(mat; dims=2))
|
||||
positive = findall(>(0), totals)
|
||||
isempty(positive) && return Any[]
|
||||
k = min(Int(n), length(positive))
|
||||
order = positive[sortperm(totals[positive]; rev=true)[1:k]]
|
||||
return [Dict{String,Any}(
|
||||
"bin" => Int(i),
|
||||
"mz" => compact_float(bin_centers[i]),
|
||||
"total_intensity" => compact_float(totals[i]),
|
||||
"spectra_with_signal" => count(>(0), mat[i, :]),
|
||||
) for i in order]
|
||||
end
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
# src/errors.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Structured errors: Julia exceptions -> JSON-RPC-ish codes that the LLM can
|
||||
# reason about, as specified in the architectural compendium (B.4).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const ERR_INVALID_PARAMS = -32602
|
||||
const ERR_INTERNAL = -32603
|
||||
const ERR_METHOD_NOT_FOUND = -32601
|
||||
const ERR_RESOURCE_NOT_FOUND = -32002
|
||||
const ERR_SESSION = -32010
|
||||
|
||||
"""
|
||||
MCPToolError(code, kind, message; suggested_action=nothing, details=nothing)
|
||||
|
||||
A tool-level failure that should be reported to the model with `isError=true`
|
||||
instead of crashing the server loop.
|
||||
"""
|
||||
struct MCPToolError <: Exception
|
||||
code::Int
|
||||
kind::String
|
||||
message::String
|
||||
suggested_action::Union{Nothing,String}
|
||||
details::Union{Nothing,Dict{String,Any}}
|
||||
end
|
||||
|
||||
function MCPToolError(message::AbstractString; kind::AbstractString="ToolError",
|
||||
code::Int=ERR_INTERNAL,
|
||||
suggested_action::Union{Nothing,AbstractString}=nothing,
|
||||
details=nothing)
|
||||
return MCPToolError(code, String(kind), String(message),
|
||||
suggested_action === nothing ? nothing : String(suggested_action),
|
||||
details === nothing ? nothing : Dict{String,Any}(details))
|
||||
end
|
||||
|
||||
invalid_params(message; suggested_action=nothing, details=nothing) =
|
||||
MCPToolError(message; kind="InvalidParams", code=ERR_INVALID_PARAMS,
|
||||
suggested_action=suggested_action, details=details)
|
||||
|
||||
internal_error(message; suggested_action=nothing, details=nothing) =
|
||||
MCPToolError(message; kind="InternalError", code=ERR_INTERNAL,
|
||||
suggested_action=suggested_action, details=details)
|
||||
|
||||
session_error(message; suggested_action=nothing) =
|
||||
MCPToolError(message; kind="SessionError", code=ERR_SESSION,
|
||||
suggested_action=suggested_action)
|
||||
|
||||
resource_not_found(message; suggested_action=nothing) =
|
||||
MCPToolError(message; kind="ResourceNotFound", code=ERR_RESOURCE_NOT_FOUND,
|
||||
suggested_action=suggested_action)
|
||||
|
||||
"""Map an arbitrary Julia exception to an `MCPToolError`."""
|
||||
function classify_exception(e::Exception)
|
||||
e isa MCPToolError && return e
|
||||
|
||||
if e isa OutOfMemoryError
|
||||
return internal_error(
|
||||
"Julia engine ran out of memory: $(sprint(showerror, e))";
|
||||
suggested_action="Retry with the streaming pipeline (msi_plan_preprocessing) or reduce num_bins; close and reopen the dataset to release OS memory.",
|
||||
details=Dict("exception_type" => "OutOfMemoryError"),
|
||||
)
|
||||
elseif e isa InterruptException
|
||||
return MCPToolError("Operation cancelled"; kind="Cancelled",
|
||||
code=ERR_INTERNAL, suggested_action="Re-run the plan if needed.")
|
||||
elseif e isa SystemError || e isa IOError || e isa EOFError
|
||||
return internal_error(
|
||||
"I/O error from the JuliaMSI engine: $(sprint(showerror, e))";
|
||||
suggested_action="Check that the .imzML/.ibd files are readable and the disk is mounted; deleting the .cache file forces a clean parser pass.",
|
||||
details=Dict("exception_type" => string(typeof(e))),
|
||||
)
|
||||
elseif e isa ArgumentError || e isa DomainError || e isa BoundsError
|
||||
return invalid_params(sprint(showerror, e);
|
||||
suggested_action="Validate coordinates, mass ranges and tool arguments before retrying.",
|
||||
details=Dict("exception_type" => string(typeof(e))))
|
||||
end
|
||||
|
||||
return internal_error(sprint(showerror, e);
|
||||
suggested_action="Inspect the server stderr log for the Julia stack trace.",
|
||||
details=Dict("exception_type" => string(typeof(e))))
|
||||
end
|
||||
|
||||
"""Build the structured error payload sent back through the tool result."""
|
||||
function error_payload(e; context::Union{Nothing,Dict{String,Any}}=nothing)
|
||||
err = classify_exception(e)
|
||||
payload = Dict{String,Any}(
|
||||
"error" => Dict{String,Any}(
|
||||
"code" => err.code,
|
||||
"type" => err.kind,
|
||||
"message" => err.message,
|
||||
),
|
||||
)
|
||||
if err.suggested_action !== nothing
|
||||
payload["error"]["suggested_action"] = err.suggested_action
|
||||
end
|
||||
if err.details !== nothing
|
||||
payload["error"]["details"] = err.details
|
||||
end
|
||||
context !== nothing && (payload["context"] = context)
|
||||
return payload
|
||||
end
|
||||
|
||||
"""Convert any exception into a `CallToolResult` with `isError=true`."""
|
||||
function error_result(e; context=nothing)
|
||||
payload = error_payload(e; context=context)
|
||||
return ModelContextProtocol.CallToolResult(
|
||||
content = [Dict{String,Any}("type" => "text", "text" => json_text(payload))],
|
||||
is_error = true,
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
guarded(f)
|
||||
|
||||
Run a tool handler body, converting any exception into a structured error
|
||||
result. The server loop must never die because of a bad argument or a corrupt
|
||||
dataset.
|
||||
"""
|
||||
function guarded(f::Function; context=nothing)
|
||||
try
|
||||
return f()
|
||||
catch e
|
||||
if !(e isa MCPToolError)
|
||||
@error "Tool handler failed" exception=(e, catch_backtrace())
|
||||
end
|
||||
return error_result(e; context=context)
|
||||
end
|
||||
end
|
||||
|
||||
"""Wrap a handler with `guarded`, preserving the one-arg MCP convention."""
|
||||
guarded_handler(f::Function) = params -> guarded(() -> f(params))
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
# src/prompts.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reusable workflow prompts. These guide the model through the plan -> execute
|
||||
# -> poll -> inspect cycle without hard-coding any particular dataset.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
import ModelContextProtocol: user, assistant
|
||||
|
||||
const PROMPT_ANALYZE_REGION = MCPPrompt(
|
||||
name = "analyze_region_of_interest",
|
||||
description = "Guides a reproducible region-of-interest (ROI) analysis: confirm mass, tolerance and mask, then plan, execute and inspect the result.",
|
||||
arguments = [
|
||||
PromptArgument(name = "dataset_path", description = "Absolute path to the .imzML (or .mzML) file.", required = true),
|
||||
PromptArgument(name = "region", description = "Description of the tissue or region of interest.", required = false),
|
||||
PromptArgument(name = "mass_hint", description = "Candidate m/z value or compound of interest (optional).", required = false),
|
||||
],
|
||||
messages = [
|
||||
PromptMessage(role = user, content = TextContent(text = """
|
||||
You are an expert mass spectrometry imaging (MSI) assistant operating the JuliaMSI
|
||||
MCP server. The dataset to analyze is: {dataset_path}.
|
||||
Region of interest: {?region?{region}}
|
||||
Candidate mass: {?mass_hint?{mass_hint}}
|
||||
If any of these fields is empty, ask the user for it before continuing.
|
||||
|
||||
Before running expensive work, collect and confirm:
|
||||
1. Target mass (m/z, in Daltons) and tolerance (Da; convert ppm to Da if needed).
|
||||
2. Whether a mask image (PNG/TIFF/BMP) is available to restrict the ROI.
|
||||
3. Whether the user wants a single mass (msi_get_mz_slice or
|
||||
msi_plan_ion_image) or a panel (msi_plan_multiple_slices).
|
||||
|
||||
Recommended workflow:
|
||||
- msi_dataset_info to check the session; if no dataset is open, use msi_open_dataset.
|
||||
- For a large dataset with analytics not ready, plan msi_plan_analytics and run it
|
||||
in the background first.
|
||||
- Create the plan with msi_plan_ion_image (or msi_plan_multiple_slices).
|
||||
- Execute with msi_execute_runspec and keep the task_id.
|
||||
- Poll msi_get_task_status until the task is terminal, then call msi_get_task_result.
|
||||
- Summarize: m/z, tolerance, dimensions, max/mean intensity, base-peak coordinate,
|
||||
artifact paths (CSV/PGM) and any range warnings.
|
||||
|
||||
Do not invent mass values. If the user has not provided one, propose candidates and
|
||||
ask for confirmation. Interpret structured errors (the suggested_action field) and
|
||||
fix the request before retrying.
|
||||
""")),
|
||||
],
|
||||
)
|
||||
|
||||
const PROMPT_STANDARD_PIPELINE = MCPPrompt(
|
||||
name = "standard_pipeline",
|
||||
description = "Reproducible streaming preprocessing workflow: open, plan, execute, poll and summarize the sparse feature matrix.",
|
||||
arguments = [
|
||||
PromptArgument(name = "dataset_path", description = "Absolute path to the .imzML/.mzML dataset.", required = true),
|
||||
PromptArgument(name = "goal", description = "Biological or analytical goal of the preprocessing run.", required = false),
|
||||
],
|
||||
messages = [
|
||||
PromptMessage(role = user, content = TextContent(text = """
|
||||
Act as an MSI analyst and run a reproducible preprocessing pipeline on:
|
||||
{dataset_path}
|
||||
Declared goal: {?goal?{goal}}
|
||||
If no goal is declared, assume general exploration and confirm that with the user.
|
||||
|
||||
Follow this order and stop if a step fails:
|
||||
1. msi_open_dataset with use_mmap=true (keep precompute_analytics=false).
|
||||
2. msi_dataset_info and record num_spectra, image_dims and m/z range.
|
||||
3. msi_plan_preprocessing with an explicit pipeline, for example:
|
||||
- smoothing: savitzky_golay, window 9, order 2
|
||||
- baseline_correction: snip, iterations 100
|
||||
- normalization: tic
|
||||
- peak_picking: profile, snr_threshold 3.0
|
||||
Use num_bins 2000, min_peaks_per_bin 3 and frequency_threshold 0.05.
|
||||
On very large datasets or low-RAM machines, keep the streaming engine and leave
|
||||
include_matrix=false.
|
||||
4. msi_execute_runspec with the runspec_id and wait_seconds=0.
|
||||
5. Poll msi_get_task_status (at most ~30 times, with a short pause between polls)
|
||||
until completed/failed/cancelled.
|
||||
6. msi_get_task_result: report matrix_shape, nonzeros, density, bin_mz_range,
|
||||
top_bins and the artifact paths (.mtx and bin_centers.csv).
|
||||
7. Finish with msi_close_dataset to release file handles and OS memory.
|
||||
|
||||
The final summary must include the exact parameters, runspec_id, task_id, matrix
|
||||
size and a short interpretation of the most intense bins.
|
||||
""")),
|
||||
],
|
||||
)
|
||||
|
||||
const PROMPT_DIAGNOSE_TASK = MCPPrompt(
|
||||
name = "diagnose_task",
|
||||
description = "Instructs the model to diagnose a failed or slow task using status, structured errors and process memory.",
|
||||
arguments = [
|
||||
PromptArgument(name = "task_id", description = "Identifier of the task to diagnose.", required = true),
|
||||
],
|
||||
messages = [
|
||||
PromptMessage(role = user, content = TextContent(text = """
|
||||
Diagnose task {task_id} on the JuliaMSI MCP server.
|
||||
|
||||
1. Read msi_get_task_status with include_summary=true and, when available, the
|
||||
resource msi://tasks/{task_id}/status.
|
||||
2. If status=failed, inspect error.code, error.type, error.message,
|
||||
error.suggested_action and error.details. Translate the error into a probable cause.
|
||||
3. If status=running for a long time, check progress, duration_seconds and the RSS
|
||||
reported by msi_dataset_info. If RSS is near the machine limit, propose cancelling
|
||||
(msi_cancel_task) and retrying with the streaming pipeline or fewer bins.
|
||||
4. If status=completed, validate the result with msi_get_task_result: check dimensions,
|
||||
density, top_bins and artifacts; flag anomalies (all-zero matrix, 100% density,
|
||||
empty bins).
|
||||
5. Finish with a list of concrete actions and, when appropriate, a corrected plan.
|
||||
|
||||
Common failure categories:
|
||||
- SessionError: no dataset is open -> msi_open_dataset.
|
||||
- InvalidParams: wrong mass/tolerance/mask or a dataset different from the one used
|
||||
for the plan -> replan.
|
||||
- I/O: missing .ibd, permissions, corrupt .cache -> delete .cache and reopen.
|
||||
- OutOfMemoryError: reduce num_bins, use a mask or switch to the streaming pipeline.
|
||||
""")),
|
||||
],
|
||||
)
|
||||
@@ -0,0 +1,111 @@
|
||||
# src/resources.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Read-only MCP resources (msi:// URI scheme).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _dataset_metadata_resource()
|
||||
return session_metadata()
|
||||
end
|
||||
|
||||
function _dataset_stats_resource()
|
||||
meta = session_metadata()
|
||||
if meta["open"] != true
|
||||
return Dict{String,Any}("open" => false, "hint" => meta["hint"])
|
||||
end
|
||||
data = lock(SESSION.lock) do
|
||||
SESSION.data
|
||||
end
|
||||
data === nothing && return Dict{String,Any}("open" => false)
|
||||
if !MSI_src.is_set(data.analytics_ready)
|
||||
return Dict{String,Any}(
|
||||
"open" => true,
|
||||
"analytics_ready" => false,
|
||||
"hint" => "Analytics have not been computed. Call msi_plan_analytics + msi_execute_runspec (recommended) or msi_get_dataset_stats.",
|
||||
)
|
||||
end
|
||||
stats_df = MSI_src.get_spectrum_stats(data)
|
||||
stats_df === nothing && return Dict{String,Any}("open" => true, "analytics_ready" => false)
|
||||
aggregate = Dict{String,Any}()
|
||||
for col in ("TIC", "BPI", "NumPoints")
|
||||
v = Float64.(stats_df[!, col])
|
||||
aggregate[col] = Dict{String,Any}(
|
||||
"min" => compact_float(minimum(v)),
|
||||
"max" => compact_float(maximum(v)),
|
||||
"mean" => compact_float(Statistics.mean(v)),
|
||||
"median" => compact_float(Statistics.median(v)),
|
||||
)
|
||||
end
|
||||
n = min(100, nrow(stats_df))
|
||||
rows = Any[]
|
||||
for i in 1:n
|
||||
push!(rows, Dict{String,Any}(
|
||||
"spectrum_id" => Int(stats_df[i, "SpectrumID"]),
|
||||
"tic" => compact_float(stats_df[i, "TIC"]),
|
||||
"bpi" => compact_float(stats_df[i, "BPI"]),
|
||||
"base_peak_mz" => compact_float(stats_df[i, "BasePeakMZ"]),
|
||||
"num_points" => Int(stats_df[i, "NumPoints"]),
|
||||
"min_mz" => compact_float(stats_df[i, "MinMZ"]),
|
||||
"max_mz" => compact_float(stats_df[i, "MaxMZ"]),
|
||||
"mode" => string(stats_df[i, "Mode"]),
|
||||
))
|
||||
end
|
||||
min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0)
|
||||
max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0)
|
||||
return Dict{String,Any}(
|
||||
"open" => true,
|
||||
"dataset_id" => meta["dataset_id"],
|
||||
"analytics_ready" => true,
|
||||
"num_spectra" => nrow(stats_df),
|
||||
"mz_range" => Any[compact_float(min_mz), compact_float(max_mz)],
|
||||
"aggregate" => aggregate,
|
||||
"rows_returned" => length(rows),
|
||||
"rows" => rows,
|
||||
"hint" => "Showing the first 100 spectra. Use msi_get_dataset_stats for more rows or the CSV artifact of msi_plan_analytics.",
|
||||
)
|
||||
end
|
||||
|
||||
const DATASET_METADATA_RESOURCE = MCPResource(
|
||||
uri = "msi://dataset/metadata",
|
||||
name = "Dataset metadata",
|
||||
description = "State of the active dataset: path, dimensions, spectra count, m/z range, mmap/cache status and process memory.",
|
||||
mime_type = JSON_MIME,
|
||||
data_provider = () -> _dataset_metadata_resource(),
|
||||
)
|
||||
|
||||
const DATASET_STATS_RESOURCE = MCPResource(
|
||||
uri = "msi://dataset/stats",
|
||||
name = "Dataset statistics",
|
||||
description = "Aggregated per-spectrum statistics (TIC, BPI, points, m/z bounds) plus the first 100 rows. Does not trigger the analytics scan.",
|
||||
mime_type = JSON_MIME,
|
||||
data_provider = () -> _dataset_stats_resource(),
|
||||
)
|
||||
|
||||
const TASK_STATUS_TEMPLATE = ResourceTemplate(
|
||||
name = "task_status",
|
||||
uri_template = "msi://tasks/{task_id}/status",
|
||||
description = "Status, progress and timestamps of a background task.",
|
||||
mime_type = JSON_MIME,
|
||||
data_provider = (uri, vars) -> begin
|
||||
id = String(vars["task_id"])
|
||||
try
|
||||
task_status_payload(get_task(id))
|
||||
catch e
|
||||
error_payload(e; context=Dict{String,Any}("uri" => string(uri)))
|
||||
end
|
||||
end,
|
||||
)
|
||||
|
||||
const TASK_RESULT_TEMPLATE = ResourceTemplate(
|
||||
name = "task_result",
|
||||
uri_template = "msi://tasks/{task_id}/result",
|
||||
description = "Full structured result of a completed task (statistics, preview, artifact paths).",
|
||||
mime_type = JSON_MIME,
|
||||
data_provider = (uri, vars) -> begin
|
||||
id = String(vars["task_id"])
|
||||
try
|
||||
task_result_payload(get_task(id))
|
||||
catch e
|
||||
error_payload(e; context=Dict{String,Any}("uri" => string(uri)))
|
||||
end
|
||||
end,
|
||||
)
|
||||
+373
@@ -0,0 +1,373 @@
|
||||
# src/runspec.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Planning layer.
|
||||
#
|
||||
# A `RunSpec` is an immutable, content-addressed description of a computation.
|
||||
# Planning tools validate arguments and mint a RunSpec; they never execute the
|
||||
# expensive engine work. `msi_execute_runspec` is the only entry point to the
|
||||
# execution layer. This keeps plans auditable and reproducible (same inputs ->
|
||||
# same hash), which matters in scientific workflows.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
struct RunSpec
|
||||
id::String
|
||||
kind::Symbol
|
||||
dataset_id::String
|
||||
params::Dict{String,Any}
|
||||
created_at::Float64
|
||||
summary::String
|
||||
end
|
||||
|
||||
const RUNSPEC_LOCK = ReentrantLock()
|
||||
const RUNSPECS = Dict{String,RunSpec}()
|
||||
const RUNSPEC_ORDER = String[]
|
||||
const MAX_RUNSPECS = 256
|
||||
|
||||
const RUNSPEC_KINDS = (:ion_image, :multiple_slices, :streaming_pipeline, :analytics)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parameter helpers (JSON3 objects behave like dictionaries)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_pget(params, key, default=nothing) = haskey(params, key) ? params[key] : default
|
||||
|
||||
function opt_string(params, key; default=nothing, allow_empty=false)
|
||||
v = _pget(params, key, default)
|
||||
v === nothing && return nothing
|
||||
s = string(v)
|
||||
if !allow_empty && isempty(strip(s))
|
||||
return default === nothing ? nothing : String(default)
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
function opt_float(params, key; default=nothing, min=-Inf, max=Inf)
|
||||
v = _pget(params, key, default)
|
||||
v === nothing && return nothing
|
||||
x = try
|
||||
Float64(v)
|
||||
catch
|
||||
throw(invalid_params("Parameter `$(key)` must be a number, got $(repr(v))."))
|
||||
end
|
||||
isfinite(x) || throw(invalid_params("Parameter `$(key)` must be finite."))
|
||||
(x < min || x > max) && throw(invalid_params(
|
||||
"Parameter `$(key)` = $(x) is outside the allowed range [$(min), $(max)]."))
|
||||
return x
|
||||
end
|
||||
|
||||
function opt_int(params, key; default=nothing, min=typemin(Int), max=typemax(Int))
|
||||
v = _pget(params, key, default)
|
||||
v === nothing && return nothing
|
||||
x = try
|
||||
Int(v)
|
||||
catch
|
||||
throw(invalid_params("Parameter `$(key)` must be an integer, got $(repr(v))."))
|
||||
end
|
||||
(x < min || x > max) && throw(invalid_params(
|
||||
"Parameter `$(key)` = $(x) is outside the allowed range [$(min), $(max)]."))
|
||||
return x
|
||||
end
|
||||
|
||||
function opt_bool(params, key; default=false)
|
||||
v = _pget(params, key, default)
|
||||
v isa Bool && return v
|
||||
v isa Integer && return v != 0
|
||||
v isa AbstractString && return lowercase(v) in ("true", "1", "yes", "on")
|
||||
return false
|
||||
end
|
||||
|
||||
function opt_float_vector(params, key; default=Float64[], min_len=0, max_len=10_000)
|
||||
v = _pget(params, key, nothing)
|
||||
v === nothing && return Float64.(default)
|
||||
v isa AbstractString && throw(invalid_params("Parameter `$(key)` must be an array of numbers."))
|
||||
values = try
|
||||
Float64[Float64(x) for x in collect(v)]
|
||||
catch
|
||||
throw(invalid_params("Parameter `$(key)` must be an array of numbers."))
|
||||
end
|
||||
all(isfinite, values) || throw(invalid_params("Parameter `$(key)` must contain only finite numbers."))
|
||||
(length(values) < min_len || length(values) > max_len) && throw(invalid_params(
|
||||
"Parameter `$(key)` must contain between $(min_len) and $(max_len) values (got $(length(values)))."))
|
||||
return values
|
||||
end
|
||||
|
||||
function validate_mask_path(params, data)
|
||||
mask = opt_string(params, "mask_path"; default=nothing)
|
||||
mask === nothing && return nothing
|
||||
path = abspath(expanduser(mask))
|
||||
isfile(path) || throw(invalid_params(
|
||||
"Mask file not found: $(path)";
|
||||
suggested_action="Pass the absolute path to a binary mask image (PNG/TIFF/BMP) with the same orientation as the image."))
|
||||
data.coordinate_map === nothing && throw(invalid_params(
|
||||
"Mask-based ROI filtering requires an imaging dataset with a coordinate map (imzML)."))
|
||||
return path
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Registry
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _register_runspec!(rs::RunSpec)
|
||||
lock(RUNSPEC_LOCK) do
|
||||
RUNSPECS[rs.id] = rs
|
||||
push!(RUNSPEC_ORDER, rs.id)
|
||||
while length(RUNSPEC_ORDER) > MAX_RUNSPECS
|
||||
old = popfirst!(RUNSPEC_ORDER)
|
||||
pop!(RUNSPECS, old, nothing)
|
||||
end
|
||||
end
|
||||
return rs
|
||||
end
|
||||
|
||||
function get_runspec(id::AbstractString)
|
||||
lock(RUNSPEC_LOCK) do
|
||||
rs = get(RUNSPECS, String(id), nothing)
|
||||
rs === nothing && throw(invalid_params(
|
||||
"Unknown runspec_id: $(id)";
|
||||
suggested_action="Create a plan with msi_plan_ion_image / msi_plan_multiple_slices / msi_plan_preprocessing first. Plans expire after 256 newer plans."))
|
||||
return rs
|
||||
end
|
||||
end
|
||||
|
||||
function list_runspecs(; limit::Integer=20)
|
||||
lock(RUNSPEC_LOCK) do
|
||||
ids = reverse(RUNSPEC_ORDER)
|
||||
take = ids[1:min(Int(limit), length(ids))]
|
||||
return [RUNSPECS[i] for i in take if haskey(RUNSPECS, i)]
|
||||
end
|
||||
end
|
||||
|
||||
function create_runspec(kind::Symbol, params::Dict{String,Any}, summary::AbstractString)
|
||||
kind in RUNSPEC_KINDS || throw(internal_error("Unimplemented RunSpec kind: $(kind)"))
|
||||
dataset_id = active_dataset_id()
|
||||
dataset_id === nothing && throw(session_error(
|
||||
"No dataset is open."; suggested_action="Call msi_open_dataset first."))
|
||||
material = Dict{String,Any}(
|
||||
"version" => 1,
|
||||
"kind" => string(kind),
|
||||
"dataset_id" => dataset_id,
|
||||
"params" => params,
|
||||
)
|
||||
id = short_hash(material, 32)
|
||||
rs = RunSpec(id, kind, dataset_id, params, time(), String(summary))
|
||||
return _register_runspec!(rs)
|
||||
end
|
||||
|
||||
"""Human/LLM-facing description of a plan (without executing it)."""
|
||||
function runspec_payload(rs::RunSpec; include_params::Bool=true)
|
||||
payload = Dict{String,Any}(
|
||||
"runspec_id" => rs.id,
|
||||
"kind" => string(rs.kind),
|
||||
"dataset_id" => rs.dataset_id,
|
||||
"summary" => rs.summary,
|
||||
"created_at" => Dates.format(Dates.unix2datetime(rs.created_at), "yyyy-mm-ddTHH:MM:SS"),
|
||||
"next_step" => "Call msi_execute_runspec with this runspec_id, then poll msi_get_task_status.",
|
||||
)
|
||||
include_params && (payload["params"] = rs.params)
|
||||
return payload
|
||||
end
|
||||
|
||||
"""Ensure a plan is executed against the dataset it was planned for."""
|
||||
function check_runspec_dataset(rs::RunSpec)
|
||||
current = active_dataset_id()
|
||||
current === nothing && throw(session_error(
|
||||
"No dataset is open."; suggested_action="Reopen the dataset and replan."))
|
||||
if current != rs.dataset_id
|
||||
throw(invalid_params(
|
||||
"This RunSpec was planned for dataset $(rs.dataset_id), but the active dataset is $(current).";
|
||||
suggested_action="Recreate the plan against the currently open dataset.",
|
||||
details=Dict("runspec_dataset" => rs.dataset_id, "active_dataset" => current)))
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Validators / plan builders
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
"""Ion images only make sense for imaging datasets with a spatial coordinate map."""
|
||||
function require_imaging(data)
|
||||
if data.coordinate_map === nothing || data.image_dims[1] <= 0 || data.image_dims[2] <= 0
|
||||
throw(invalid_params(
|
||||
"Ion-image extraction requires imaging data (an .imzML file with a coordinate map); this dataset has no spatial dimensions (.mzML or non-imaging input).";
|
||||
suggested_action="Use msi_get_spectrum_by_index and msi_get_dataset_stats for mzML/profile files, or open an .imzML dataset for spatial analysis.",
|
||||
details=Dict("image_dims" => Any[data.image_dims[1], data.image_dims[2]],
|
||||
"coordinate_map" => data.coordinate_map !== nothing)))
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
function _ion_image_params(params, data; multiple::Bool=false)
|
||||
require_imaging(data)
|
||||
mask_path = validate_mask_path(params, data)
|
||||
tolerance = opt_float(params, "tolerance"; default=0.1, min=eps(Float64), max=1000.0)
|
||||
|
||||
out = Dict{String,Any}(
|
||||
"tolerance" => tolerance,
|
||||
"mask_path" => mask_path,
|
||||
"include_matrix" => opt_bool(params, "include_matrix"; default=false),
|
||||
"preview_max_dim" => opt_int(params, "preview_max_dim"; default=96, min=16, max=256),
|
||||
)
|
||||
|
||||
if multiple
|
||||
masses = opt_float_vector(params, "masses"; min_len=1, max_len=5000)
|
||||
masses = unique(masses)
|
||||
out["masses"] = masses
|
||||
out["output_name"] = safe_filename(
|
||||
something(opt_string(params, "output_name"; default=nothing), "multiple_slices"))
|
||||
out["_verify"] = _mz_overlap_note(masses, tolerance)
|
||||
else
|
||||
mass = opt_float(params, "mass"; default=nothing, min=eps(Float64), max=1.0e7)
|
||||
mass === nothing && throw(invalid_params(
|
||||
"Missing required parameter `mass` (Daltons).";
|
||||
suggested_action="Example: {\"mass\": 756.55, \"tolerance\": 0.1}"))
|
||||
out["mass"] = mass
|
||||
out["output_name"] = safe_filename(
|
||||
something(opt_string(params, "output_name"; default=nothing),
|
||||
"ion_mz_" * string(round(mass, digits=4))))
|
||||
out["_verify"] = _mz_overlap_note([mass], tolerance)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
"""Warn (not fail) when a target lies outside the computed global m/z range."""
|
||||
function _mz_overlap_note(masses::Vector{Float64}, tolerance::Float64)
|
||||
note = Dict{String,Any}("checked" => false)
|
||||
data = lock(SESSION.lock) do
|
||||
SESSION.data
|
||||
end
|
||||
data === nothing && return note
|
||||
MSI_src.is_set(data.analytics_ready) || begin
|
||||
note["reason"] = "analytics not computed yet; range check deferred to execution"
|
||||
return note
|
||||
end
|
||||
min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0)
|
||||
max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0)
|
||||
lo, hi = min_mz - tolerance, max_mz + tolerance
|
||||
outside = [m for m in masses if m < lo || m > hi]
|
||||
note["checked"] = true
|
||||
note["global_mz_range"] = Any[compact_float(min_mz), compact_float(max_mz)]
|
||||
isempty(outside) || (note["outside_range"] = outside)
|
||||
return note
|
||||
end
|
||||
|
||||
const ALLOWED_STEP_NAMES = Set([
|
||||
"smoothing", "baseline_correction", "normalization", "stabilization",
|
||||
"intensity_transformation", "peak_picking", "calibration",
|
||||
])
|
||||
|
||||
function _parse_steps(params)
|
||||
raw = _pget(params, "steps", nothing)
|
||||
if raw !== nothing
|
||||
raw isa AbstractString && throw(invalid_params("`steps` must be an array of objects."))
|
||||
steps = Dict{String,Any}[]
|
||||
for (i, item) in enumerate(collect(raw))
|
||||
item isa AbstractDict || throw(invalid_params(
|
||||
"steps[$(i)] must be an object like {\"name\": \"smoothing\", \"params\": {...}}."))
|
||||
name = String(_pget(item, "name", ""))
|
||||
name in ALLOWED_STEP_NAMES || throw(invalid_params(
|
||||
"Unknown preprocessing step '$(name)' at steps[$(i)].";
|
||||
suggested_action="Allowed steps: " * join(sort(collect(ALLOWED_STEP_NAMES)), ", ")))
|
||||
step_params = _pget(item, "params", Dict{String,Any}())
|
||||
steps = push!(steps, Dict{String,Any}("name" => name,
|
||||
"params" => Dict{String,Any}(jsonable(step_params))))
|
||||
end
|
||||
isempty(steps) || return steps
|
||||
end
|
||||
|
||||
# Convenience shorthands mirroring the compendium / app.jl names.
|
||||
steps = Dict{String,Any}[]
|
||||
window = opt_int(params, "smoothing_window"; default=0, min=0, max=1001)
|
||||
if window > 0
|
||||
push!(steps, Dict{String,Any}("name" => "smoothing",
|
||||
"params" => Dict{String,Any}("method" => "savitzky_golay", "window" => window, "order" => 2)))
|
||||
end
|
||||
baseline_it = opt_int(params, "baseline_iterations"; default=0, min=0, max=10_000)
|
||||
if baseline_it > 0
|
||||
push!(steps, Dict{String,Any}("name" => "baseline_correction",
|
||||
"params" => Dict{String,Any}("method" => "snip", "iterations" => baseline_it)))
|
||||
end
|
||||
norm = lowercase(String(_pget(params, "normalization", "none")))
|
||||
if norm in ("tic", "rms", "median")
|
||||
push!(steps, Dict{String,Any}("name" => "normalization",
|
||||
"params" => Dict{String,Any}("method" => norm)))
|
||||
end
|
||||
if opt_bool(params, "peak_picking"; default=true)
|
||||
push!(steps, Dict{String,Any}("name" => "peak_picking",
|
||||
"params" => Dict{String,Any}(
|
||||
"method" => lowercase(String(_pget(params, "peak_method", "profile"))),
|
||||
"snr_threshold" => Float64(opt_float(params, "snr_threshold"; default=3.0, min=0.0, max=1000.0)),
|
||||
)))
|
||||
end
|
||||
isempty(steps) && throw(invalid_params(
|
||||
"The pipeline contains no steps.";
|
||||
suggested_action="Provide `steps` or at least one of smoothing_window, baseline_iterations, normalization, peak_picking."))
|
||||
return steps
|
||||
end
|
||||
|
||||
function _preprocessing_params(params, data)
|
||||
steps = _parse_steps(params)
|
||||
return Dict{String,Any}(
|
||||
"steps" => steps,
|
||||
"num_bins" => opt_int(params, "num_bins"; default=2000, min=1, max=100_000),
|
||||
"min_peaks_per_bin" => opt_int(params, "min_peaks_per_bin"; default=3, min=1, max=1_000_000),
|
||||
"frequency_threshold" => opt_float(params, "frequency_threshold"; default=0.0, min=0.0, max=1.0),
|
||||
"reference_peaks" => opt_float_vector(params, "reference_peaks"; default=Float64[],
|
||||
min_len=0, max_len=100_000),
|
||||
"mask_path" => validate_mask_path(params, data),
|
||||
"include_matrix" => opt_bool(params, "include_matrix"; default=false),
|
||||
"output_name" => safe_filename(
|
||||
something(opt_string(params, "output_name"; default=nothing), "streaming_pipeline")),
|
||||
)
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Planner entry points (shared by MCP tools and tests)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function plan_ion_image(params)
|
||||
data = require_data()
|
||||
p = _ion_image_params(params, data; multiple=false)
|
||||
note = pop!(p, "_verify")
|
||||
rs = create_runspec(:ion_image, p,
|
||||
"Ion image at m/z $(round(p["mass"], digits=5)) ± $(p["tolerance"]) Da")
|
||||
payload = runspec_payload(rs)
|
||||
payload["validation"] = note
|
||||
payload["estimated_cost"] = "one full pass over the spectra (I/O bound); analytics may run on first use"
|
||||
return payload
|
||||
end
|
||||
|
||||
function plan_multiple_slices(params)
|
||||
data = require_data()
|
||||
p = _ion_image_params(params, data; multiple=true)
|
||||
note = pop!(p, "_verify")
|
||||
rs = create_runspec(:multiple_slices, p,
|
||||
"$(length(p["masses"])) ion images in a single I/O pass (± $(p["tolerance"]) Da)")
|
||||
payload = runspec_payload(rs)
|
||||
payload["validation"] = note
|
||||
payload["estimated_cost"] = "one full pass over the spectra (hierarchy inversion; independent of the number of masses)"
|
||||
return payload
|
||||
end
|
||||
|
||||
function plan_preprocessing(params)
|
||||
data = require_data()
|
||||
p = _preprocessing_params(params, data)
|
||||
rs = create_runspec(:streaming_pipeline, p,
|
||||
"Streaming preprocessing ($(length(p["steps"])) steps) -> sparse feature matrix ($(p["num_bins"]) bins)")
|
||||
payload = runspec_payload(rs)
|
||||
payload["estimated_cost"] = "one streaming pass; RAM bounded by threads × largest spectrum"
|
||||
return payload
|
||||
end
|
||||
|
||||
function plan_analytics(params)
|
||||
data = require_data()
|
||||
p = Dict{String,Any}(
|
||||
"include_rows" => opt_int(params, "include_rows"; default=20, min=0, max=5000),
|
||||
"output_name" => safe_filename(
|
||||
something(opt_string(params, "output_name"; default=nothing), "analytics")),
|
||||
)
|
||||
rs = create_runspec(:analytics, p, "Per-spectrum analytics scan (TIC/BPI/min-max m/z + Bloom filters)")
|
||||
payload = runspec_payload(rs)
|
||||
payload["estimated_cost"] = "one full pass over the spectra; required before ion-image extraction"
|
||||
return payload
|
||||
end
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
# src/server.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# MCP server assembly and entry points (stdio + Streamable HTTP).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const SERVER_NAME = "juliamsi"
|
||||
const SERVER_VERSION = "0.1.0"
|
||||
|
||||
const SERVER_DESCRIPTION = """
|
||||
High-performance Mass Spectrometry Imaging engine (JuliaMSI) exposed through the
|
||||
Model Context Protocol. Keeps an .imzML/.mzML dataset open between calls, plans
|
||||
expensive work as immutable RunSpecs, executes it in background Julia tasks with
|
||||
memory-mapped I/O, and returns compact statistics plus on-disk artifacts.
|
||||
"""
|
||||
|
||||
const ALL_TOOLS = MCPTool[
|
||||
OPEN_DATASET_TOOL,
|
||||
CLOSE_DATASET_TOOL,
|
||||
DATASET_INFO_TOOL,
|
||||
DATASET_STATS_TOOL,
|
||||
GET_SPECTRUM_TOOL,
|
||||
GET_SPECTRUM_BY_INDEX_TOOL,
|
||||
GET_MZ_SLICE_TOOL,
|
||||
GET_MULTIPLE_SLICES_TOOL,
|
||||
PLAN_ION_IMAGE_TOOL,
|
||||
PLAN_MULTIPLE_SLICES_TOOL,
|
||||
PLAN_PREPROCESSING_TOOL,
|
||||
PLAN_STREAMING_PIPELINE_TOOL,
|
||||
PLAN_ANALYTICS_TOOL,
|
||||
EXECUTE_RUNSPEC_TOOL,
|
||||
LIST_PLANS_TOOL,
|
||||
TASK_STATUS_TOOL,
|
||||
TASK_RESULT_TOOL,
|
||||
CANCEL_TASK_TOOL,
|
||||
LIST_TASKS_TOOL,
|
||||
CLEAN_ARTIFACTS_TOOL,
|
||||
]
|
||||
|
||||
const ALL_RESOURCES = MCPResource[
|
||||
DATASET_METADATA_RESOURCE,
|
||||
DATASET_STATS_RESOURCE,
|
||||
]
|
||||
|
||||
const ALL_RESOURCE_TEMPLATES = ResourceTemplate[
|
||||
TASK_STATUS_TEMPLATE,
|
||||
TASK_RESULT_TEMPLATE,
|
||||
]
|
||||
|
||||
const ALL_PROMPTS = MCPPrompt[
|
||||
PROMPT_ANALYZE_REGION,
|
||||
PROMPT_STANDARD_PIPELINE,
|
||||
PROMPT_DIAGNOSE_TASK,
|
||||
]
|
||||
|
||||
"""Build (but do not start) the JuliaMSI MCP server."""
|
||||
function build_server()
|
||||
return mcp_server(
|
||||
name = SERVER_NAME,
|
||||
version = SERVER_VERSION,
|
||||
title = "JuliaMSI MCP",
|
||||
description = SERVER_DESCRIPTION,
|
||||
tools = ALL_TOOLS,
|
||||
resources = ALL_RESOURCES,
|
||||
resource_templates = ALL_RESOURCE_TEMPLATES,
|
||||
prompts = ALL_PROMPTS,
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
startup_maintenance()
|
||||
|
||||
Run one-shot housekeeping before the server loop: apply the artifact retention
|
||||
policy (age and size budgets from the environment). Errors are non-fatal.
|
||||
"""
|
||||
function startup_maintenance()
|
||||
max_age_days, max_total_bytes = artifact_retention_config()
|
||||
if max_age_days > 0 || max_total_bytes > 0
|
||||
try
|
||||
summary = prune_artifacts!(max_age_days=max_age_days, max_total_bytes=max_total_bytes)
|
||||
if summary["removed"] > 0
|
||||
println(stderr, "[juliamsi] pruned $(summary["removed"]) artifact dir(s), freed $(summary["freed_bytes"]) bytes")
|
||||
end
|
||||
catch e
|
||||
@warn "Artifact pruning at startup failed" exception=(e, catch_backtrace())
|
||||
end
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Optional shared-token authentication for the HTTP transport.
|
||||
#
|
||||
# This is a single shared bearer token (not OAuth, not a substitute for TLS).
|
||||
# Set JULIA_MSI_MCP_TOKEN (or pass `--token`) to require
|
||||
# `Authorization: Bearer <token>` on every HTTP request.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
struct SharedTokenValidator <: ModelContextProtocol.TokenValidator
|
||||
token::String
|
||||
end
|
||||
|
||||
function _secure_equals(a::AbstractString, b::AbstractString)
|
||||
ba, bb = codeunits(a), codeunits(b)
|
||||
length(ba) == length(bb) || return false
|
||||
diff = 0x00
|
||||
@inbounds for i in eachindex(ba)
|
||||
diff |= ba[i] ⊻ bb[i]
|
||||
end
|
||||
return diff == 0x00
|
||||
end
|
||||
|
||||
function ModelContextProtocol.validate_token(validator::SharedTokenValidator,
|
||||
token::AbstractString,
|
||||
::ModelContextProtocol.OAuthConfig)
|
||||
if _secure_equals(validator.token, token)
|
||||
return ModelContextProtocol.AuthResult(ModelContextProtocol.AuthenticatedUser(
|
||||
subject="shared-token", provider="static"))
|
||||
end
|
||||
return ModelContextProtocol.AuthResult("Invalid token", :invalid_token)
|
||||
end
|
||||
|
||||
function _http_auth(token::Union{Nothing,AbstractString})
|
||||
(token === nothing || isempty(strip(String(token)))) && return nothing
|
||||
config = ModelContextProtocol.OAuthConfig(issuer="juliamsi", audience="juliamsi")
|
||||
return ModelContextProtocol.AuthMiddleware(config=config,
|
||||
validator=SharedTokenValidator(String(token)))
|
||||
end
|
||||
|
||||
"""
|
||||
install_output_guard()
|
||||
|
||||
Send all further writes to the process-global `stdout` to `stderr`, and return
|
||||
the original stdout handle. The JuliaMSI engine (and some Julia packages) print
|
||||
debug/progress lines with `println`; on the MCP stdio transport those bytes would
|
||||
corrupt the JSON-RPC framing. The transport keeps writing to the saved handle.
|
||||
"""
|
||||
function install_output_guard()
|
||||
real_stdout = stdout
|
||||
if get(ENV, "JULIA_MSI_MCP_KEEP_STDOUT", "0") != "1"
|
||||
redirect_stdout(stderr)
|
||||
end
|
||||
return real_stdout
|
||||
end
|
||||
|
||||
"""
|
||||
run_stdio(; server=build_server())
|
||||
|
||||
Run the server over stdio (Claude Desktop, VS Code, any local MCP client).
|
||||
Blocks until stdin is closed.
|
||||
"""
|
||||
function run_stdio(; server=build_server())
|
||||
real_stdout = install_output_guard()
|
||||
transport = StdioTransport(input=stdin, output=real_stdout)
|
||||
startup_maintenance()
|
||||
println(stderr, "[juliamsi] starting MCP server over stdio (Julia $(VERSION), $(Base.Threads.nthreads()) threads)")
|
||||
try
|
||||
start!(server; transport=transport)
|
||||
finally
|
||||
try
|
||||
close_dataset()
|
||||
catch e
|
||||
@warn "Cleanup on shutdown failed" exception=(e, catch_backtrace())
|
||||
end
|
||||
println(stderr, "[juliamsi] server stopped")
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
"""
|
||||
run_http(; host="127.0.0.1", port=3000, token=nothing, server=build_server())
|
||||
|
||||
Run the server over the MCP Streamable HTTP transport. When `token` (or
|
||||
`JULIA_MSI_MCP_TOKEN`) is set, every request must send `Authorization: Bearer
|
||||
<token>`. Put a TLS reverse proxy in front for anything beyond localhost.
|
||||
"""
|
||||
function run_http(; host::AbstractString="127.0.0.1", port::Integer=3000,
|
||||
token::Union{Nothing,AbstractString}=nothing, server=build_server())
|
||||
token = something(token, get(ENV, "JULIA_MSI_MCP_TOKEN", nothing))
|
||||
auth = _http_auth(token)
|
||||
transport = HttpTransport(host=String(host), port=Int(port), auth=auth)
|
||||
startup_maintenance()
|
||||
println(stderr, "[juliamsi] starting MCP Streamable HTTP server on http://$(host):$(port)",
|
||||
auth === nothing ? "" : " (shared-token auth enabled)")
|
||||
connect(transport)
|
||||
try
|
||||
start!(server; transport=transport)
|
||||
finally
|
||||
try
|
||||
close_dataset()
|
||||
catch e
|
||||
@warn "Cleanup on shutdown failed" exception=(e, catch_backtrace())
|
||||
end
|
||||
println(stderr, "[juliamsi] server stopped")
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
# src/session.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Persistent JuliaMSI session.
|
||||
#
|
||||
# The whole point of running the MCP server inside a Julia process is to keep
|
||||
# the (potentially very large) MSIData object alive between tool calls. Opening
|
||||
# an imzML file costs seconds; querying a spectrum afterwards costs
|
||||
# microseconds. This file owns that lifecycle.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
"""
|
||||
SessionState
|
||||
|
||||
Mutable, process-global MCP session. Only one dataset is open at a time (the
|
||||
JuliaMSI engine is built around a single `MSIData`); call `open_dataset` again
|
||||
to switch datasets, which closes and cleans the previous one.
|
||||
"""
|
||||
mutable struct SessionState
|
||||
data::Union{Nothing,MSI_src.MSIData}
|
||||
path::Union{Nothing,String}
|
||||
dataset_id::Union{Nothing,String}
|
||||
opened_at::Union{Nothing,Float64}
|
||||
last_access::Float64
|
||||
cache_size::Int
|
||||
use_mmap::Bool
|
||||
xml_bytes::Int64
|
||||
ibd_bytes::Int64
|
||||
lock::ReentrantLock
|
||||
end
|
||||
|
||||
SessionState() = SessionState(nothing, nothing, nothing, nothing, 0.0, 300,
|
||||
true, 0, 0, ReentrantLock())
|
||||
|
||||
const SESSION = SessionState()
|
||||
const CLEANUP_LOCK = ReentrantLock()
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OS-level memory release (compendium A.12)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
"""
|
||||
release_os_memory!(; full::Bool=true)
|
||||
|
||||
Ask Julia's GC to collect and, on glibc/Linux, ask `malloc_trim(0)` to return
|
||||
free arena pages to the kernel. Without `malloc_trim`, RSS stays inflated after
|
||||
closing a multi-gigabyte dataset even though Julia has freed the objects.
|
||||
|
||||
Safe to call at any time; failures (musl, non-glibc, Windows, macOS) are
|
||||
silently ignored.
|
||||
"""
|
||||
function release_os_memory!(; full::Bool=true)
|
||||
lock(CLEANUP_LOCK) do
|
||||
try
|
||||
GC.gc(full)
|
||||
catch
|
||||
end
|
||||
if Sys.islinux()
|
||||
try
|
||||
ccall(:malloc_trim, Cint, (Cint,), 0)
|
||||
catch
|
||||
# musl libc (Alpine) has no malloc_trim; nothing to do.
|
||||
end
|
||||
end
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dataset identity
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _file_signature(path::String)
|
||||
isfile(path) || return (0, 0.0)
|
||||
st = stat(path)
|
||||
return (Int64(st.size), Float64(st.mtime))
|
||||
end
|
||||
|
||||
"""
|
||||
dataset_id_for(path)
|
||||
|
||||
Content-ish identity of a dataset: path, XML size/mtime and IBD size/mtime.
|
||||
Plans are bound to this id so a RunSpec cannot silently run against a different
|
||||
file after the user opens another dataset.
|
||||
"""
|
||||
function dataset_id_for(path::String)
|
||||
xml_size, xml_mtime = _file_signature(path)
|
||||
ibd_path = replace(path, r"\.(imzML|mzML)"i => ".ibd")
|
||||
ibd_size, ibd_mtime = _file_signature(ibd_path)
|
||||
material = string(path, "|", xml_size, "|", xml_mtime, "|", ibd_size, "|", ibd_mtime)
|
||||
return short_hash(material, 16)
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Open / close
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
"""Validate the file and return `(absolute_path, extension, ibd_path_or_nothing)`."""
|
||||
function _validate_dataset_path(file_path::AbstractString)
|
||||
isempty(strip(String(file_path))) && throw(invalid_params("`file_path` is empty."))
|
||||
path = abspath(expanduser(String(file_path)))
|
||||
isfile(path) || throw(invalid_params(
|
||||
"Dataset file not found: $(path)";
|
||||
suggested_action="Pass an absolute path to an existing .imzML or .mzML file.",
|
||||
details=Dict("path" => path),
|
||||
))
|
||||
ext = lowercase(splitext(path)[2])
|
||||
ext in (".imzml", ".mzml") || throw(invalid_params(
|
||||
"Unsupported dataset extension '$(ext)' for $(path). Supported: .imzML, .mzML.";
|
||||
suggested_action="Convert the file to .imzML (with its .ibd pair) or .mzML.",
|
||||
))
|
||||
ibd = nothing
|
||||
if ext == ".imzml"
|
||||
ibd = replace(path, r"\.imzML"i => ".ibd")
|
||||
isfile(ibd) || throw(invalid_params(
|
||||
"The .ibd binary file paired with $(path) was not found: $(ibd)";
|
||||
suggested_action="Keep the .imzML and .ibd files together with the same basename.",
|
||||
details=Dict("expected_ibd" => ibd),
|
||||
))
|
||||
end
|
||||
return path, ext, ibd
|
||||
end
|
||||
|
||||
"""
|
||||
open_dataset(file_path; cache_size=300, use_mmap=true, precompute_analytics=false)
|
||||
|
||||
Open (or switch) the active dataset and return its metadata summary.
|
||||
"""
|
||||
function open_dataset(file_path::AbstractString;
|
||||
cache_size::Integer=300,
|
||||
use_mmap::Bool=true,
|
||||
precompute_analytics::Bool=false)
|
||||
path, ext, ibd = _validate_dataset_path(file_path)
|
||||
cache_size = clamp(Int(cache_size), 0, 100_000)
|
||||
|
||||
return lock(SESSION.lock) do
|
||||
t0 = time_ns()
|
||||
if SESSION.data !== nothing
|
||||
_close_locked!()
|
||||
end
|
||||
|
||||
data = if ext == ".imzml"
|
||||
MSI_src.load_imzml_lazy(path; cache_size=cache_size, use_mmap=use_mmap)
|
||||
else
|
||||
MSI_src.load_mzml_lazy(path; cache_size=cache_size)
|
||||
end
|
||||
|
||||
if precompute_analytics
|
||||
MSI_src.precompute_analytics(data)
|
||||
end
|
||||
|
||||
xml_size, _ = _file_signature(path)
|
||||
ibd_size, _ = ibd === nothing ? (0, 0.0) : _file_signature(ibd)
|
||||
|
||||
SESSION.data = data
|
||||
SESSION.path = path
|
||||
SESSION.dataset_id = dataset_id_for(path)
|
||||
SESSION.opened_at = time()
|
||||
SESSION.last_access = time()
|
||||
SESSION.cache_size = cache_size
|
||||
SESSION.use_mmap = use_mmap
|
||||
SESSION.xml_bytes = xml_size
|
||||
SESSION.ibd_bytes = ibd_size
|
||||
|
||||
meta = _metadata_locked(data)
|
||||
meta["open_seconds"] = compact_float((time_ns() - t0) / 1e9)
|
||||
meta["cache_file"] = isfile(path * ".cache") ? path * ".cache" : nothing
|
||||
return meta
|
||||
end
|
||||
end
|
||||
|
||||
"""Close the active dataset without acquiring the lock (internal)."""
|
||||
function _close_locked!()
|
||||
if SESSION.data !== nothing
|
||||
try
|
||||
Base.close(SESSION.data)
|
||||
catch e
|
||||
@warn "Error while closing MSIData" exception=(e, catch_backtrace())
|
||||
end
|
||||
end
|
||||
SESSION.data = nothing
|
||||
SESSION.path = nothing
|
||||
SESSION.dataset_id = nothing
|
||||
SESSION.opened_at = nothing
|
||||
SESSION.last_access = time()
|
||||
SESSION.xml_bytes = 0
|
||||
SESSION.ibd_bytes = 0
|
||||
return nothing
|
||||
end
|
||||
|
||||
"""
|
||||
close_dataset()
|
||||
|
||||
Close the open dataset, drop every reference and return memory to the OS.
|
||||
"""
|
||||
function close_dataset()
|
||||
summary = lock(SESSION.lock) do
|
||||
info = session_metadata()
|
||||
_close_locked!()
|
||||
return info
|
||||
end
|
||||
release_os_memory!(full=true)
|
||||
return summary
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Access helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
"""Return the active `MSIData` or throw a structured session error."""
|
||||
function require_data()
|
||||
data = lock(SESSION.lock) do
|
||||
SESSION.data
|
||||
end
|
||||
data === nothing && throw(session_error(
|
||||
"No dataset is open in this MCP session.";
|
||||
suggested_action="Call msi_open_dataset with the path to an .imzML or .mzML file first.",
|
||||
))
|
||||
SESSION.last_access = time()
|
||||
return data
|
||||
end
|
||||
|
||||
"""Return the active dataset id, or `nothing`."""
|
||||
active_dataset_id() = lock(SESSION.lock) do
|
||||
SESSION.dataset_id
|
||||
end
|
||||
|
||||
has_open_dataset() = lock(SESSION.lock) do
|
||||
SESSION.data !== nothing
|
||||
end
|
||||
|
||||
"""Ensure per-spectrum analytics (TIC/BPI/min/max + Bloom filters) are computed."""
|
||||
function ensure_analytics!(data::MSI_src.MSIData)
|
||||
MSI_src.is_set(data.analytics_ready) && return 0.0
|
||||
t0 = time_ns()
|
||||
MSI_src.precompute_analytics(data)
|
||||
return (time_ns() - t0) / 1e9
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Metadata
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _source_info(data::MSI_src.MSIData)
|
||||
src = data.source
|
||||
if src isa MSI_src.ImzMLSource
|
||||
return Dict{String,Any}(
|
||||
"type" => "imzML",
|
||||
"mz_format" => string(src.mz_format),
|
||||
"intensity_format" => string(src.intensity_format),
|
||||
"compressed" => src.is_any_compressed,
|
||||
"mmap_active" => src.mmap_data !== nothing,
|
||||
"open_handles" => length(src.ibd_handles),
|
||||
)
|
||||
elseif src isa MSI_src.MzMLSource
|
||||
return Dict{String,Any}(
|
||||
"type" => "mzML",
|
||||
"mz_format" => string(src.mz_format),
|
||||
"intensity_format" => string(src.intensity_format),
|
||||
"compressed" => false,
|
||||
"mmap_active" => src.mmap_data !== nothing,
|
||||
"open_handles" => length(src.file_handles),
|
||||
)
|
||||
end
|
||||
return Dict{String,Any}("type" => string(typeof(src)))
|
||||
end
|
||||
|
||||
function _instrument_info(data::MSI_src.MSIData)
|
||||
im = data.instrument_metadata
|
||||
im === nothing && return nothing
|
||||
return Dict{String,Any}(
|
||||
"instrument_model" => im.instrument_model,
|
||||
"resolution" => im.resolution,
|
||||
"mass_accuracy_ppm" => im.mass_accuracy_ppm,
|
||||
"polarity" => im.polarity,
|
||||
"calibration_status" => im.calibration_status,
|
||||
"acquisition_mode" => im.acquisition_mode,
|
||||
"mz_axis_type" => im.mz_axis_type,
|
||||
"laser_settings" => im.laser_settings,
|
||||
"vendor_preprocessing_steps" => im.vendor_preprocessing_steps,
|
||||
)
|
||||
end
|
||||
|
||||
function _metadata_locked(data::MSI_src.MSIData)
|
||||
min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0)
|
||||
max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0)
|
||||
mz_range = (min_mz < max_mz && isfinite(min_mz) && isfinite(max_mz)) ?
|
||||
Any[compact_float(min_mz), compact_float(max_mz)] : nothing
|
||||
|
||||
width, height = data.image_dims
|
||||
cached = try
|
||||
lock(data.cache_lock) do
|
||||
length(data.cache)
|
||||
end
|
||||
catch
|
||||
0
|
||||
end
|
||||
|
||||
return Dict{String,Any}(
|
||||
"open" => true,
|
||||
"path" => SESSION.path,
|
||||
"dataset_id" => SESSION.dataset_id,
|
||||
"num_spectra" => length(data.spectra_metadata),
|
||||
"image_dims" => Any[width, height],
|
||||
"coordinate_map" => data.coordinate_map !== nothing,
|
||||
"mz_range" => mz_range,
|
||||
"analytics_ready" => MSI_src.is_set(data.analytics_ready),
|
||||
"cache_size" => SESSION.cache_size,
|
||||
"cached_spectra" => cached,
|
||||
"use_mmap" => SESSION.use_mmap,
|
||||
"file_bytes" => Dict{String,Any}("xml" => SESSION.xml_bytes, "ibd" => SESSION.ibd_bytes),
|
||||
"source" => _source_info(data),
|
||||
"instrument" => _instrument_info(data),
|
||||
"opened_at" => SESSION.opened_at === nothing ? nothing : Dates.format(Dates.unix2datetime(SESSION.opened_at), "yyyy-mm-ddTHH:MM:SS"),
|
||||
"uptime_seconds" => SESSION.opened_at === nothing ? nothing : compact_float(time() - SESSION.opened_at),
|
||||
"process" => Dict{String,Any}(
|
||||
"julia_version" => string(VERSION),
|
||||
"threads" => Base.Threads.nthreads(),
|
||||
"pid" => getpid(),
|
||||
"rss_mb" => _rss_mb(),
|
||||
),
|
||||
)
|
||||
end
|
||||
|
||||
function _rss_mb()
|
||||
try
|
||||
for line in eachline("/proc/$(getpid())/status")
|
||||
startswith(line, "VmRSS:") || continue
|
||||
parts = split(line)
|
||||
length(parts) >= 2 || continue
|
||||
return round(parse(Float64, parts[2]) / 1024, digits=1)
|
||||
end
|
||||
catch
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
"""Public, lock-safe metadata snapshot (returns `open=false` when idle)."""
|
||||
function session_metadata()
|
||||
return lock(SESSION.lock) do
|
||||
if SESSION.data === nothing
|
||||
return Dict{String,Any}(
|
||||
"open" => false,
|
||||
"hint" => "Call msi_open_dataset to load an .imzML or .mzML dataset.",
|
||||
"process" => Dict{String,Any}(
|
||||
"julia_version" => string(VERSION),
|
||||
"threads" => Base.Threads.nthreads(),
|
||||
"pid" => getpid(),
|
||||
"rss_mb" => _rss_mb(),
|
||||
),
|
||||
)
|
||||
end
|
||||
_metadata_locked(SESSION.data)
|
||||
end
|
||||
end
|
||||
+610
@@ -0,0 +1,610 @@
|
||||
# src/tasks.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Execution layer: background tasks + polling.
|
||||
#
|
||||
# `msi_execute_runspec` never blocks the JSON-RPC loop. It spawns a Julia Task
|
||||
# on the thread pool and returns a task_id immediately. The client polls
|
||||
# `msi_get_task_status` and finally fetches `msi_get_task_result` (or reads the
|
||||
# matching MCP resource).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
mutable struct EngineTask
|
||||
id::String
|
||||
runspec_id::String
|
||||
kind::Symbol
|
||||
dataset_id::String
|
||||
status::Symbol # :queued | :running | :completed | :failed | :cancelled
|
||||
progress::Float64
|
||||
message::String
|
||||
created_at::Float64
|
||||
started_at::Union{Nothing,Float64}
|
||||
finished_at::Union{Nothing,Float64}
|
||||
result::Union{Nothing,Dict{String,Any}}
|
||||
error::Union{Nothing,Dict{String,Any}}
|
||||
cancel_requested::Bool
|
||||
task::Union{Nothing,Task}
|
||||
end
|
||||
|
||||
const TASK_LOCK = ReentrantLock()
|
||||
const TASKS = Dict{String,EngineTask}()
|
||||
const TASK_ORDER = String[]
|
||||
const MAX_TASKS = 64
|
||||
|
||||
is_terminal(status::Symbol) = status in (:completed, :failed, :cancelled)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Registry helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _update_task!(f::Function, task::EngineTask)
|
||||
lock(TASK_LOCK) do
|
||||
f(task)
|
||||
end
|
||||
return task
|
||||
end
|
||||
|
||||
function _finish_task!(task::EngineTask, status::Symbol;
|
||||
result=nothing, error=nothing, message=nothing)
|
||||
_update_task!(task) do t
|
||||
t.status = status
|
||||
t.finished_at = time()
|
||||
t.progress = status == :completed ? 1.0 : t.progress
|
||||
result !== nothing && (t.result = result)
|
||||
error !== nothing && (t.error = error)
|
||||
message !== nothing && (t.message = message)
|
||||
end
|
||||
return task
|
||||
end
|
||||
|
||||
function _prune_tasks!()
|
||||
# Called while holding TASK_LOCK.
|
||||
while length(TASK_ORDER) > MAX_TASKS
|
||||
idx = findfirst(id -> begin
|
||||
t = get(TASKS, id, nothing)
|
||||
t === nothing || is_terminal(t.status)
|
||||
end, TASK_ORDER)
|
||||
idx === nothing && break
|
||||
id = TASK_ORDER[idx]
|
||||
deleteat!(TASK_ORDER, idx)
|
||||
pop!(TASKS, id, nothing)
|
||||
end
|
||||
end
|
||||
|
||||
function get_task(task_id::AbstractString)
|
||||
lock(TASK_LOCK) do
|
||||
t = get(TASKS, String(task_id), nothing)
|
||||
t === nothing && throw(invalid_params(
|
||||
"Unknown task_id: $(task_id)";
|
||||
suggested_action="Use msi_list_tasks to see recent tasks. Task records are pruned after 64 newer tasks."))
|
||||
return t
|
||||
end
|
||||
end
|
||||
|
||||
function list_tasks(; limit::Integer=20, status::Union{Nothing,AbstractString}=nothing)
|
||||
lock(TASK_LOCK) do
|
||||
ids = reverse(TASK_ORDER)
|
||||
out = EngineTask[]
|
||||
wanted = status === nothing ? nothing : Symbol(status)
|
||||
for id in ids
|
||||
t = get(TASKS, id, nothing)
|
||||
t === nothing && continue
|
||||
wanted !== nothing && t.status != wanted && continue
|
||||
push!(out, t)
|
||||
length(out) >= Int(limit) && break
|
||||
end
|
||||
return out
|
||||
end
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public status/result payloads
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _duration(t::EngineTask)
|
||||
t.started_at === nothing && return nothing
|
||||
stop = t.finished_at === nothing ? time() : t.finished_at
|
||||
return compact_float(stop - t.started_at)
|
||||
end
|
||||
|
||||
function task_status_payload(t::EngineTask; include_summary::Bool=true)
|
||||
payload = Dict{String,Any}(
|
||||
"task_id" => t.id,
|
||||
"runspec_id" => t.runspec_id,
|
||||
"kind" => string(t.kind),
|
||||
"status" => string(t.status),
|
||||
"progress" => compact_float(t.progress),
|
||||
"message" => t.message,
|
||||
"created_at" => Dates.format(Dates.unix2datetime(t.created_at), "yyyy-mm-ddTHH:MM:SS"),
|
||||
"started_at" => t.started_at === nothing ? nothing : Dates.format(Dates.unix2datetime(t.started_at), "yyyy-mm-ddTHH:MM:SS"),
|
||||
"finished_at" => t.finished_at === nothing ? nothing : Dates.format(Dates.unix2datetime(t.finished_at), "yyyy-mm-ddTHH:MM:SS"),
|
||||
"duration_seconds" => _duration(t),
|
||||
"cancel_requested" => t.cancel_requested,
|
||||
"result_ready" => t.status == :completed && t.result !== nothing,
|
||||
)
|
||||
if t.error !== nothing
|
||||
payload["error"] = t.error
|
||||
end
|
||||
if include_summary && t.status == :completed && t.result !== nothing
|
||||
payload["result_summary"] = result_summary(t.result)
|
||||
end
|
||||
return payload
|
||||
end
|
||||
|
||||
"""Short version of a result, safe to embed in status polling responses."""
|
||||
function result_summary(result::Dict{String,Any})
|
||||
summary = Dict{String,Any}()
|
||||
for key in ("kind", "mass", "tolerance", "shape", "stats", "num_slices",
|
||||
"matrix_shape", "nonzeros", "density", "artifacts", "analytics", "note")
|
||||
haskey(result, key) && (summary[key] = result[key])
|
||||
end
|
||||
return summary
|
||||
end
|
||||
|
||||
function task_result_payload(t::EngineTask)
|
||||
if t.status == :completed
|
||||
return t.result === nothing ? Dict{String,Any}("task_id" => t.id, "status" => string(t.status)) :
|
||||
merge(Dict{String,Any}("task_id" => t.id, "status" => string(t.status)), t.result)
|
||||
elseif t.status == :failed
|
||||
return Dict{String,Any}(
|
||||
"task_id" => t.id,
|
||||
"status" => string(t.status),
|
||||
"error" => t.error === nothing ? Dict{String,Any}("message" => "Unknown failure") : t.error,
|
||||
"hint" => "Use msi_get_task_status for the timeline, or re-plan with smaller parameters.",
|
||||
)
|
||||
elseif t.status == :cancelled
|
||||
return Dict{String,Any}("task_id" => t.id, "status" => string(t.status),
|
||||
"message" => t.message)
|
||||
end
|
||||
payload = task_status_payload(t; include_summary=false)
|
||||
payload["hint"] = "Task is still in progress. Poll msi_get_task_status, then retry msi_get_task_result."
|
||||
return payload
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cancellation / waiting
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function cancel_task(task_id::AbstractString)
|
||||
t = get_task(task_id)
|
||||
lock(TASK_LOCK) do
|
||||
if t.status in (:queued, :running)
|
||||
t.cancel_requested = true
|
||||
t.message = "cancellation requested"
|
||||
if t.status == :queued
|
||||
t.status = :cancelled
|
||||
t.finished_at = time()
|
||||
end
|
||||
end
|
||||
return task_status_payload(t; include_summary=false)
|
||||
end
|
||||
end
|
||||
|
||||
_cancelled(t::EngineTask) = lock(TASK_LOCK) do
|
||||
t.cancel_requested
|
||||
end
|
||||
|
||||
function wait_for_task(t::EngineTask; timeout::Real=0.0)
|
||||
timeout <= 0 && return t
|
||||
deadline = time() + Float64(timeout)
|
||||
while time() < deadline
|
||||
done = lock(TASK_LOCK) do
|
||||
is_terminal(t.status)
|
||||
end
|
||||
done && break
|
||||
sleep(0.05)
|
||||
end
|
||||
return t
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Execution
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function submit_runspec(rs::RunSpec; force::Bool=false, wait_seconds::Real=0.0)
|
||||
check_runspec_dataset(rs)
|
||||
|
||||
local task::EngineTask
|
||||
local reused::Bool
|
||||
lock(TASK_LOCK) do
|
||||
reused = false
|
||||
if !force
|
||||
for id in reverse(TASK_ORDER)
|
||||
t = get(TASKS, id, nothing)
|
||||
t === nothing && continue
|
||||
if t.runspec_id == rs.id && t.dataset_id == rs.dataset_id &&
|
||||
t.status in (:queued, :running, :completed)
|
||||
task = t
|
||||
reused = true
|
||||
break
|
||||
end
|
||||
end
|
||||
end
|
||||
if !reused
|
||||
task = EngineTask(
|
||||
string(uuid4()), rs.id, rs.kind, rs.dataset_id,
|
||||
:queued, 0.0, "queued", time(), nothing, nothing,
|
||||
nothing, nothing, false, nothing,
|
||||
)
|
||||
TASKS[task.id] = task
|
||||
push!(TASK_ORDER, task.id)
|
||||
_prune_tasks!()
|
||||
task.task = Base.Threads.@spawn _execute_task!(task, rs)
|
||||
end
|
||||
end
|
||||
|
||||
wait_seconds > 0 && wait_for_task(task; timeout=wait_seconds)
|
||||
payload = task_status_payload(task)
|
||||
payload["reused"] = reused
|
||||
return payload
|
||||
end
|
||||
|
||||
function _execute_task!(task::EngineTask, rs::RunSpec)
|
||||
cancelled_before_start = lock(TASK_LOCK) do
|
||||
if task.cancel_requested
|
||||
task.status = :cancelled
|
||||
task.finished_at = time()
|
||||
task.message = "cancelled before start"
|
||||
true
|
||||
else
|
||||
task.status = :running
|
||||
task.started_at = time()
|
||||
task.message = "starting $(rs.kind)"
|
||||
task.progress = 0.01
|
||||
false
|
||||
end
|
||||
end
|
||||
cancelled_before_start && return nothing
|
||||
|
||||
try
|
||||
_cancelled(task) && throw(InterruptException())
|
||||
data = require_data()
|
||||
check_runspec_dataset(rs)
|
||||
|
||||
result = _dispatch_runspec(rs, task, data)
|
||||
|
||||
if _cancelled(task)
|
||||
_finish_task!(task, :cancelled; message="cancelled before completion")
|
||||
else
|
||||
_finish_task!(task, :completed; result=result, message="completed")
|
||||
end
|
||||
catch e
|
||||
if _cancelled(task) || e isa InterruptException
|
||||
_finish_task!(task, :cancelled; message="cancelled")
|
||||
else
|
||||
@error "RunSpec execution failed" task_id=task.id runspec=rs.id exception=(e, catch_backtrace())
|
||||
_finish_task!(task, :failed; error=error_payload(e; context=Dict{String,Any}(
|
||||
"task_id" => task.id, "runspec_id" => rs.id, "kind" => string(rs.kind))),
|
||||
message=sprint(showerror, e))
|
||||
end
|
||||
finally
|
||||
if rs.kind in (:streaming_pipeline, :analytics)
|
||||
release_os_memory!(full=false)
|
||||
end
|
||||
end
|
||||
return nothing
|
||||
end
|
||||
|
||||
function _set_progress!(task::EngineTask, progress::Real, message::AbstractString)
|
||||
_update_task!(task) do t
|
||||
t.progress = clamp(Float64(progress), 0.0, 1.0)
|
||||
t.message = String(message)
|
||||
end
|
||||
end
|
||||
|
||||
function _dispatch_runspec(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData)
|
||||
if rs.kind == :ion_image
|
||||
return _run_ion_image(rs, task, data)
|
||||
elseif rs.kind == :multiple_slices
|
||||
return _run_multiple_slices(rs, task, data)
|
||||
elseif rs.kind == :streaming_pipeline
|
||||
return _run_streaming_pipeline(rs, task, data)
|
||||
elseif rs.kind == :analytics
|
||||
return _run_analytics(rs, task, data)
|
||||
end
|
||||
throw(internal_error("Unimplemented RunSpec kind: $(rs.kind)"))
|
||||
end
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Kind-specific executors
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _matrix_rows(mat::AbstractMatrix{<:Real})
|
||||
return Any[Any[compact_float(Float64(mat[y, x])) for x in 1:size(mat, 2)]
|
||||
for y in 1:size(mat, 1)]
|
||||
end
|
||||
|
||||
function _analytics_seconds(data, task, stage::AbstractString)
|
||||
if MSI_src.is_set(data.analytics_ready)
|
||||
return 0.0
|
||||
end
|
||||
_set_progress!(task, 0.03, "computing per-spectrum analytics ($(stage))")
|
||||
return ensure_analytics!(data)
|
||||
end
|
||||
|
||||
function _run_ion_image(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData)
|
||||
p = rs.params
|
||||
mass = Float64(p["mass"])
|
||||
tolerance = Float64(p["tolerance"])
|
||||
mask_path = p["mask_path"]
|
||||
|
||||
analytics_s = _analytics_seconds(data, task, "ion image")
|
||||
_cancelled(task) && throw(InterruptException())
|
||||
|
||||
_set_progress!(task, 0.45, "extracting ion image at m/z $(mass) ± $(tolerance)")
|
||||
mat = MSI_src.get_mz_slice(data, mass, tolerance; mask_path=mask_path)
|
||||
analytics_s += 0.0
|
||||
|
||||
_cancelled(task) && throw(InterruptException())
|
||||
_set_progress!(task, 0.80, "writing ion image artifacts")
|
||||
label = safe_filename("ion_mz_" * string(round(mass, digits=4)))
|
||||
dir = artifact_dir(task.id; label=p["output_name"])
|
||||
extra = Dict{String,Any}(
|
||||
"mass" => mass, "tolerance" => tolerance, "mask_path" => mask_path,
|
||||
"dataset_id" => rs.dataset_id, "runspec_id" => rs.id,
|
||||
)
|
||||
artifacts = persist_ion_image(dir, label, mat; extra=extra)
|
||||
|
||||
result = Dict{String,Any}(
|
||||
"kind" => "ion_image",
|
||||
"mass" => mass,
|
||||
"tolerance" => tolerance,
|
||||
"mask_path" => mask_path,
|
||||
"shape" => Any[size(mat, 2), size(mat, 1)],
|
||||
"stats" => matrix_stats(mat),
|
||||
"preview" => preview_matrix(mat; max_dim=Int(p["preview_max_dim"])),
|
||||
"artifacts" => artifacts,
|
||||
"analytics_seconds" => compact_float(analytics_s),
|
||||
"dataset_id" => rs.dataset_id,
|
||||
"runspec_id" => rs.id,
|
||||
)
|
||||
if p["include_matrix"] && length(mat) <= 250_000
|
||||
result["matrix"] = _matrix_rows(mat)
|
||||
elseif p["include_matrix"]
|
||||
result["note"] = "include_matrix was requested but the matrix has $(length(mat)) pixels; read the CSV artifact instead."
|
||||
end
|
||||
_set_progress!(task, 0.98, "finalizing")
|
||||
return result
|
||||
end
|
||||
|
||||
function _run_multiple_slices(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData)
|
||||
p = rs.params
|
||||
masses = Float64.(p["masses"])
|
||||
tolerance = Float64(p["tolerance"])
|
||||
mask_path = p["mask_path"]
|
||||
include_matrix = Bool(p["include_matrix"])
|
||||
preview_dim = Int(p["preview_max_dim"])
|
||||
max_artifacts = 100
|
||||
|
||||
analytics_s = _analytics_seconds(data, task, "multiple slices")
|
||||
_cancelled(task) && throw(InterruptException())
|
||||
|
||||
_set_progress!(task, 0.35, "extracting $(length(masses)) ion images in one pass")
|
||||
slice_dict = MSI_src.get_multiple_mz_slices(data, masses, tolerance; mask_path=mask_path)
|
||||
|
||||
_set_progress!(task, 0.75, "writing artifacts")
|
||||
dir = artifact_dir(task.id; label=p["output_name"])
|
||||
|
||||
sorted_masses = sort(unique(masses))
|
||||
slices = Dict{String,Any}[]
|
||||
summary_rows = Tuple{Float64,Int,Float64,Float64,Int,Union{Nothing,Vector{Float64}}}[]
|
||||
for (i, mass) in enumerate(sorted_masses)
|
||||
mat = get(slice_dict, mass, nothing)
|
||||
if mat === nothing
|
||||
mat = get(slice_dict, Float64(mass), nothing)
|
||||
end
|
||||
mat === nothing && continue
|
||||
st = matrix_stats(mat)
|
||||
entry = Dict{String,Any}(
|
||||
"mass" => mass,
|
||||
"stats" => st,
|
||||
)
|
||||
if i <= max_artifacts
|
||||
label = safe_filename("ion_mz_" * string(round(mass, digits=4)))
|
||||
entry["artifacts"] = persist_ion_image(dir, label, mat;
|
||||
extra=Dict{String,Any}("mass" => mass, "tolerance" => tolerance,
|
||||
"dataset_id" => rs.dataset_id, "runspec_id" => rs.id))
|
||||
end
|
||||
if i <= 8
|
||||
entry["preview"] = preview_matrix(mat; max_dim=preview_dim)
|
||||
end
|
||||
push!(slices, entry)
|
||||
push!(summary_rows, (mass, length(mat), st["max"], st["mean"], st["nonzero"], st["base_peak_coord"]))
|
||||
end
|
||||
|
||||
# One CSV with all per-mass stats is cheap and always written.
|
||||
summary_csv = joinpath(dir, "slices_summary.csv")
|
||||
open(summary_csv, "w") do io
|
||||
println(io, "mass,pixels,max,mean,nonzero,base_peak_x,base_peak_y")
|
||||
for (mass, npix, mx, mn, nz, bp) in summary_rows
|
||||
bx = bp === nothing ? "" : bp[1]
|
||||
by = bp === nothing ? "" : bp[2]
|
||||
println(io, mass, ",", npix, ",", mx, ",", mn, ",", nz, ",", bx, ",", by)
|
||||
end
|
||||
end
|
||||
|
||||
result = Dict{String,Any}(
|
||||
"kind" => "multiple_slices",
|
||||
"tolerance" => tolerance,
|
||||
"mask_path" => mask_path,
|
||||
"num_slices" => length(slices),
|
||||
"slices" => slices,
|
||||
"artifacts" => Dict{String,Any}(
|
||||
"summary_csv" => artifact_record(summary_csv),
|
||||
"directory" => dir,
|
||||
),
|
||||
"artifacts_written_for" => min(length(slices), max_artifacts),
|
||||
"analytics_seconds" => compact_float(analytics_s),
|
||||
"dataset_id" => rs.dataset_id,
|
||||
"runspec_id" => rs.id,
|
||||
)
|
||||
if include_matrix && !isempty(slices) && length(slices) <= 16
|
||||
result["matrices"] = [Dict{String,Any}(
|
||||
"mass" => s["mass"],
|
||||
"rows" => _matrix_rows(get(slice_dict, s["mass"], zeros(Float32, 0, 0))),
|
||||
) for s in slices]
|
||||
end
|
||||
_set_progress!(task, 0.98, "finalizing")
|
||||
return result
|
||||
end
|
||||
|
||||
"""Convert JSON step params into the `Dict{Symbol,Any}` shape the engine expects."""
|
||||
function _engine_step_params(params::Dict{String,Any})
|
||||
out = Dict{Symbol,Any}()
|
||||
for (k, v) in params
|
||||
key = Symbol(k)
|
||||
if key in (:method, :peak_method, :calibration_method) && v isa AbstractString
|
||||
out[key] = Symbol(v)
|
||||
elseif v isa AbstractString && key in (:mode, :type)
|
||||
out[key] = Symbol(v)
|
||||
elseif v isa Bool || v isa Real || v isa AbstractString
|
||||
out[key] = v
|
||||
elseif v isa AbstractDict
|
||||
out[key] = Dict{Symbol,Any}(Symbol(kk) => vv for (kk, vv) in v)
|
||||
else
|
||||
out[key] = v
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
function _run_streaming_pipeline(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData)
|
||||
p = rs.params
|
||||
steps = MSI_src.StreamingStep[]
|
||||
for s in p["steps"]
|
||||
push!(steps, MSI_src.StreamingStep(Symbol(s["name"]),
|
||||
_engine_step_params(Dict{String,Any}(s["params"]))))
|
||||
end
|
||||
config = MSI_src.PipelineConfig(
|
||||
steps = steps,
|
||||
reference_peaks = Float64.(p["reference_peaks"]),
|
||||
num_bins = Int(p["num_bins"]),
|
||||
min_peaks_per_bin = Int(p["min_peaks_per_bin"]),
|
||||
frequency_threshold = Float64(p["frequency_threshold"]),
|
||||
)
|
||||
|
||||
masked_indices = nothing
|
||||
if p["mask_path"] !== nothing
|
||||
_set_progress!(task, 0.05, "preparing ROI mask")
|
||||
width, height = data.image_dims
|
||||
mask_matrix = MSI_src.load_and_prepare_mask(String(p["mask_path"]), (width, height))
|
||||
masked_indices = collect(MSI_src.get_masked_spectrum_indices(data, mask_matrix))
|
||||
isempty(masked_indices) && throw(invalid_params(
|
||||
"The ROI mask selects zero spectra."; suggested_action="Check the mask orientation and threshold."))
|
||||
end
|
||||
|
||||
_cancelled(task) && throw(InterruptException())
|
||||
_set_progress!(task, 0.15, "streaming $(length(steps)) kernel steps over $(length(data.spectra_metadata)) spectra")
|
||||
feature_matrix, bin_centers = MSI_src.process_dataset!(data, config;
|
||||
progress_callback = frac -> _set_progress!(task, 0.15 + 0.65 * Float64(frac),
|
||||
"streaming pass $(round(Int, 100 * frac))%"),
|
||||
masked_indices = masked_indices)
|
||||
|
||||
_cancelled(task) && throw(InterruptException())
|
||||
_set_progress!(task, 0.85, "writing feature matrix artifacts")
|
||||
dir = artifact_dir(task.id; label=p["output_name"])
|
||||
mtx = write_sparse_mtx(joinpath(dir, "feature_matrix.mtx"), feature_matrix)
|
||||
bins_csv = write_vector_csv(joinpath(dir, "bin_centers.csv"), bin_centers;
|
||||
header="bin,mz")
|
||||
|
||||
rows, cols = size(feature_matrix)
|
||||
nnz_val = SparseArrays.nnz(feature_matrix)
|
||||
density = rows * cols == 0 ? 0.0 : nnz_val / (rows * cols)
|
||||
processed = masked_indices === nothing ? cols : length(masked_indices)
|
||||
result = Dict{String,Any}(
|
||||
"kind" => "streaming_pipeline",
|
||||
"matrix_shape" => Any[rows, cols],
|
||||
"nonzeros" => nnz_val,
|
||||
"density" => compact_float(density),
|
||||
"num_bins_requested" => Int(p["num_bins"]),
|
||||
"num_bins_kept" => rows,
|
||||
"steps" => p["steps"],
|
||||
"mask_path" => p["mask_path"],
|
||||
"num_spectra_total" => cols,
|
||||
"num_spectra_processed" => processed,
|
||||
"bin_mz_range" => isempty(bin_centers) ? nothing :
|
||||
Any[compact_float(first(bin_centers)), compact_float(last(bin_centers))],
|
||||
"top_bins" => top_bins(feature_matrix, bin_centers; n=20),
|
||||
"artifacts" => Dict{String,Any}(
|
||||
"matrix_mtx" => mtx,
|
||||
"bin_centers_csv" => bins_csv,
|
||||
"directory" => dir,
|
||||
),
|
||||
"dataset_id" => rs.dataset_id,
|
||||
"runspec_id" => rs.id,
|
||||
)
|
||||
if masked_indices !== nothing
|
||||
result["note"] = "Masked run: $(processed) of $(cols) spectra were processed; columns outside the ROI are all-zero."
|
||||
end
|
||||
if p["include_matrix"] && nnz_val <= 20_000
|
||||
I, J, V = SparseArrays.findnz(feature_matrix)
|
||||
result["sparse_triplets"] = Dict{String,Any}(
|
||||
"rows" => collect(Int, I), "cols" => collect(Int, J),
|
||||
"values" => [compact_float(v) for v in V],
|
||||
)
|
||||
end
|
||||
_set_progress!(task, 0.98, "finalizing")
|
||||
return result
|
||||
end
|
||||
|
||||
function _run_analytics(rs::RunSpec, task::EngineTask, data::MSI_src.MSIData)
|
||||
p = rs.params
|
||||
_set_progress!(task, 0.05, "scanning spectra (TIC, BPI, m/z bounds, Bloom filters)")
|
||||
elapsed = ensure_analytics!(data)
|
||||
_set_progress!(task, 0.85, "summarizing statistics")
|
||||
|
||||
stats_df = MSI_src.get_spectrum_stats(data)
|
||||
dir = artifact_dir(task.id; label=p["output_name"])
|
||||
csv_path = joinpath(dir, "spectrum_stats.csv")
|
||||
stats_df === nothing || CSV.write(csv_path, stats_df)
|
||||
|
||||
summary = Dict{String,Any}()
|
||||
rows = Any[]
|
||||
if stats_df !== nothing
|
||||
for col in ("TIC", "BPI", "NumPoints")
|
||||
v = Float64.(stats_df[!, col])
|
||||
summary[col] = Dict{String,Any}(
|
||||
"min" => compact_float(minimum(v)),
|
||||
"max" => compact_float(maximum(v)),
|
||||
"mean" => compact_float(Statistics.mean(v)),
|
||||
"median" => compact_float(Statistics.median(v)),
|
||||
"sum" => compact_float(sum(v)),
|
||||
)
|
||||
end
|
||||
summary["base_peak_mz_range"] = Any[
|
||||
compact_float(minimum(stats_df[!, "BasePeakMZ"])),
|
||||
compact_float(maximum(stats_df[!, "BasePeakMZ"])),
|
||||
]
|
||||
n = min(Int(p["include_rows"]), nrow(stats_df))
|
||||
for i in 1:n
|
||||
push!(rows, Dict{String,Any}(
|
||||
"spectrum_id" => Int(stats_df[i, "SpectrumID"]),
|
||||
"tic" => compact_float(stats_df[i, "TIC"]),
|
||||
"bpi" => compact_float(stats_df[i, "BPI"]),
|
||||
"base_peak_mz" => compact_float(stats_df[i, "BasePeakMZ"]),
|
||||
"num_points" => Int(stats_df[i, "NumPoints"]),
|
||||
"min_mz" => compact_float(stats_df[i, "MinMZ"]),
|
||||
"max_mz" => compact_float(stats_df[i, "MaxMZ"]),
|
||||
"mode" => string(stats_df[i, "Mode"]),
|
||||
))
|
||||
end
|
||||
end
|
||||
|
||||
min_mz = Base.Threads.atomic_add!(data.global_min_mz, 0.0)
|
||||
max_mz = Base.Threads.atomic_add!(data.global_max_mz, 0.0)
|
||||
result = Dict{String,Any}(
|
||||
"kind" => "analytics",
|
||||
"elapsed_seconds" => compact_float(elapsed),
|
||||
"num_spectra" => length(data.spectra_metadata),
|
||||
"mz_range" => Any[compact_float(min_mz), compact_float(max_mz)],
|
||||
"aggregate" => summary,
|
||||
"rows" => rows,
|
||||
"artifacts" => Dict{String,Any}(
|
||||
"spectrum_stats_csv" => stats_df === nothing ? nothing : artifact_record(csv_path),
|
||||
"directory" => dir,
|
||||
),
|
||||
"dataset_id" => rs.dataset_id,
|
||||
"runspec_id" => rs.id,
|
||||
)
|
||||
_set_progress!(task, 0.98, "finalizing")
|
||||
return result
|
||||
end
|
||||
@@ -0,0 +1,153 @@
|
||||
# src/tools/dataset.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Dataset lifecycle tools (synchronous, cheap).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const _OPEN_DATASET_SCHEMA = object_schema(Dict{String,Any}(
|
||||
"file_path" => prop("string",
|
||||
"Absolute path to the .imzML file (its .ibd companion must exist) or to a .mzML file."),
|
||||
"cache_size" => prop("integer",
|
||||
"Number of spectra kept in the LRU cache for random access. Default 300.",
|
||||
default=300, minimum=0, maximum=100000),
|
||||
"use_mmap" => prop("boolean",
|
||||
"Memory-map the .ibd file and hint MADV_SEQUENTIAL to the Linux kernel. Default true.",
|
||||
default=true),
|
||||
"precompute_analytics" => prop("boolean",
|
||||
"Run the per-spectrum analytics scan immediately (TIC/BPI/mz bounds + Bloom filters). " *
|
||||
"Set false to open fast and defer the scan to the first extraction. Default false.",
|
||||
default=false),
|
||||
); required=["file_path"])
|
||||
|
||||
const OPEN_DATASET_TOOL = MCPTool(
|
||||
name = "msi_open_dataset",
|
||||
description = """
|
||||
Open (or switch) the active mass-spectrometry imaging dataset. This is the first
|
||||
call in every session: it reads the imzML header and the binary metadata cache
|
||||
(.cache) and keeps the resulting MSIData object alive between tool calls.
|
||||
|
||||
Returns dataset metadata: number of spectra, image dimensions, m/z range (if
|
||||
analytics are ready), source formats, mmap status and how long opening took.
|
||||
Only one dataset can be open at a time; opening a new one closes and cleans the
|
||||
previous one.
|
||||
""",
|
||||
input_schema = _OPEN_DATASET_SCHEMA,
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => true),
|
||||
handler = guarded_handler() do params
|
||||
file_path = opt_string(params, "file_path"; default="")
|
||||
isempty(file_path) && throw(invalid_params(
|
||||
"`file_path` is required."; suggested_action="Pass an absolute .imzML or .mzML path."))
|
||||
meta = open_dataset(file_path;
|
||||
cache_size = opt_int(params, "cache_size"; default=300, min=0, max=100_000),
|
||||
use_mmap = opt_bool(params, "use_mmap"; default=true),
|
||||
precompute_analytics = opt_bool(params, "precompute_analytics"; default=false))
|
||||
return tool_json(meta)
|
||||
end,
|
||||
)
|
||||
|
||||
const _CLOSE_DATASET_SCHEMA = object_schema(Dict{String,Any}())
|
||||
|
||||
const CLOSE_DATASET_TOOL = MCPTool(
|
||||
name = "msi_close_dataset",
|
||||
description = """
|
||||
Close the active dataset, release every file handle and return freed memory to
|
||||
the operating system (GC.gc(true) + malloc_trim on glibc/Linux). Call this when
|
||||
you are done, or before opening a different dataset, to keep RSS low in long
|
||||
sessions.
|
||||
""",
|
||||
input_schema = _CLOSE_DATASET_SCHEMA,
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
previous = close_dataset()
|
||||
release_os_memory!(full=true)
|
||||
return tool_json(Dict{String,Any}(
|
||||
"closed" => true,
|
||||
"previous_dataset" => previous,
|
||||
"process" => Dict{String,Any}("rss_mb" => _rss_mb()),
|
||||
))
|
||||
end,
|
||||
)
|
||||
|
||||
const DATASET_INFO_TOOL = MCPTool(
|
||||
name = "msi_dataset_info",
|
||||
description = """
|
||||
Report the state of the active session without doing heavy work: path, dataset
|
||||
id, dimensions, number of spectra, whether analytics are computed, mmap and
|
||||
cache status, RSS and thread count. Use it to check whether a dataset is open
|
||||
before planning work.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}()),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
return tool_json(session_metadata())
|
||||
end,
|
||||
)
|
||||
|
||||
const DATASET_STATS_TOOL = MCPTool(
|
||||
name = "msi_get_dataset_stats",
|
||||
description = """
|
||||
Return per-spectrum descriptive statistics (TIC, BPI, base-peak m/z, number of
|
||||
points, m/z bounds, mode). If analytics have not been computed yet this call
|
||||
runs the full scan, which can take a while on large datasets; for big files
|
||||
prefer msi_plan_analytics + msi_execute_runspec so the scan runs in the
|
||||
background. The resource msi://dataset/stats is only populated after that scan.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"aggregate_only" => prop("boolean", "If true, omit per-spectrum rows. Default false.", default=false),
|
||||
"limit" => prop("integer", "Maximum number of per-spectrum rows to return. Default 50.",
|
||||
default=50, minimum=0, maximum=5000),
|
||||
)),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
data = require_data()
|
||||
elapsed = ensure_analytics!(data)
|
||||
stats_df = MSI_src.get_spectrum_stats(data)
|
||||
if stats_df === nothing
|
||||
throw(internal_error("Analytics scan finished but no statistics table was produced."))
|
||||
end
|
||||
limit = opt_int(params, "limit"; default=50, min=0, max=5000)
|
||||
aggregate_only = opt_bool(params, "aggregate_only"; default=false)
|
||||
aggregate = Dict{String,Any}()
|
||||
for col in ("TIC", "BPI", "NumPoints")
|
||||
v = Float64.(stats_df[!, col])
|
||||
aggregate[col] = Dict{String,Any}(
|
||||
"min" => compact_float(minimum(v)),
|
||||
"max" => compact_float(maximum(v)),
|
||||
"mean" => compact_float(Statistics.mean(v)),
|
||||
"median" => compact_float(Statistics.median(v)),
|
||||
)
|
||||
end
|
||||
rows = Any[]
|
||||
if !aggregate_only
|
||||
n = min(limit, nrow(stats_df))
|
||||
for i in 1:n
|
||||
push!(rows, Dict{String,Any}(
|
||||
"spectrum_id" => Int(stats_df[i, "SpectrumID"]),
|
||||
"tic" => compact_float(stats_df[i, "TIC"]),
|
||||
"bpi" => compact_float(stats_df[i, "BPI"]),
|
||||
"base_peak_mz" => compact_float(stats_df[i, "BasePeakMZ"]),
|
||||
"num_points" => Int(stats_df[i, "NumPoints"]),
|
||||
"min_mz" => compact_float(stats_df[i, "MinMZ"]),
|
||||
"max_mz" => compact_float(stats_df[i, "MaxMZ"]),
|
||||
"mode" => string(stats_df[i, "Mode"]),
|
||||
))
|
||||
end
|
||||
end
|
||||
return tool_json(Dict{String,Any}(
|
||||
"dataset_id" => active_dataset_id(),
|
||||
"num_spectra" => nrow(stats_df),
|
||||
"analytics_seconds" => compact_float(elapsed),
|
||||
"aggregate" => aggregate,
|
||||
"rows" => rows,
|
||||
"rows_returned" => length(rows),
|
||||
"hint" => "Full table available as a CSV artifact via msi_plan_analytics.",
|
||||
))
|
||||
end,
|
||||
)
|
||||
@@ -0,0 +1,99 @@
|
||||
# src/tools/imaging.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Synchronous ion-image shortcuts.
|
||||
#
|
||||
# These execute immediately in the tool call. They are convenient for quick
|
||||
# queries but block the response until the pass completes; for expensive jobs
|
||||
# use the planning + task tools instead.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
function _sync_runspec(kind::Symbol, params::Dict{String,Any})
|
||||
material = Dict{String,Any}("kind" => string(kind), "params" => params,
|
||||
"dataset_id" => active_dataset_id())
|
||||
return RunSpec(short_hash(material, 32), kind, active_dataset_id(), params, time(), "synchronous call")
|
||||
end
|
||||
|
||||
function _sync_task(kind::Symbol)
|
||||
return EngineTask(string(uuid4()), "sync", kind, active_dataset_id(),
|
||||
:running, 0.0, "synchronous call", time(), time(), nothing,
|
||||
nothing, nothing, false, nothing)
|
||||
end
|
||||
|
||||
const GET_MZ_SLICE_SCHEMA = object_schema(Dict{String,Any}(
|
||||
"mass" => prop("number", "Target m/z in Daltons (e.g. 756.55)."),
|
||||
"tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.",
|
||||
default=0.1, exclusiveMinimum=0.0),
|
||||
"mask_path" => prop("string",
|
||||
"Optional absolute path to a mask image; only ROI pixels are read (white = tissue)."),
|
||||
"include_matrix" => prop("boolean",
|
||||
"Include the full intensity matrix in the JSON response (only for matrices ≤ 250,000 pixels). Default false.",
|
||||
default=false),
|
||||
"preview_max_dim" => prop("integer", "Maximum preview dimension. Default 96.",
|
||||
default=96, minimum=16, maximum=256),
|
||||
"output_name" => prop("string", "Label for the artifact directory. Default derived from m/z."),
|
||||
); required=["mass"])
|
||||
|
||||
const GET_MZ_SLICE_TOOL = MCPTool(
|
||||
name = "msi_get_mz_slice",
|
||||
description = """
|
||||
Extract an ion image (2D intensity matrix) for one m/z value immediately,
|
||||
without planning. Applies the engine's 3-layer pre-filter (m/z range → Bloom
|
||||
filter → targeted read) and, on the first extraction, runs the analytics scan.
|
||||
The full matrix is written as CSV + PGM under artifacts/; the response carries
|
||||
compact statistics and a downsampled preview.
|
||||
|
||||
For large datasets or several masses prefer msi_plan_ion_image +
|
||||
msi_execute_runspec, which runs in the background.
|
||||
""",
|
||||
input_schema = GET_MZ_SLICE_SCHEMA,
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
data = require_data()
|
||||
p = _ion_image_params(params, data; multiple=false)
|
||||
pop!(p, "_verify", nothing)
|
||||
result = _run_ion_image(_sync_runspec(:ion_image, p), _sync_task(:ion_image), data)
|
||||
result["synchronous"] = true
|
||||
return tool_json(result)
|
||||
end,
|
||||
)
|
||||
|
||||
const GET_MULTIPLE_SLICES_SCHEMA = object_schema(Dict{String,Any}(
|
||||
"masses" => prop("array", "List of target m/z values (max 50 for the synchronous shortcut).",
|
||||
items=Dict{String,Any}("type" => "number"), minItems=1, maxItems=50),
|
||||
"tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.",
|
||||
default=0.1, exclusiveMinimum=0.0),
|
||||
"mask_path" => prop("string", "Optional absolute path to a mask image."),
|
||||
"include_matrix" => prop("boolean",
|
||||
"Include matrices for up to 16 slices. Default false.", default=false),
|
||||
"preview_max_dim" => prop("integer", "Maximum preview dimension. Default 64.",
|
||||
default=64, minimum=16, maximum=256),
|
||||
"output_name" => prop("string", "Label for the artifact directory. Default multiple_slices_sync."),
|
||||
); required=["masses"])
|
||||
|
||||
const GET_MULTIPLE_SLICES_TOOL = MCPTool(
|
||||
name = "msi_get_multiple_mz_slices",
|
||||
description = """
|
||||
Synchronous shortcut to extract several ion images in a single I/O pass using
|
||||
the engine's hierarchy inversion (O(N log M) instead of M passes). Limited to 50
|
||||
masses; for larger panels use msi_plan_multiple_slices + msi_execute_runspec.
|
||||
Full images are written to artifacts/; the response includes per-mass statistics
|
||||
and previews for the first slices.
|
||||
""",
|
||||
input_schema = GET_MULTIPLE_SLICES_SCHEMA,
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
data = require_data()
|
||||
p = _ion_image_params(params, data; multiple=true)
|
||||
pop!(p, "_verify", nothing)
|
||||
length(p["masses"]) > 50 && throw(invalid_params(
|
||||
"The synchronous shortcut accepts at most 50 masses (got $(length(p["masses"]))).";
|
||||
suggested_action="Use msi_plan_multiple_slices + msi_execute_runspec for large panels."))
|
||||
result = _run_multiple_slices(_sync_runspec(:multiple_slices, p), _sync_task(:multiple_slices), data)
|
||||
result["synchronous"] = true
|
||||
return tool_json(result)
|
||||
end,
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
# src/tools/maintenance.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Operational hygiene: artifact retention and OS-memory release.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const CLEAN_ARTIFACTS_TOOL = MCPTool(
|
||||
name = "msi_clean_artifacts",
|
||||
description = """
|
||||
Prune generated artifacts (CSV/PGM/MatrixMarket outputs) from the artifact root.
|
||||
Removes task directories older than `max_age_days` and, when a byte budget is set,
|
||||
deletes oldest-first until the root fits under `max_total_bytes`. Defaults come from
|
||||
the environment variables JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS (default 7) and
|
||||
JULIA_MSI_MCP_ARTIFACT_MAX_BYTES (default 0 = disabled). The same policy is applied
|
||||
automatically at server startup.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"max_age_days" => prop("number",
|
||||
"Remove directories older than this many days (0 disables age pruning).",
|
||||
minimum=0.0),
|
||||
"max_total_bytes" => prop("number",
|
||||
"Trim oldest directories until the root is under this many bytes (0 disables).",
|
||||
minimum=0.0),
|
||||
"dry_run" => prop("boolean", "Preview what would be removed without deleting anything.",
|
||||
default=false),
|
||||
)),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => true,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
age_default, bytes_default = artifact_retention_config()
|
||||
summary = prune_artifacts!(
|
||||
max_age_days = opt_float(params, "max_age_days"; default=age_default, min=0.0, max=3650.0),
|
||||
max_total_bytes = opt_float(params, "max_total_bytes"; default=bytes_default, min=0.0, max=1.0e15),
|
||||
dry_run = opt_bool(params, "dry_run"; default=false))
|
||||
return tool_json(summary)
|
||||
end,
|
||||
)
|
||||
@@ -0,0 +1,208 @@
|
||||
# src/tools/planning.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Planning tools: validate arguments, mint a RunSpec, never run the engine.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const _PLAN_METADATA = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false)
|
||||
|
||||
const PLAN_ION_IMAGE_TOOL = MCPTool(
|
||||
name = "msi_plan_ion_image",
|
||||
description = """
|
||||
Validate an ion-image request and produce an immutable RunSpec (content hash +
|
||||
parameters bound to the current dataset). Nothing heavy runs here. Then call
|
||||
msi_execute_runspec with the returned runspec_id.
|
||||
|
||||
Validation covers: positive mass/tolerance, mask existence, image availability
|
||||
and (when analytics are ready) whether the target falls inside the global m/z
|
||||
range.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"mass" => prop("number", "Target m/z in Daltons."),
|
||||
"tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.",
|
||||
default=0.1, exclusiveMinimum=0.0),
|
||||
"mask_path" => prop("string", "Optional mask image (PNG/TIFF/BMP) restricting I/O to the ROI."),
|
||||
"output_name" => prop("string", "Artifact directory label."),
|
||||
"include_matrix" => prop("boolean", "Include the full matrix in the result when ≤ 250k pixels. Default false.",
|
||||
default=false),
|
||||
"preview_max_dim" => prop("integer", "Preview size cap. Default 96.",
|
||||
default=96, minimum=16, maximum=256),
|
||||
); required=["mass"]),
|
||||
annotations = _PLAN_METADATA,
|
||||
handler = guarded_handler() do params
|
||||
return tool_json(plan_ion_image(params))
|
||||
end,
|
||||
)
|
||||
|
||||
const PLAN_MULTIPLE_SLICES_TOOL = MCPTool(
|
||||
name = "msi_plan_multiple_slices",
|
||||
description = """
|
||||
Validate a multi-mass ion-image panel and produce a RunSpec for the engine's
|
||||
hierarchy-inversion pass (all masses in ONE read of the .ibd file). Intended for
|
||||
large panels (tens to thousands of m/z values). Then call msi_execute_runspec.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"masses" => prop("array", "Target m/z values in Daltons (duplicates removed; max 5000).",
|
||||
items=Dict{String,Any}("type" => "number"), minItems=1, maxItems=5000),
|
||||
"tolerance" => prop("number", "Mass window half-width in Daltons. Default 0.1.",
|
||||
default=0.1, exclusiveMinimum=0.0),
|
||||
"mask_path" => prop("string", "Optional mask image restricting I/O to the ROI."),
|
||||
"output_name" => prop("string", "Artifact directory label."),
|
||||
"include_matrix" => prop("boolean", "Include matrices for up to 16 slices. Default false.",
|
||||
default=false),
|
||||
"preview_max_dim" => prop("integer", "Preview size cap. Default 96.",
|
||||
default=96, minimum=16, maximum=256),
|
||||
); required=["masses"]),
|
||||
annotations = _PLAN_METADATA,
|
||||
handler = guarded_handler() do params
|
||||
return tool_json(plan_multiple_slices(params))
|
||||
end,
|
||||
)
|
||||
|
||||
const _STEPS_SCHEMA = prop("array",
|
||||
"Ordered preprocessing steps. Each item: {\"name\": \"smoothing\", \"params\": {\"method\": \"savitzky_golay\", \"window\": 9, \"order\": 2}}. " *
|
||||
"Allowed names: smoothing, baseline_correction, normalization, stabilization/intensity_transformation, peak_picking, calibration.",
|
||||
items=Dict{String,Any}(
|
||||
"type" => "object",
|
||||
"properties" => Dict{String,Any}(
|
||||
"name" => Dict{String,Any}("type" => "string"),
|
||||
"params" => Dict{String,Any}("type" => "object"),
|
||||
),
|
||||
"required" => ["name"],
|
||||
),
|
||||
minItems=1)
|
||||
|
||||
const _PREPROCESSING_PROPERTIES = Dict{String,Any}(
|
||||
"steps" => _STEPS_SCHEMA,
|
||||
"smoothing_window" => prop("integer",
|
||||
"Shorthand: add Savitzky-Golay smoothing with this window (0 disables). Default 0.",
|
||||
default=0, minimum=0, maximum=1001),
|
||||
"baseline_iterations" => prop("integer",
|
||||
"Shorthand: add SNIP baseline correction with this many iterations (0 disables). Default 0.",
|
||||
default=0, minimum=0, maximum=10000),
|
||||
"normalization" => prop("string", "Shorthand: TIC/RMS/median normalization, or none.",
|
||||
enum=["none", "tic", "rms", "median"], default="none"),
|
||||
"peak_picking" => prop("boolean",
|
||||
"Shorthand: run streaming peak detection before binning. Default true when no steps are given.",
|
||||
default=true),
|
||||
"num_bins" => prop("integer", "Number of m/z bins in the feature matrix. Default 2000.",
|
||||
default=2000, minimum=1, maximum=100000),
|
||||
"min_peaks_per_bin" => prop("integer", "Minimum peaks per bin kept. Default 3.",
|
||||
default=3, minimum=1),
|
||||
"frequency_threshold" => prop("number",
|
||||
"Keep only bins present in at least this fraction of spectra (0-1). Default 0.",
|
||||
default=0.0, minimum=0.0, maximum=1.0),
|
||||
"reference_peaks" => prop("array", "Fixed reference m/z values for calibration steps.",
|
||||
items=Dict{String,Any}("type" => "number")),
|
||||
"mask_path" => prop("string", "Optional ROI mask; only masked spectra are streamed."),
|
||||
"include_matrix" => prop("boolean",
|
||||
"Include sparse triplets in the result when nnz ≤ 20,000. Default false.",
|
||||
default=false),
|
||||
"output_name" => prop("string", "Artifact directory label. Default streaming_pipeline."),
|
||||
)
|
||||
|
||||
const PREPROCESSING_DESCRIPTION = """
|
||||
Validate a streaming preprocessing pipeline and produce a RunSpec for the
|
||||
Sprint-2 engine (`process_dataset!`): smooth → baseline → normalize → peak-pick
|
||||
→ bin, with thread-local sparse accumulators and RAM bounded by
|
||||
threads × largest spectrum. No dense matrix is ever materialised.
|
||||
|
||||
Either pass an explicit ordered `steps` array (full control) or use the
|
||||
shorthands smoothing_window / baseline_iterations / normalization /
|
||||
peak_picking. Then call msi_execute_runspec and read the Matrix Market artifact
|
||||
(or the top_bins summary) from the task result.
|
||||
"""
|
||||
|
||||
const PLAN_PREPROCESSING_TOOL = MCPTool(
|
||||
name = "msi_plan_preprocessing",
|
||||
description = PREPROCESSING_DESCRIPTION,
|
||||
input_schema = object_schema(_PREPROCESSING_PROPERTIES),
|
||||
annotations = _PLAN_METADATA,
|
||||
handler = guarded_handler() do params
|
||||
return tool_json(plan_preprocessing(params))
|
||||
end,
|
||||
)
|
||||
|
||||
const PLAN_STREAMING_PIPELINE_TOOL = MCPTool(
|
||||
name = "msi_plan_streaming_pipeline",
|
||||
description = PREPROCESSING_DESCRIPTION *
|
||||
"\n\nThis is an alias of msi_plan_preprocessing kept for workflow compatibility.",
|
||||
input_schema = object_schema(_PREPROCESSING_PROPERTIES),
|
||||
annotations = _PLAN_METADATA,
|
||||
handler = guarded_handler() do params
|
||||
return tool_json(plan_preprocessing(params))
|
||||
end,
|
||||
)
|
||||
|
||||
const PLAN_ANALYTICS_TOOL = MCPTool(
|
||||
name = "msi_plan_analytics",
|
||||
description = """
|
||||
Plan the one-time analytics scan (per-spectrum TIC, BPI, base-peak m/z, m/z
|
||||
bounds, Bloom filters). Ion-image extraction needs it; running it in the
|
||||
background avoids blocking the first slice request. The result includes a CSV
|
||||
artifact with the full stats table.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"include_rows" => prop("integer", "Rows to inline in the result. Default 20.",
|
||||
default=20, minimum=0, maximum=5000),
|
||||
"output_name" => prop("string", "Artifact directory label. Default analytics."),
|
||||
)),
|
||||
annotations = _PLAN_METADATA,
|
||||
handler = guarded_handler() do params
|
||||
return tool_json(plan_analytics(params))
|
||||
end,
|
||||
)
|
||||
|
||||
const EXECUTE_RUNSPEC_TOOL = MCPTool(
|
||||
name = "msi_execute_runspec",
|
||||
description = """
|
||||
Execute a previously planned RunSpec in a background Julia task and return a
|
||||
task_id immediately. Re-using the same runspec_id returns the existing
|
||||
queued/running/completed task unless `force=true`.
|
||||
|
||||
Then poll msi_get_task_status, fetch msi_get_task_result, or read
|
||||
msi://tasks/{task_id}/status and msi://tasks/{task_id}/result.
|
||||
|
||||
Optionally set wait_seconds (0-600) to block this call briefly, handy for small
|
||||
datasets where the job finishes in a second or two.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"runspec_id" => prop("string", "The content hash returned by a planning tool."),
|
||||
"force" => prop("boolean", "Run again even if a matching task already exists. Default false.",
|
||||
default=false),
|
||||
"wait_seconds" => prop("number",
|
||||
"Wait up to this many seconds for completion before returning. Default 0.",
|
||||
default=0.0, minimum=0.0, maximum=600.0),
|
||||
); required=["runspec_id"]),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
id = opt_string(params, "runspec_id"; default="")
|
||||
isempty(id) && throw(invalid_params("`runspec_id` is required."))
|
||||
rs = get_runspec(id)
|
||||
payload = submit_runspec(rs;
|
||||
force = opt_bool(params, "force"; default=false),
|
||||
wait_seconds = opt_float(params, "wait_seconds"; default=0.0, min=0.0, max=600.0))
|
||||
return tool_json(payload)
|
||||
end,
|
||||
)
|
||||
|
||||
const LIST_PLANS_TOOL = MCPTool(
|
||||
name = "msi_list_plans",
|
||||
description = "List recent RunSpecs (newest first) with their kind, summary and dataset id.",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"limit" => prop("integer", "Maximum plans to list. Default 20.",
|
||||
default=20, minimum=1, maximum=200),
|
||||
)),
|
||||
annotations = _PLAN_METADATA,
|
||||
handler = guarded_handler() do params
|
||||
limit = opt_int(params, "limit"; default=20, min=1, max=200)
|
||||
specs = list_runspecs(limit=limit)
|
||||
return tool_json(Dict{String,Any}(
|
||||
"plans" => [runspec_payload(rs; include_params=false) for rs in specs],
|
||||
"count" => length(specs),
|
||||
))
|
||||
end,
|
||||
)
|
||||
@@ -0,0 +1,138 @@
|
||||
# src/tools/spectra.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Random-access spectrum queries (LRU-cached in the engine).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const _SPECTRUM_PROPS = Dict{String,Any}(
|
||||
"representation" => prop("string",
|
||||
"`peaks`: local maxima only (compact, chemically meaningful). `profile`: uniformly decimated m/z grid. Default peaks.",
|
||||
enum=["peaks", "profile"], default="peaks"),
|
||||
"max_points" => prop("integer",
|
||||
"Maximum number of points returned. Default 2000.",
|
||||
default=2000, minimum=10, maximum=100000),
|
||||
"min_intensity" => prop("number",
|
||||
"Drop points with intensity below this value. Default 0.", default=0.0),
|
||||
)
|
||||
|
||||
function _spectrum_payload(data, mz, intensity; x=nothing, y=nothing, index=nothing,
|
||||
representation::AbstractString="peaks", max_points::Int=2000,
|
||||
min_intensity::Float64=0.0)
|
||||
n = length(mz)
|
||||
mz_f = Float64.(mz)
|
||||
int_f = Float64.(intensity)
|
||||
total = sum(int_f)
|
||||
bpi, base_idx = n == 0 ? (0.0, 0) : findmax(int_f)
|
||||
base_mz = n == 0 ? nothing : compact_float(mz_f[base_idx])
|
||||
|
||||
kept = Int[]
|
||||
if min_intensity > 0
|
||||
kept = findall(v -> v >= min_intensity, int_f)
|
||||
# Never return an empty spectrum because of a too-aggressive threshold.
|
||||
isempty(kept) && (kept = collect(1:n))
|
||||
else
|
||||
kept = collect(1:n)
|
||||
end
|
||||
|
||||
if representation == "profile"
|
||||
idx = kept[uniform_indices(length(kept), max_points)]
|
||||
truncated = length(kept) > max_points
|
||||
else
|
||||
sub_mz = view(mz_f, kept)
|
||||
sub_int = view(int_f, kept)
|
||||
local_idx = top_local_maxima(sub_mz, sub_int, max_points)
|
||||
idx = kept[local_idx]
|
||||
truncated = length(kept) > max_points
|
||||
end
|
||||
|
||||
points = Any[Any[compact_float(mz_f[i]), compact_float(int_f[i])] for i in idx]
|
||||
payload = Dict{String,Any}(
|
||||
"num_points" => n,
|
||||
"points_returned" => length(points),
|
||||
"truncated" => truncated,
|
||||
"representation" => representation,
|
||||
"mz_range" => n == 0 ? nothing : Any[compact_float(minimum(mz_f)), compact_float(maximum(mz_f))],
|
||||
"tic" => compact_float(total),
|
||||
"bpi" => compact_float(bpi),
|
||||
"base_peak_mz" => base_mz,
|
||||
"points" => points,
|
||||
)
|
||||
x !== nothing && (payload["coord"] = Any[x, y])
|
||||
index !== nothing && (payload["spectrum_index"] = index)
|
||||
return payload
|
||||
end
|
||||
|
||||
const GET_SPECTRUM_TOOL = MCPTool(
|
||||
name = "msi_get_spectrum_at_coord",
|
||||
description = """
|
||||
Return the spectrum at spatial coordinates (x, y) using the O(1) coordinate map
|
||||
and the engine's LRU cache. By default only local maxima ("peaks") up to
|
||||
`max_points` are returned, keeping the payload small; use representation
|
||||
"profile" for a uniformly decimated profile. Includes TIC, BPI, base-peak m/z
|
||||
and the m/z range. Coordinates are 1-based.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"x" => prop("integer", "Column coordinate (1-based)."),
|
||||
"y" => prop("integer", "Row coordinate (1-based)."),
|
||||
_SPECTRUM_PROPS...,
|
||||
); required=["x", "y"]),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
data = require_data()
|
||||
x = opt_int(params, "x"; default=nothing)
|
||||
y = opt_int(params, "y"; default=nothing)
|
||||
(x === nothing || y === nothing) && throw(invalid_params("Both `x` and `y` are required."))
|
||||
data.coordinate_map === nothing && throw(invalid_params(
|
||||
"This dataset has no coordinate map (not imaging data). Use msi_get_spectrum_by_index."))
|
||||
width, height = data.image_dims
|
||||
(1 <= x <= width && 1 <= y <= height) || throw(invalid_params(
|
||||
"Coordinates ($(x), $(y)) are outside the image bounds $(width)×$(height).";
|
||||
details=Dict("image_dims" => Any[width, height])))
|
||||
idx = data.coordinate_map[x, y]
|
||||
idx == 0 && throw(invalid_params(
|
||||
"No spectrum exists at ($(x), $(y)); this pixel is empty in the coordinate map.";
|
||||
suggested_action="Pick a coordinate inside the tissue region; msi_get_dataset_stats can help locate non-empty spectra."))
|
||||
|
||||
mz, intensity = MSI_src.GetSpectrum(data, x, y)
|
||||
rep = lowercase(String(_pget(params, "representation", "peaks")))
|
||||
rep in ("peaks", "profile") || throw(invalid_params("`representation` must be \"peaks\" or \"profile\"."))
|
||||
payload = _spectrum_payload(data, mz, intensity;
|
||||
x=x, y=y, index=idx, representation=rep,
|
||||
max_points=opt_int(params, "max_points"; default=2000, min=10, max=100_000),
|
||||
min_intensity=opt_float(params, "min_intensity"; default=0.0, min=0.0, max=Inf))
|
||||
return tool_json(payload)
|
||||
end,
|
||||
)
|
||||
|
||||
const GET_SPECTRUM_BY_INDEX_TOOL = MCPTool(
|
||||
name = "msi_get_spectrum_by_index",
|
||||
description = """
|
||||
Return the spectrum with a given linear index (1..num_spectra). Useful for
|
||||
non-imaging mzML data or when you already know the index from
|
||||
msi_get_dataset_stats. Same output shape as msi_get_spectrum_at_coord.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"index" => prop("integer", "Linear spectrum index (1-based)."),
|
||||
_SPECTRUM_PROPS...,
|
||||
); required=["index"]),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
data = require_data()
|
||||
index = opt_int(params, "index"; default=nothing)
|
||||
index === nothing && throw(invalid_params("`index` is required."))
|
||||
n = length(data.spectra_metadata)
|
||||
(1 <= index <= n) || throw(invalid_params(
|
||||
"Spectrum index $(index) is outside 1..$(n)."))
|
||||
mz, intensity = MSI_src.GetSpectrum(data, index)
|
||||
rep = lowercase(String(_pget(params, "representation", "peaks")))
|
||||
rep in ("peaks", "profile") || throw(invalid_params("`representation` must be \"peaks\" or \"profile\"."))
|
||||
payload = _spectrum_payload(data, mz, intensity;
|
||||
index=index, representation=rep,
|
||||
max_points=opt_int(params, "max_points"; default=2000, min=10, max=100_000),
|
||||
min_intensity=opt_float(params, "min_intensity"; default=0.0, min=0.0, max=Inf))
|
||||
return tool_json(payload)
|
||||
end,
|
||||
)
|
||||
@@ -0,0 +1,97 @@
|
||||
# src/tools/tasks.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Polling / result / cancellation tools for background RunSpec executions.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const TASK_STATUS_TOOL = MCPTool(
|
||||
name = "msi_get_task_status",
|
||||
description = """
|
||||
Poll a background task: status (queued/running/completed/failed/cancelled),
|
||||
progress 0-1, message, timestamps, duration, result availability, and a short
|
||||
result summary when completed. This is the tool to call in a loop after
|
||||
msi_execute_runspec.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"task_id" => prop("string", "Task identifier returned by msi_execute_runspec."),
|
||||
"include_summary" => prop("boolean",
|
||||
"Include a compact result summary when completed. Default true.", default=true),
|
||||
); required=["task_id"]),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
id = opt_string(params, "task_id"; default="")
|
||||
isempty(id) && throw(invalid_params("`task_id` is required."))
|
||||
t = get_task(id)
|
||||
return tool_json(task_status_payload(t;
|
||||
include_summary = opt_bool(params, "include_summary"; default=true)))
|
||||
end,
|
||||
)
|
||||
|
||||
const TASK_RESULT_TOOL = MCPTool(
|
||||
name = "msi_get_task_result",
|
||||
description = """
|
||||
Fetch the full structured result of a completed task: statistics, preview,
|
||||
artifact paths (CSV/PGM/MatrixMarket) and, when requested, inline matrices or
|
||||
sparse triplets. If the task is still running, returns its status plus a hint
|
||||
instead of failing.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"task_id" => prop("string", "Task identifier returned by msi_execute_runspec."),
|
||||
); required=["task_id"]),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
id = opt_string(params, "task_id"; default="")
|
||||
isempty(id) && throw(invalid_params("`task_id` is required."))
|
||||
return tool_json(task_result_payload(get_task(id)))
|
||||
end,
|
||||
)
|
||||
|
||||
const CANCEL_TASK_TOOL = MCPTool(
|
||||
name = "msi_cancel_task",
|
||||
description = """
|
||||
Request cancellation of a queued or running task. Cancellation is cooperative:
|
||||
the engine cannot interrupt an in-flight disk pass, so the task stops at the
|
||||
next checkpoint (before/after the expensive call). Queued tasks are cancelled
|
||||
immediately.
|
||||
""",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"task_id" => prop("string", "Task identifier."),
|
||||
); required=["task_id"]),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => false, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
id = opt_string(params, "task_id"; default="")
|
||||
isempty(id) && throw(invalid_params("`task_id` is required."))
|
||||
return tool_json(Dict{String,Any}(
|
||||
"cancellation_requested" => true,
|
||||
"task" => cancel_task(id),
|
||||
))
|
||||
end,
|
||||
)
|
||||
|
||||
const LIST_TASKS_TOOL = MCPTool(
|
||||
name = "msi_list_tasks",
|
||||
description = "List recent background tasks (newest first), optionally filtered by status.",
|
||||
input_schema = object_schema(Dict{String,Any}(
|
||||
"limit" => prop("integer", "Maximum tasks to return. Default 20.",
|
||||
default=20, minimum=1, maximum=64),
|
||||
"status" => prop("string", "Optional status filter.",
|
||||
enum=["queued", "running", "completed", "failed", "cancelled"]),
|
||||
)),
|
||||
annotations = Dict{String,Any}(
|
||||
"readOnlyHint" => true, "destructiveHint" => false,
|
||||
"idempotentHint" => true, "openWorldHint" => false),
|
||||
handler = guarded_handler() do params
|
||||
limit = opt_int(params, "limit"; default=20, min=1, max=64)
|
||||
status = opt_string(params, "status"; default=nothing)
|
||||
tasks = list_tasks(limit=limit, status=status)
|
||||
return tool_json(Dict{String,Any}(
|
||||
"tasks" => [task_status_payload(t; include_summary=false) for t in tasks],
|
||||
"count" => length(tasks),
|
||||
))
|
||||
end,
|
||||
)
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
# src/util.jl
|
||||
# ---------------------------------------------------------------------------
|
||||
# Small, dependency-light helpers shared across the server.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
const JSON_MIME = "application/json"
|
||||
|
||||
"""
|
||||
jsonable(x)
|
||||
|
||||
Recursively convert `x` into a value that `JSON3.write` can always encode.
|
||||
|
||||
Julia's JSON stack is not a fan of `NaN`, `Inf`, `Symbol`, `Type` or tuples, so
|
||||
we normalize them here (non-finite floats become `nothing`).
|
||||
"""
|
||||
jsonable(x::Nothing) = nothing
|
||||
jsonable(x::Bool) = x
|
||||
jsonable(x::Integer) = x
|
||||
jsonable(x::AbstractFloat) = isfinite(x) ? Float64(x) : nothing
|
||||
jsonable(x::AbstractString) = String(x)
|
||||
jsonable(x::Symbol) = String(x)
|
||||
jsonable(x::Type) = string(x)
|
||||
jsonable(x::Dates.AbstractTime) = string(x)
|
||||
jsonable(x::AbstractDict) = Dict{String,Any}(string(k) => jsonable(v) for (k, v) in x)
|
||||
jsonable(x::NamedTuple) = Dict{String,Any}(string(k) => jsonable(v) for (k, v) in pairs(x))
|
||||
jsonable(x::Tuple) = Any[jsonable(v) for v in x]
|
||||
jsonable(x::AbstractMatrix) = Any[Any[jsonable(v) for v in x[i, :]] for i in 1:size(x, 1)]
|
||||
jsonable(x::AbstractArray) = Any[jsonable(v) for v in x]
|
||||
jsonable(x) = string(x)
|
||||
|
||||
json_text(x) = JSON3.write(jsonable(x))
|
||||
|
||||
"""Wrap a payload as an MCP text content block containing compact JSON."""
|
||||
tool_json(payload) = TextContent(text=json_text(payload))
|
||||
|
||||
"""Build a JSON-Schema object schema for `input_schema`."""
|
||||
function object_schema(properties::AbstractDict; required::Vector{String}=String[])
|
||||
schema = Dict{String,Any}("type" => "object", "properties" => Dict{String,Any}(properties))
|
||||
!isempty(required) && (schema["required"] = required)
|
||||
return schema
|
||||
end
|
||||
|
||||
"""Shorthand for a JSON-Schema property."""
|
||||
prop(type::AbstractString, description::AbstractString; kwargs...) = begin
|
||||
d = Dict{String,Any}("type" => String(type), "description" => String(description))
|
||||
for (k, v) in kwargs
|
||||
d[String(k)] = v
|
||||
end
|
||||
d
|
||||
end
|
||||
|
||||
now_iso() = Dates.format(Dates.now(), "yyyy-mm-ddTHH:MM:SS.sss")
|
||||
|
||||
"""
|
||||
canonical_json(x)
|
||||
|
||||
Deterministic JSON-ish encoding used to hash `RunSpec`s. Dictionary keys are
|
||||
sorted so the digest is stable across processes (Julia randomizes string hashes
|
||||
between runs).
|
||||
"""
|
||||
canonical_json(x::Nothing) = "null"
|
||||
canonical_json(x::Bool) = x ? "true" : "false"
|
||||
canonical_json(x::Integer) = string(x)
|
||||
canonical_json(x::AbstractFloat) = isfinite(x) ? repr(Float64(x)) : "null"
|
||||
canonical_json(x::AbstractString) = JSON3.write(String(x))
|
||||
canonical_json(x::Symbol) = canonical_json(String(x))
|
||||
canonical_json(x::AbstractDict) = begin
|
||||
keys_sorted = sort!(collect(String.(keys(x))))
|
||||
parts = String["$(canonical_json(k)):$(canonical_json(x[k]))" for k in keys_sorted]
|
||||
"{" * join(parts, ",") * "}"
|
||||
end
|
||||
canonical_json(x::NamedTuple) = canonical_json(Dict(string(k) => v for (k, v) in pairs(x)))
|
||||
canonical_json(x::Union{Tuple,AbstractArray}) = "[" * join(canonical_json.(collect(x)), ",") * "]"
|
||||
canonical_json(x::Type) = canonical_json(string(x))
|
||||
canonical_json(x) = canonical_json(string(x))
|
||||
|
||||
short_hash(value::AbstractString, n::Int=16) = first(bytes2hex(SHA.sha256(value)), n)
|
||||
short_hash(value, n::Int=16) = short_hash(canonical_json(value), n)
|
||||
|
||||
"""
|
||||
safe_filename(name)
|
||||
|
||||
Turn arbitrary user text into a conservative file-name fragment.
|
||||
"""
|
||||
function safe_filename(name::AbstractString, fallback::AbstractString="output")
|
||||
cleaned = replace(String(name), r"[^A-Za-z0-9._-]+" => "_")
|
||||
cleaned = strip(cleaned, ['_', '.'])
|
||||
return isempty(cleaned) ? String(fallback) : first(cleaned, 80)
|
||||
end
|
||||
|
||||
"""Round a float for compact machine-readable output."""
|
||||
compact_float(x) = isfinite(x) ? round(Float64(x), sigdigits=6) : nothing
|
||||
|
||||
"""Aggregate statistics for an intensity matrix."""
|
||||
function matrix_stats(mat::AbstractMatrix{<:Real})
|
||||
n = length(mat)
|
||||
n == 0 && return Dict{String,Any}(
|
||||
"shape" => [0, 0], "count" => 0, "nonzero" => 0,
|
||||
"min" => nothing, "max" => nothing, "mean" => nothing,
|
||||
"median" => nothing, "p95" => nothing, "sum" => 0.0,
|
||||
"base_peak_coord" => nothing, "centroid_coord" => nothing,
|
||||
)
|
||||
|
||||
vals = Float64.(vec(mat))
|
||||
finite_vals = filter(isfinite, vals)
|
||||
nz_count = count(>(0.0), finite_vals)
|
||||
vmax = isempty(finite_vals) ? 0.0 : maximum(finite_vals)
|
||||
|
||||
base_peak_coord = nothing
|
||||
centroid = nothing
|
||||
if vmax > 0
|
||||
idx = argmax(mat)
|
||||
base_peak_coord = [idx[2], idx[1]] # (x, y)
|
||||
total = sum(vals)
|
||||
ys, xs = size(mat)
|
||||
sx = 0.0
|
||||
sy = 0.0
|
||||
for y in 1:ys, x in 1:xs
|
||||
v = Float64(mat[y, x])
|
||||
isfinite(v) || continue
|
||||
sx += v * x
|
||||
sy += v * y
|
||||
end
|
||||
if total > 0
|
||||
centroid = [compact_float(sx / total), compact_float(sy / total)]
|
||||
end
|
||||
end
|
||||
|
||||
finite_vals_sorted = sort!(finite_vals)
|
||||
median = isempty(finite_vals_sorted) ? nothing :
|
||||
(length(finite_vals_sorted) % 2 == 1 ? finite_vals_sorted[(end + 1) ÷ 2] :
|
||||
(finite_vals_sorted[end ÷ 2] + finite_vals_sorted[end ÷ 2 + 1]) / 2)
|
||||
p95 = isempty(finite_vals_sorted) ? nothing :
|
||||
finite_vals_sorted[clamp(round(Int, 0.95 * length(finite_vals_sorted)), 1, length(finite_vals_sorted))]
|
||||
|
||||
return Dict{String,Any}(
|
||||
"shape" => [size(mat, 2), size(mat, 1)], # [width, height]
|
||||
"count" => n,
|
||||
"nonzero" => nz_count,
|
||||
"min" => compact_float(minimum(finite_vals; init=0.0)),
|
||||
"max" => compact_float(vmax),
|
||||
"mean" => compact_float(sum(finite_vals) / max(length(finite_vals), 1)),
|
||||
"median" => compact_float(median === nothing ? 0.0 : median),
|
||||
"p95" => compact_float(p95 === nothing ? 0.0 : p95),
|
||||
"sum" => compact_float(sum(finite_vals)),
|
||||
"base_peak_coord" => base_peak_coord,
|
||||
"centroid_coord" => centroid,
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
downsample_matrix(mat; max_dim=96)
|
||||
|
||||
Average-pool `mat` down to at most `max_dim` in either dimension. Returns the
|
||||
reduced matrix (kept as a full matrix so callers can render it directly).
|
||||
"""
|
||||
function downsample_matrix(mat::AbstractMatrix{<:Real}; max_dim::Int=96)
|
||||
h, w = size(mat)
|
||||
(h == 0 || w == 0 || (h <= max_dim && w <= max_dim)) && return Matrix{Float64}(mat)
|
||||
max_dim = max(1, max_dim)
|
||||
factor = max(ceil(Int, h / max_dim), ceil(Int, w / max_dim), 1)
|
||||
out_h = max(1, fld(h, factor))
|
||||
out_w = max(1, fld(w, factor))
|
||||
out = zeros(Float64, out_h, out_w)
|
||||
for oy in 1:out_h, ox in 1:out_w
|
||||
y0 = (oy - 1) * factor + 1
|
||||
y1 = min(oy * factor, h)
|
||||
x0 = (ox - 1) * factor + 1
|
||||
x1 = min(ox * factor, w)
|
||||
acc = 0.0
|
||||
cnt = 0
|
||||
@inbounds for y in y0:y1, x in x0:x1
|
||||
v = Float64(mat[y, x])
|
||||
if isfinite(v)
|
||||
acc += v
|
||||
cnt += 1
|
||||
end
|
||||
end
|
||||
out[oy, ox] = cnt == 0 ? 0.0 : acc / cnt
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
"""Nearest/bilinear-free preview with row-major [y][x] nesting for JSON."""
|
||||
function preview_matrix(mat::AbstractMatrix{<:Real}; max_dim::Int=96)
|
||||
reduced = downsample_matrix(mat; max_dim=max_dim)
|
||||
# Round to 4 significant digits to keep payloads small.
|
||||
rows = [Any[compact_float(v) for v in reduced[y, :]] for y in 1:size(reduced, 1)]
|
||||
return Dict{String,Any}(
|
||||
"dims" => [size(reduced, 2), size(reduced, 1)],
|
||||
"rows" => rows,
|
||||
"scale" => "linear; 0 = no signal; averaged pooling from the full matrix",
|
||||
)
|
||||
end
|
||||
|
||||
"""
|
||||
top_local_maxima(mz, intensity, limit)
|
||||
|
||||
Return at most `limit` local maxima sorted by m/z, useful for compact spectrum
|
||||
payloads. Falls back to the global top intensities if no local maxima exist.
|
||||
"""
|
||||
function top_local_maxima(mz::AbstractVector, intensity::AbstractVector, limit::Int)
|
||||
n = length(mz)
|
||||
limit = max(1, limit)
|
||||
candidates = Int[]
|
||||
@inbounds for i in 1:n
|
||||
v = intensity[i]
|
||||
left = i == 1 ? -Inf : intensity[i - 1]
|
||||
right = i == n ? -Inf : intensity[i + 1]
|
||||
if v >= left && v >= right
|
||||
push!(candidates, i)
|
||||
end
|
||||
end
|
||||
if isempty(candidates)
|
||||
candidates = collect(1:n)
|
||||
end
|
||||
# Partial sort candidates by intensity (descending), then keep m/z order.
|
||||
order = sortperm(candidates; by=i -> -Float64(intensity[i]))
|
||||
selected = candidates[order[1:min(limit, length(order))]]
|
||||
sort!(selected; by=i -> Float64(mz[i]))
|
||||
return selected
|
||||
end
|
||||
|
||||
"""Uniformly decimate an index range to at most `limit` indices."""
|
||||
function uniform_indices(n::Int, limit::Int)
|
||||
n <= 0 && return Int[]
|
||||
limit = max(1, limit)
|
||||
n <= limit && return collect(1:n)
|
||||
step = n / limit
|
||||
return unique([clamp(round(Int, 1 + (k - 1) * step), 1, n) for k in 1:limit])
|
||||
end
|
||||
@@ -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