From d4ae90c1d7ebdba4d7233eddb53dd62e6779f2a0 Mon Sep 17 00:00:00 2001 From: Pixelguy14 Date: Wed, 25 Nov 2026 14:06:35 -0600 Subject: [PATCH] Test with a prompt for MCP successful, readme translated --- .gitignore | 4 + README.md | 600 ++++++++++++++++++++++++++--------------------------- 2 files changed, 303 insertions(+), 301 deletions(-) diff --git a/.gitignore b/.gitignore index 61fd8ba..48fc544 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,7 @@ build/ # Python __pycache__/ *.pyc + +# Tests +tests_ignore/ +opencode.json \ No newline at end of file diff --git a/README.md b/README.md index 5683705..0517ac8 100644 --- a/README.md +++ b/README.md @@ -1,153 +1,151 @@ # 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. +A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server for the +**Mass Spectrometry Imaging** engine [JuliaMSI](../JuliaMSI). It exposes the persistent +session, ion-image extraction, streaming preprocessing pipeline and random-access +spectrum queries as tools that an LLM (Claude Desktop, VS Code/Copilot, OpenCode, etc.) +can invoke reproducibly. -> 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. +> Status: **Phases 1–3 of the plan implemented and tested** (persistent session, +> planning + async execution layer, full tools/resources/prompts catalog). Phase 4 +> (Streamable HTTP + memory resilience) is also integrated; production hardening +> (TLS, native task notifications) is the remaining polish. --- -## 1. Arquitectura +## 1. Architecture ``` ┌───────────────────────────────────────────────────────────────────────────┐ -│ Cliente LLM (host MCP) │ +│ LLM client (MCP host) │ │ Claude Desktop · VS Code · OpenCode · Cursor │ └───────────────────────────────────┬───────────────────────────────────────┘ - │ JSON-RPC 2.0 (stdio o Streamable HTTP) + │ JSON-RPC 2.0 (stdio or Streamable HTTP) ┌───────────────────────────────────▼───────────────────────────────────────┐ -│ Servidor MCP — JuliaMSI_MCP │ +│ MCP server — JuliaMSI_MCP │ │ │ -│ SessionState (Ref lógica) RunSpec registry Task registry │ -│ ─ MSIData persistente ─ hash de contenido ─ Threads.@spawn │ -│ ─ lock + dataset_id ─ validación ─ polling/cancel │ +│ SessionState (logical Ref) RunSpec registry Task registry │ +│ ─ persistent MSIData ─ content hash ─ Threads.@spawn │ +│ ─ lock + dataset_id ─ validation ─ polling/cancel │ │ │ -│ Tools síncronas · Tools de planificación · Tools de ejecución │ -│ Resources msi:// · Prompts de flujo │ +│ Sync tools · Planning tools · Execution tools │ +│ Resources msi:// · Workflow prompts │ └───────────────────────────────────┬───────────────────────────────────────┘ - │ llamadas directas en proceso (sin IPC) + │ direct in-process calls (no IPC) ┌───────────────────────────────────▼───────────────────────────────────────┐ -│ Motor JuliaMSI (src/ de JuliaMSI) │ -│ imzML + .cache binaria · mmap + madvise · Bloom filters · LRU │ +│ JuliaMSI engine (JuliaMSI src/) │ +│ imzML + binary .cache · mmap + madvise · Bloom filters · LRU │ │ get_mz_slice · get_multiple_mz_slices · process_dataset! │ └───────────────────────────────────────────────────────────────────────────┘ ``` -### Las cuatro capas +### The four layers -| 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. | +| Layer | File | Responsibility | +|-------|------|----------------| +| **Session** | `src/session.jl` | Open/close `MSIData`, keep it alive between calls, compute `dataset_id`, return memory to the OS (`GC.gc(true)` + `malloc_trim`). | +| **Planning** | `src/runspec.jl` | Validate arguments and mint an immutable `RunSpec` with a deterministic SHA-256 hash, bound to the `dataset_id`. No computation runs here. | +| **Execution** | `src/tasks.jl` | Launch the RunSpec in a `Threads.@spawn`, track state/progress, cooperative cancellation, polling and results. | +| **Artifacts** | `src/artifacts.jl` | Full matrices go to disk (CSV, PGM, Matrix Market); the LLM receives statistics and a downsampled *preview*. | -### Decisiones de diseño relevantes +### Key design decisions -- **`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. +- **Clean `stdout` for stdio.** The JuliaMSI engine prints debug traces with `println`; + the server redirects the global `stdout` to `stderr` and hands the transport the + original `stdout` handle (`install_output_guard`), so the JSON-RPC channel is never + corrupted. +- **One dataset at a time.** This is the natural `MSIData` model; opening another one + closes and cleans the previous. Plans are bound to the `dataset_id` and rejected if + the dataset changes. +- **Plan ≠ execute.** The LLM receives an auditable `runspec_id`; re-running the same + plan reuses the existing task unless `force=true`. +- **Bounded results.** A 2000×2000 matrix is ~32 MB of JSON. Results carry `stats`, + `preview` (≤256 px) and artifact paths instead; `include_matrix` is opt-in and capped. +- **Memory.** `msi_close_dataset` and the streaming/analytics tasks run + `GC.gc(true/false)` + `malloc_trim(0)` on Linux to return glibc arenas to the kernel. --- -## 2. Requisitos +## 2. Requirements -- 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`). +- Julia **1.11+** (tested on 1.11.7). +- A JuliaMSI engine checkout with its `Project.toml` (default `../JuliaMSI`). +- JuliaMSI dependencies installed (resolved by `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. +The integration uses a path dependency (`[sources] MSI_src = {path = "../JuliaMSI"}`), +so the engine code is **not copied**: changes in JuliaMSI take effect when the server is +restarted. --- -## 3. Instalación +## 3. Installation ```bash -cd /home/pixel/Documents/2026/JuliaMSI_MCP +cd /path/to/JuliaMSI_MCP -# Opción A: layout hermano por defecto (../JuliaMSI) +# Option A: default sibling layout (../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 +# Option B: explicit path to the engine checkout +JULIA_MSI_PATH=/path/to/JuliaMSI julia --project=. scripts/setup.jl ``` -`scripts/setup.jl` hace `Pkg.develop(path=...)`, `instantiate` y `precompile`. +`scripts/setup.jl` runs `Pkg.develop(path=...)`, `instantiate` and `precompile`. -### Proyecto autocontenido (opcional) +### Self-contained project (optional) -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: +The integration uses the local engine checkout (`../JuliaMSI`) so engine changes are +reflected without duplicating ~10,000 lines. To distribute the server without the rest +of the engine repo: ```bash mkdir -p vendor/JuliaMSI cp -r ../JuliaMSI/src ../JuliaMSI/Project.toml vendor/JuliaMSI/ -# edita [sources] en Project.toml: +# edit [sources] in 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. +You can also point at any engine remote with +`Pkg.add(url="https://github.com/Pixelguy14/Julia_msi_GUI")` (or the Codeberg mirror) +and use the `MSI_src` name in `[deps]`, though the path dependency is the most convenient +during development. -### Parches recomendados para JuliaMSI +### Recommended patches for 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`: +Three engine bugs surfaced during validation (including real datasets). The patches live +in `patches/` and are **already applied** to the local `../JuliaMSI` checkout: -1. **`juliamsi-fix-nonmmap.patch`** — 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. +1. **`juliamsi-fix-nonmmap.patch`** — non-mmap reading: + - `load_imzml_lazy` built a temporary `MSIData` to write the cache while sharing the + real handle vector; its finalizer closed the dataset's handles + (`Bad file descriptor`). It now uses `IO[]` for the temporary object. + - `_iterate_uncompressed_fast` read into `Vector{Float64}` buffers even when the + `.ibd` was Float32, consuming twice the bytes. It now uses the source's real type. +2. **`juliamsi-fix-mask-io.patch`** — ROI masks: + - `load_and_prepare_mask` called `Gray.(img)` and failed on TIFFs that load as + `TiffImages.WidePixel` (e.g. the HR2MSI optical reference image). It now uses the + embedded color channel. + - `process_image_pipeline` built an even-sized structuring element from the default + `smoothing=2`, which ImageMorphology rejects (`connectivity must be odd-sized`). + It now normalizes to an odd size ≥ 3. -**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: +**Upstream status (Nov 2026):** all three fixes are part of engine commit `bc71b9c`, +present on the `rel/Windows_Mac_Recompatibility` branch (Codeberg, GitHub, nube-gran) +and on **GitHub** `main`. **Codeberg** `main` and **nube-gran** `main` do not include +them yet, so the patches remain useful as a fallback for those default branches: ```bash -cd /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 +cd /path/to/JuliaMSI +git apply /path/to/JuliaMSI_MCP/patches/juliamsi-fix-nonmmap.patch +git apply /path/to/JuliaMSI_MCP/patches/juliamsi-fix-mask-io.patch ``` -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. +Recommendation: merge `rel/Windows_Mac_Recompatibility` into `main` on Codeberg and +nube-gran so the `patches/` folder can eventually be removed. The mmap path (default) is +unaffected by the first patch. -Verificación rápida: +Quick check: ```bash julia --project=. -e 'using JuliaMSI_MCP; println(JuliaMSI_MCP.SERVER_VERSION)' @@ -155,16 +153,16 @@ julia --project=. -e 'using JuliaMSI_MCP; println(JuliaMSI_MCP.SERVER_VERSION)' --- -## 4. Ejecución +## 4. Running -### stdio (recomendado para escritorio) +### stdio (recommended for desktop) ```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. +`--threads=auto` matters: the engine parallelizes spectra and the server launches +background tasks. ### Streamable HTTP @@ -172,151 +170,150 @@ en segundo plano. 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: +By default it listens on localhost only, without authentication. To protect the endpoint, +require a shared token: ```bash julia --project=. --threads=auto bin/run_server.jl --http --port 3000 --token S3CR3T -# o bien: JULIA_MSI_MCP_TOKEN=S3CR3T ... --http +# or: 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). +Clients must send `Authorization: Bearer S3CR3T`. To expose it beyond the machine, put a +TLS reverse proxy in front (a shared token does **not** replace TLS). -### Arranque rápido con sysimage (AOT, Fase 4) +### Fast startup with a sysimage (AOT, Phase 4) -Para eliminar el JIT de la primera llamada, compila una imagen de sistema: +To eliminate the first-call JIT, build a system image: ```bash -julia scripts/build_sysimage.jl # genera build/sys_mcp.so +julia scripts/build_sysimage.jl # produces build/sys_mcp.so julia --project=. --threads=auto --sysimage=build/sys_mcp.so bin/run_server.jl ``` -`scripts/build_sysimage.jl` 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. +`scripts/build_sysimage.jl` creates a throwaway environment, develops the engine and +`JuliaMSI_MCP`, and runs `scripts/sysimage_warmup.jl` (open, spectrum, slices, streaming, +tool registration) to bake in the native code. The build takes several minutes and the +`.so` is machine-specific. -### Configuración de clientes (cópialas a la ubicación que espera cada cliente): +### Client configuration (copy to the location each client expects): -- `config/claude_desktop_config.json` → Claude Desktop (`mcpServers`). En Linux: - `~/.config/Claude/claude_desktop_config.json`; en Windows: +- `config/claude_desktop_config.json` → Claude Desktop (`mcpServers`). On Linux: + `~/.config/Claude/claude_desktop_config.json`; on Windows: `%APPDATA%\Claude\claude_desktop_config.json`. -- `config/vscode_mcp.json` → VS Code / Copilot. 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. +- `config/vscode_mcp.json` → VS Code / Copilot. Copy it as `.vscode/mcp.json` in the + workspace (or run *MCP: Add Server*). +- `config/opencode.json` → OpenCode V2 (key `mcp.servers`). Copy it as `opencode.json` + at the project root, or merge it into `~/.config/opencode/opencode.json` for global use. -Todas asumen este layout: +All assume this layout (adjust the absolute paths to your checkout): ``` -julia --project=/home/pixel/Documents/2026/JuliaMSI_MCP --threads=auto \ - /home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl +julia --project=/path/to/JuliaMSI_MCP --threads=auto \ + /path/to/JuliaMSI_MCP/bin/run_server.jl ``` -Variables de entorno útiles: +Useful environment variables: -| Variable | Efecto | +| Variable | Effect | |----------|--------| -| `JULIA_NUM_THREADS=auto` | Hilos del motor (también `--threads=auto`). | -| `JULIA_MSI_MCP_ARTIFACTS=/ruta` | Directorio de artefactos (por defecto `/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). | +| `JULIA_NUM_THREADS=auto` | Engine threads (also `--threads=auto`). | +| `JULIA_MSI_MCP_ARTIFACTS=/path` | Artifact directory (default `/artifacts`). | +| `JULIA_MSI_MCP_ARTIFACT_MAX_AGE_DAYS` | Artifact lifetime before pruning at startup (default 7). | +| `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` | Total artifact budget in bytes (default 0 = unlimited). | +| `JULIA_MSI_MCP_TOKEN` | Shared token for `--http` (same as `--token`). | +| `JULIA_MSI_MCP_KEEP_STDOUT=1` | Disable the stdout redirect (local debugging only). | --- -## 5. Catálogo de herramientas +## 5. Tool catalog -### Sesión y datos +### Session and data -| Tool | Tipo | Descripción | +| Tool | Type | Description | |------|------|-------------| -| `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). | +| `msi_open_dataset` | sync | Open/switch an imzML/mzML dataset; creates or uses `.cache`; optional `precompute_analytics`. | +| `msi_close_dataset` | sync | Closes handles, empties the cache and returns RAM to the OS. | +| `msi_dataset_info` | sync | Session state (dimensions, m/z range, mmap, RSS, threads). | +| `msi_get_dataset_stats` | sync | Per-spectrum statistics (TIC/BPI/NumPoints/m/z range). | -### Espectros +### Spectra -| Tool | Tipo | Descripción | +| Tool | Type | Description | |------|------|-------------| -| `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). | +| `msi_get_spectrum_at_coord` | sync | Spectrum at `(x, y)` via the LRU cache. `representation=peaks` or `profile`. | +| `msi_get_spectrum_by_index` | sync | Spectrum by linear index (useful for non-imaging mzML). | -### Imágenes iónicas +### Ion images -| Tool | Tipo | Descripción | +| Tool | Type | Description | |------|------|-------------| -| `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). | +| `msi_get_mz_slice` | sync | Immediate ion image for one mass. | +| `msi_get_multiple_mz_slices` | sync | Up to 50 masses in a single pass (hierarchy inversion). | +| `msi_plan_ion_image` | planning | Validates and mints a `runspec_id` for one mass. | +| `msi_plan_multiple_slices` | planning | Mints a `runspec_id` for a panel of up to 5000 masses (1 I/O pass). | -### Preprocesamiento y analíticas +### Preprocessing and analytics -| Tool | Tipo | Descripción | +| Tool | Type | Description | |------|------|-------------| -| `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. | +| `msi_plan_preprocessing` | planning | Streaming pipeline (`process_dataset!`) → sparse matrix. | +| `msi_plan_streaming_pipeline` | planning | Alias of the above. | +| `msi_plan_analytics` | planning | TIC/BPI/Bloom-filter scan in the background. | -### Ejecución asíncrona +### Async execution -| Tool | Tipo | Descripción | +| Tool | Type | Description | |------|------|-------------| -| `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. | +| `msi_execute_runspec` | execution | Launches the plan in the background and returns a `task_id` (reuses tasks unless `force`). | +| `msi_get_task_status` | sync | State, progress, timings and summary. | +| `msi_get_task_result` | sync | Full result (stats, preview, artifacts, opt-in matrices). | +| `msi_cancel_task` | sync | Cooperative cancellation. | +| `msi_list_tasks` | sync | List recent tasks (filter by status). | +| `msi_list_plans` | sync | List recent RunSpecs. | -### Mantenimiento +### Maintenance -| Tool | Tipo | Descripción | +| Tool | Type | Description | |------|------|-------------| -| `msi_clean_artifacts` | síncrona | Poda artefactos por antigüedad y/o presupuesto de bytes (con `dry_run`). | +| `msi_clean_artifacts` | sync | Prune artifacts by age and/or byte budget (with `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. | +| URI | Content | +|-----|---------| +| `msi://dataset/metadata` | Active session metadata. | +| `msi://dataset/stats` | Aggregates + first 100 rows (does not trigger the scan). | +| `msi://tasks/{task_id}/status` | Task status. | +| `msi://tasks/{task_id}/result` | Task result. | ### Prompts -| Prompt | Uso | +| Prompt | Use | |--------|-----| | `analyze_region_of_interest` | Forces confirmation of mass, tolerance and mask before planning. | | `standard_pipeline` | Open → plan → execute → poll → summarize workflow. | | `diagnose_task` | Interprets task states/errors and proposes corrective actions. | -> 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`, +> Prompts (and their content) are in English, the project's primary language. Earlier +> compendium names: `analizar_region_de_interes`, `pipeline_estandar`, > `diagnostico_de_tarea`. --- -## 6. Flujo típico (lo que hace el LLM) +## 6. Typical flow (what the LLM does) ```text -msi_open_dataset(file_path="/datos/muestra.imzML", precompute_analytics=false) +msi_open_dataset(file_path="/data/sample.imzML", precompute_analytics=false) │ - ├─(dataset grande)─► msi_plan_analytics ─► msi_execute_runspec ─► poll + ├─(large dataset)─► msi_plan_analytics ─► msi_execute_runspec ─► poll │ -msi_plan_ion_image(mass=756.55, tolerance=0.1, mask_path="/datos/roi.png") +msi_plan_ion_image(mass=756.55, tolerance=0.1, mask_path="/data/roi.png") │ → {"runspec_id": "a1b2…", "kind": "ion_image", …} ▼ msi_execute_runspec(runspec_id="a1b2…", wait_seconds=0) │ → {"task_id": "uuid", "status": "queued"} ▼ -msi_get_task_status(task_id="uuid") # repetir hasta completed +msi_get_task_status(task_id="uuid") # repeat until completed ▼ msi_get_task_result(task_id="uuid") │ → stats, preview, artifacts.csv/pgm @@ -324,7 +321,7 @@ msi_get_task_result(task_id="uuid") msi_close_dataset() ``` -Resultado de una imagen iónica (resumido): +Ion-image result (abridged): ```json { @@ -349,10 +346,10 @@ Resultado de una imagen iónica (resumido): --- -## 7. Manejo de errores +## 7. Error handling -Los handlers nunca tumban el bucle JSON-RPC: toda excepción se convierte en -`CallToolResult(is_error=true)` con este cuerpo: +Handlers never crash the JSON-RPC loop: every exception becomes +`CallToolResult(is_error=true)` with this body: ```json { @@ -366,95 +363,96 @@ Los handlers nunca tumban el bucle JSON-RPC: toda excepción se convierte en } ``` -| 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 | +| Type | Code | Typical origin | Suggested action | +|------|------|----------------|------------------| +| `InvalidParams` | `-32602` | mass/tolerance/mask/coordinates | fix arguments | +| `SessionError` | `-32010` | no dataset open | `msi_open_dataset` | +| `ResourceNotFound` | `-32002` | unknown task_id/URI | list tasks/plans | +| `InternalError` | `-32603` | I/O, corrupt `.cache`, OOM | check stderr; delete `.cache`; use streaming | --- -## 8. Pruebas +## 8. Testing ```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: +The suite generates a **valid synthetic imzML** (4×3, Float32, 5 peaks/spectrum, one +strong peak at 300 Da) and covers: -- 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. +- utilities (canonical hash, safe JSON, preview, statistics), +- session open/close and `.cache`, +- spectrum by coordinate and index, +- synchronous single and multiple ion-image extraction, +- plan validation and dataset binding, +- the full async flow (plan → execute → status → result), +- analytics and the streaming pipeline, +- resources, prompts and dataset switching, +- non-mmap I/O regression, and artifact retention. -Resultado actual: **107 tests OK** (~22 s en un equipo de desarrollo). +Current result: **107 tests OK** (~22 s on a dev machine). -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). +There is also an end-to-end stdio smoke test in `test/smoke_stdio.py` (generates the +synthetic dataset, launches the server and walks initialize → tools → plan → execute → +result). --- -## 9. Validación con datasets reales +## 9. Validation with real datasets -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). +Validated against the `Cinvestav_2025/Analisis` data (12 threads, 14 GB RAM, local disk; +timings vary with page cache). -### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imagen) +### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imaging) -| 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 | +| Metric | Result | +|--------|--------| +| Spectra / dimensions | 34,840 / 260 × 134 | +| Size | `.ibd` 815 MB, `.imzML` 56 MB (with `.cache`) | +| Open | 2.0–3.5 s using the binary `.cache` | +| Analytics scan | 6.8–12.9 s | +| Spectrum `(130,67)` | 966 points, BPI 4,026.3, base peak 798.5387 | +| Ion image `798.5387 ± 0.15` | 1.8 s, max 14,274.8, 21,920 pixels with signal, base peak (167,105) | +| 4–5 masses in one pass | 2.2 s without mask / 3.7 s with mask | +| ROI mask (optical → PGM) | 36% of the area; the optical TIFF directly gives ~43% after the patch | +| Streaming (12,571 masked spectra) | 3.9 s; matrix 420 × 34,840; 1,424,362 nnz; `.mtx` 44 MB | +| Streaming (34,840 spectra, no mask) | 5.75 s engine (10.3 s wall); matrix 500 × 34,840; 3,822,821 nnz (78.1%); ~61 MB RAM | +| Most intense bins | 580.6, 443.8, 716.2 m/z | -> 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. +> The difference between "engine" and "wall" on the first run is mostly first-call JIT of +> the analytics/streaming path plus 1 s polling granularity; later calls approach engine +> time. That is the main argument for the Phase-4 AOT sysimage. -El pipeline streaming mantiene la RAM acotada: incluso con 34 840 espectros, el motor -solo conserva un espectro por hilo y ensambla una `SparseMatrixCSC`. +The streaming pipeline keeps RAM bounded: even with 34,840 spectra, the engine keeps one +spectrum per thread and assembles a `SparseMatrixCSC`. -### `mzML/` (perfiles no-imaging) +### `mzML/` (non-imaging profiles) -| Archivo | Espectros | Apertura | Analíticas | -|---------|-----------|----------|------------| +| File | Spectra | Open | Analytics | +|------|--------:|-----:|----------:| | `T9_A1.mzML` | 10 | 0.06 s | 0.15–1.2 s | | `Cytochrome_C.mzML` | 32 | 0.07 s | 0.15 s | | `Col_1.mzML` | 800 | 0.17 s | 0.07 s | -- `msi_get_spectrum_by_index` 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. +- `msi_get_spectrum_by_index` and `msi_get_dataset_stats` work correctly. +- Imaging tools (`msi_get_mz_slice`, `msi_plan_ion_image`, …) are rejected with + `InvalidParams` because the dataset has no `coordinate_map` and no spatial dimensions. -### Reproducir +### Reproduce ```bash -# Smoke test genérico (detecta imaging vs. mzML automáticamente) -python3 test/smoke_stdio.py --dataset /ruta/archivo.imzML +# Generic smoke test (auto-detects imaging vs. mzML) +python3 test/smoke_stdio.py --dataset /path/file.imzML -# Validación más completa (analíticas + ion image + múltiples masas + streaming opcional) +# Fuller validation (analytics + ion image + multiple masses + optional streaming) JULIA_MSI_MCP_REAL_STREAMING=1 julia --project=. test/real_datasets.jl \ - /ruta/archivo.imzML /ruta/archivo.mzML + /path/file.imzML /path/file.mzML ``` --- -## 10. Estructura del repositorio +## 10. Repository layout ``` JuliaMSI_MCP/ @@ -464,94 +462,94 @@ JuliaMSI_MCP/ ├── 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) +│ ├── build_sysimage.jl # AOT system image (Phase 4) +│ └── sysimage_warmup.jl # precompile workload +├── patches/ # fallback engine patches (see §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 +│ ├── JuliaMSI_MCP.jl # module and includes +│ ├── util.jl # safe JSON, hashes, previews +│ ├── errors.jl # MCPToolError + JSON-RPC mapping +│ ├── session.jl # persistent MSIData + cleanup +│ ├── runspec.jl # planning and validation +│ ├── tasks.jl # async execution + registry +│ ├── artifacts.jl # CSV/PGM/MatrixMarket + retention │ ├── resources.jl # msi:// -│ ├── prompts.jl # flujos guiados (inglés) +│ ├── prompts.jl # workflow prompts (English) │ ├── server.jl # build_server / run_stdio / run_http (+ token) │ └── tools/ # dataset, spectra, imaging, planning, tasks, maintenance ├── config/ # Claude Desktop, VS Code, OpenCode ├── test/ -│ ├── synthetic.jl # generador imzML de prueba +│ ├── synthetic.jl # test imzML generator │ ├── 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) +│ ├── smoke_stdio.py # end-to-end stdio smoke test +│ └── real_datasets.jl # reproducible real-dataset validation +├── build/ # generated sysimage (git-ignored) +└── artifacts/ # results (git-ignored) ``` --- -## 11. Relación con el compendio arquitectónico +## 11. Relation to the architectural compendium -| 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 | +| Compendium section | MCP implementation | +|--------------------|--------------------| +| A.1 `MSIData`, LRU, atomics | persistent session + `GetSpectrum` | +| A.2 slices / hierarchy inversion | `msi_get_multiple_mz_slices`, `msi_plan_multiple_slices` | +| A.3 dual parser + `.cache` | `msi_open_dataset` (delegated to the engine) | +| A.4 handle pool | `--threads=auto`; the engine opens one handle per thread | +| A.5 Bloom filters | rejection applied by `get_mz_slice` | +| A.6 mmap + `madvise` | `use_mmap=true` and bounded `preview` | | A.7–A.8 preprocessing/streaming | `msi_plan_preprocessing`, `process_dataset!` | -| A.10 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 | +| A.10 ROI masks | `mask_path` in plans and slices | +| A.11 AOT sysimage | `scripts/build_sysimage.jl` + `--sysimage` (see §4) | +| A.12 `malloc_trim` | `release_os_memory!` on close and heavy tasks | +| B.1 STDIO/HTTP | `run_stdio`, `run_http` (optional shared token) | +| B.2 tools | 20 registered tools | | B.3 resources | `msi://dataset/*`, `msi://tasks/*` | -| B.4 errores/cleanup | `errors.jl` + hooks + retención de artefactos | +| B.4 errors/cleanup | `errors.jl` + hooks + artifact retention | --- -## 12. Solución de problemas +## 12. Troubleshooting -| 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 `.imzML.cache`; el parser XML se regenera. | -| Error de permisos al abrir | El motor escribe `.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). | +| Symptom | Cause / fix | +|---------|-------------| +| `GLMakie failed to precompile` on instantiate | GLMakie is a dependency of the engine's GUI project; the `MSI_src` core (and therefore the MCP server) no longer loads it thanks to `PlottingStubs.jl`. Harmless for the server. | +| Server starts but the client sees no tools | Make sure the client launches `bin/run_server.jl` with `--project=...` and `--threads=auto`; startup logs go to `stderr`. | +| `Dataset file not found` / `.ibd not found` | Use absolute paths and keep `.imzML` + `.ibd` with the same basename. | +| First slice is slow | The analytics scan is running. Use `msi_plan_analytics` + `msi_execute_runspec` in the background. | +| `.cache` corrupt after a crash | Delete `.imzML.cache`; the XML parser regenerates it. | +| Permission error on open | The engine writes `.imzML.cache` next to the dataset; copy `.imzML`+`.ibd` to a writable directory. | +| RSS does not drop after close | `msi_close_dataset` already calls `malloc_trim` on Linux; on musl/Alpine it does not exist and the kernel reclaims memory under pressure. | +| `stdout` pollution while debugging | Don't `println` in the server process; use `stderr` or `@info`. `JULIA_MSI_MCP_KEEP_STDOUT=1` disables the guard (local only). | -## 13. Limitaciones conocidas y próximos pasos +## 13. Known limitations and next steps -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. +1. **One dataset per process** (by engine design). Multiplexing datasets would need a + session pool or one process per dataset. +2. **Cooperative cancellation**: an in-flight `pread`/disk pass cannot be interrupted; + the task stops at the next checkpoint. +3. **`msi_get_dataset_stats` and sync slices can block** during the first analytics scan. + For large datasets, use `msi_plan_analytics` + execution. +4. **Native MCP tasks (SEP-1686/2663)**: the server uses its own task registry, compatible + with any client. `task_support=:optional` and `task_detach` can be added to publish + state via the SDK's `tasks/get`. +5. **Baseline memory footprint**: `using MSI_src` no longer loads the plotting stack + (CairoMakie/GLMakie) thanks to `PlottingStubs.jl`, but `Images` (for masks) still + leaves the process at ~1.6 GB RSS. Splitting the data core from `ImageProcessing` + would reduce startup and RAM. +6. **TLS**: the HTTP shared token protects the endpoint, but transport encryption still + requires a TLS reverse proxy (Caddy/nginx). -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`). +Resolved in Phase 4: artifact retention (`msi_clean_artifacts` + startup policy), HTTP +shared-token auth, the AOT sysimage script (`scripts/build_sysimage.jl`) and CI +(`.github/workflows/ci.yml`). -Roadmap sugerido (restante): +Remaining roadmap: -- [ ] Publicar tareas/progreso por el mecanismo nativo de MCP (`task_support=:optional`, +- [ ] Publish tasks/progress via the native MCP mechanism (`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. +- [ ] `notifications/resources/updated` for `msi://tasks/{id}/status`. +- [ ] Verify startup with `--sysimage=build/sys_mcp.so` and measure the TTFX improvement. +- [ ] CI unit/integration on a real reference dataset (repo benchmarks). +- [ ] `Dockerfile`/systemd for headless deployment.