Test with a prompt for MCP successful, readme translated
CI / test (push) Has been cancelled

This commit is contained in:
Pixelguy14
2026-11-25 14:06:35 -06:00
parent c3d5daeec5
commit d4ae90c1d7
2 changed files with 303 additions and 301 deletions
+4
View File
@@ -20,3 +20,7 @@ build/
# Python # Python
__pycache__/ __pycache__/
*.pyc *.pyc
# Tests
tests_ignore/
opencode.json
+299 -301
View File
@@ -1,153 +1,151 @@
# JuliaMSI_MCP # JuliaMSI_MCP
Servidor [Model Context Protocol](https://modelcontextprotocol.io) (MCP) para el motor de A [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server for the
**Mass Spectrometry Imaging** [JuliaMSI](../JuliaMSI). Expone la sesión persistente, la **Mass Spectrometry Imaging** engine [JuliaMSI](../JuliaMSI). It exposes the persistent
extracción de imágenes iónicas, el pipeline de preprocesamiento streaming y el acceso session, ion-image extraction, streaming preprocessing pipeline and random-access
aleatorio a espectros como herramientas que un LLM (Claude Desktop, VS Code/Copilot, spectrum queries as tools that an LLM (Claude Desktop, VS Code/Copilot, OpenCode, etc.)
OpenCode, etc.) puede invocar de forma reproducible. can invoke reproducibly.
> Estado: **Fase 1–3 del plan implementadas y probadas** (sesión persistente, capa de > Status: **Phases 1–3 of the plan implemented and tested** (persistent session,
> planificación + ejecución asíncrona, catálogo completo de tools/resources/prompts). > planning + async execution layer, full tools/resources/prompts catalog). Phase 4
> La Fase 4 (Streamable HTTP + resiliencia de memoria) también está integrada; falta > (Streamable HTTP + memory resilience) is also integrated; production hardening
> endurecer autenticación y empaquetado AOT para producción. > (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 │ │ 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 │ │ SessionState (logical Ref) RunSpec registry Task registry │
│ ─ MSIData persistente ─ hash de contenido ─ Threads.@spawn │ │ ─ persistent MSIData ─ content hash ─ Threads.@spawn │
│ ─ lock + dataset_id ─ validación ─ polling/cancel │ │ ─ lock + dataset_id ─ validation ─ polling/cancel │
│ │ │ │
│ Tools síncronas · Tools de planificación · Tools de ejecución │ │ Sync tools · Planning tools · Execution tools │
│ Resources msi:// · Prompts de flujo │ │ Resources msi:// · Workflow prompts │
└───────────────────────────────────┬───────────────────────────────────────┘ └───────────────────────────────────┬───────────────────────────────────────┘
│ llamadas directas en proceso (sin IPC) │ direct in-process calls (no IPC)
┌───────────────────────────────────▼───────────────────────────────────────┐ ┌───────────────────────────────────▼───────────────────────────────────────┐
│ Motor JuliaMSI (src/ de JuliaMSI) │ │ JuliaMSI engine (JuliaMSI src/) │
│ imzML + .cache binaria · mmap + madvise · Bloom filters · LRU │ │ imzML + binary .cache · mmap + madvise · Bloom filters · LRU │
│ get_mz_slice · get_multiple_mz_slices · process_dataset! │ │ get_mz_slice · get_multiple_mz_slices · process_dataset! │
└───────────────────────────────────────────────────────────────────────────┘ └───────────────────────────────────────────────────────────────────────────┘
``` ```
### Las cuatro capas ### The four layers
| Capa | Archivo | Responsabilidad | | Layer | File | Responsibility |
|------|---------|-----------------| |-------|------|----------------|
| **Sesión** | `src/session.jl` | Abrir/cerrar `MSIData`, conservarlo entre llamadas, calcular `dataset_id`, liberar memoria al SO (`GC.gc(true)` + `malloc_trim`). | | **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`). |
| **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. | | **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. |
| **Ejecución** | `src/tasks.jl` | Lanzar el RunSpec en una `Threads.@spawn`, registrar estado/progreso, cancelación cooperativa, polling y resultados. | | **Execution** | `src/tasks.jl` | Launch the RunSpec in a `Threads.@spawn`, track state/progress, cooperative cancellation, polling and results. |
| **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. | | **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 - **Clean `stdout` for stdio.** The JuliaMSI engine prints debug traces with `println`;
`println`; el servidor redirige el `stdout` global a `stderr` y entrega al transporte the server redirects the global `stdout` to `stderr` and hands the transport the
el handle original de `stdout` (`install_output_guard`). Así el canal JSON-RPC nunca original `stdout` handle (`install_output_guard`), so the JSON-RPC channel is never
se corrompe. corrupted.
- **Un dataset a la vez.** Es el modelo natural de `MSIData`; abrir otro cierra y limpia - **One dataset at a time.** This is the natural `MSIData` model; opening another one
el anterior. Los planes quedan ligados al `dataset_id` y se rechazan si el dataset closes and cleans the previous. Plans are bound to the `dataset_id` and rejected if
cambió. the dataset changes.
- **Planificar ≠ ejecutar.** El LLM recibe un `runspec_id` auditable; reejecutar el mismo - **Plan ≠ execute.** The LLM receives an auditable `runspec_id`; re-running the same
plan reutiliza la tarea existente salvo `force=true`. plan reuses the existing task unless `force=true`.
- **Resultados acotados.** Una matriz 2000×2000 en JSON son ~32 MB. Por eso el resultado - **Bounded results.** A 2000×2000 matrix is ~32 MB of JSON. Results carry `stats`,
incluye `stats`, `preview` (≤256 px) y rutas a artefactos; `include_matrix` es opt-in y `preview` (≤256 px) and artifact paths instead; `include_matrix` is opt-in and capped.
tiene topes de tamaño. - **Memory.** `msi_close_dataset` and the streaming/analytics tasks run
- **Memoria.** `msi_close_dataset` y las tareas de streaming/analytics ejecutan `GC.gc(true/false)` + `malloc_trim(0)` on Linux to return glibc arenas to the kernel.
`GC.gc(true/false)` + `malloc_trim(0)` en Linux para devolver arenas de glibc al kernel.
--- ---
## 2. Requisitos ## 2. Requirements
- Julia **1.11+** (probado con 1.11.7). - Julia **1.11+** (tested on 1.11.7).
- Un checkout del motor JuliaMSI con su `Project.toml` (por defecto `../JuliaMSI`). - A JuliaMSI engine checkout with its `Project.toml` (default `../JuliaMSI`).
- Dependencias de JuliaMSI ya instaladas (el proyecto las resuelve vía `Pkg`). - JuliaMSI dependencies installed (resolved by `Pkg`).
La integración usa una dependencia de ruta (`[sources] MSI_src = {path = "../JuliaMSI"}`), The integration uses a path dependency (`[sources] MSI_src = {path = "../JuliaMSI"}`),
así que **no se copia** el código del motor: los cambios en JuliaMSI se reflejan al so the engine code is **not copied**: changes in JuliaMSI take effect when the server is
reiniciar el servidor. restarted.
--- ---
## 3. Instalación ## 3. Installation
```bash ```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 julia --project=. scripts/setup.jl
# Opción B: ruta explícita al checkout del motor # Option B: explicit path to the engine checkout
JULIA_MSI_PATH=/ruta/a/JuliaMSI julia --project=. scripts/setup.jl 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 The integration uses the local engine checkout (`../JuliaMSI`) so engine changes are
JuliaMSI se reflejen sin duplicar 10 000 líneas. Si necesitas distribuir el servidor sin reflected without duplicating ~10,000 lines. To distribute the server without the rest
el resto del repo del motor: of the engine repo:
```bash ```bash
mkdir -p vendor/JuliaMSI mkdir -p vendor/JuliaMSI
cp -r ../JuliaMSI/src ../JuliaMSI/Project.toml 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"} # MSI_src = {path = "vendor/JuliaMSI"}
julia --project=. -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()' julia --project=. -e 'using Pkg; Pkg.resolve(); Pkg.instantiate()'
``` ```
También puedes apuntar a cualquiera de los remotos del motor con You can also point at any engine remote with
`Pkg.add(url="https://github.com/Pixelguy14/Julia_msi_GUI")` (o el mirror de Codeberg) y `Pkg.add(url="https://github.com/Pixelguy14/Julia_msi_GUI")` (or the Codeberg mirror)
usar el nombre `MSI_src` en `[deps]`, aunque la dependencia de ruta es la más cómoda and use the `MSI_src` name in `[deps]`, though the path dependency is the most convenient
durante el desarrollo. during development.
### Parches recomendados para JuliaMSI ### Recommended patches for JuliaMSI
Durante la validación (incluidos datasets reales) se encontraron tres bugs del motor. Three engine bugs surfaced during validation (including real datasets). The patches live
Los parches están en `patches/` y **ya están aplicados** al checkout local `../JuliaMSI`: in `patches/` and are **already applied** to the local `../JuliaMSI` checkout:
1. **`juliamsi-fix-nonmmap.patch`** — lectura sin mmap: 1. **`juliamsi-fix-nonmmap.patch`** — non-mmap reading:
- `load_imzml_lazy` creaba un `MSIData` temporal para escribir la caché compartiendo - `load_imzml_lazy` built a temporary `MSIData` to write the cache while sharing the
el vector de handles reales; su finalizador cerraba los handles del dataset real handle vector; its finalizer closed the dataset's handles
(`Bad file descriptor`). Ahora el objeto temporal usa `IO[]`. (`Bad file descriptor`). It now uses `IO[]` for the temporary object.
- `_iterate_uncompressed_fast` leía en buffers `Vector{Float64}` aunque el `.ibd` - `_iterate_uncompressed_fast` read into `Vector{Float64}` buffers even when the
fuera Float32, consumiendo el doble de bytes. Ahora usa el tipo real de la fuente. `.ibd` was Float32, consuming twice the bytes. It now uses the source's real type.
2. **`juliamsi-fix-mask-io.patch`** — máscaras ROI: 2. **`juliamsi-fix-mask-io.patch`** — ROI masks:
- `load_and_prepare_mask` llamaba `Gray.(img)` y fallaba con TIFF que cargan como - `load_and_prepare_mask` called `Gray.(img)` and failed on TIFFs that load as
`TiffImages.WidePixel` (p. ej. la imagen óptica de referencia del dataset HR2MSI). `TiffImages.WidePixel` (e.g. the HR2MSI optical reference image). It now uses the
Ahora usa el canal de color embebido. embedded color channel.
- `process_image_pipeline` creaba un elemento estructurante par con el valor por - `process_image_pipeline` built an even-sized structuring element from the default
defecto `smoothing=2`, que ImageMorphology rechaza `smoothing=2`, which ImageMorphology rejects (`connectivity must be odd-sized`).
(`connectivity must be odd-sized`). Ahora normaliza a un tamaño impar ≥ 3. It now normalizes to an odd size ≥ 3.
**Estado upstream (nov 2026):** las tres correcciones ya están integradas en el commit **Upstream status (Nov 2026):** all three fixes are part of engine commit `bc71b9c`,
`bc71b9c` del motor, presente en la rama `rel/Windows_Mac_Recompatibility` (Codeberg, present on the `rel/Windows_Mac_Recompatibility` branch (Codeberg, GitHub, nube-gran)
GitHub y nube-gran) y en `main` de **GitHub**. `main` de **Codeberg** y de **nube-gran** and on **GitHub** `main`. **Codeberg** `main` and **nube-gran** `main` do not include
todavía no las incluye, así que los parches siguen siendo útiles como respaldo para them yet, so the patches remain useful as a fallback for those default branches:
quien clone esas ramas por defecto:
```bash ```bash
cd /ruta/a/JuliaMSI cd /path/to/JuliaMSI
git apply /home/pixel/Documents/2026/JuliaMSI_MCP/patches/juliamsi-fix-nonmmap.patch git apply /path/to/JuliaMSI_MCP/patches/juliamsi-fix-nonmmap.patch
git apply /home/pixel/Documents/2026/JuliaMSI_MCP/patches/juliamsi-fix-mask-io.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 Recommendation: merge `rel/Windows_Mac_Recompatibility` into `main` on Codeberg and
nube-gran para poder eliminar la carpeta `patches/`. La ruta con mmap (por defecto) no nube-gran so the `patches/` folder can eventually be removed. The mmap path (default) is
se ve afectada por el primer parche. unaffected by the first patch.
Verificación rápida: Quick check:
```bash ```bash
julia --project=. -e 'using JuliaMSI_MCP; println(JuliaMSI_MCP.SERVER_VERSION)' 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 ```bash
julia --project=. --threads=auto bin/run_server.jl julia --project=. --threads=auto bin/run_server.jl
``` ```
`--threads=auto` es importante: el motor paraleliza espectros y el servidor lanza tareas `--threads=auto` matters: the engine parallelizes spectra and the server launches
en segundo plano. background tasks.
### Streamable HTTP ### 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 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 By default it listens on localhost only, without authentication. To protect the endpoint,
puede exigir un token compartido: require a shared token:
```bash ```bash
julia --project=. --threads=auto bin/run_server.jl --http --port 3000 --token S3CR3T 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 Clients must send `Authorization: Bearer S3CR3T`. To expose it beyond the machine, put a
máquina, pon un reverse proxy con TLS delante (el token compartido **no** sustituye a TLS). 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 ```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 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 `scripts/build_sysimage.jl` creates a throwaway environment, develops the engine and
`JuliaMSI_MCP`, y ejecuta `scripts/sysimage_warmup.jl` (apertura, espectro, slices, `JuliaMSI_MCP`, and runs `scripts/sysimage_warmup.jl` (open, spectrum, slices, streaming,
streaming y registro de tools) para precargar el código nativo. La construcción tarda tool registration) to bake in the native code. The build takes several minutes and the
varios minutos y el `.so` es específico de la máquina. `.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_desktop_config.json` → Claude Desktop (`mcpServers`). On Linux:
`~/.config/Claude/claude_desktop_config.json`; en Windows: `~/.config/Claude/claude_desktop_config.json`; on Windows:
`%APPDATA%\Claude\claude_desktop_config.json`. `%APPDATA%\Claude\claude_desktop_config.json`.
- `config/vscode_mcp.json` → VS Code / Copilot. Cópialo como `.vscode/mcp.json` en el - `config/vscode_mcp.json` → VS Code / Copilot. Copy it as `.vscode/mcp.json` in the
workspace (o ejecuta *MCP: Add Server*). workspace (or run *MCP: Add Server*).
- `config/opencode.json` → OpenCode V2 (clave `mcp.servers`). Cópialo como - `config/opencode.json` → OpenCode V2 (key `mcp.servers`). Copy it as `opencode.json`
`opencode.json` en la raíz del proyecto, o fusiónalo con at the project root, or merge it into `~/.config/opencode/opencode.json` for global use.
`~/.config/opencode/opencode.json` para uso global.
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 \ julia --project=/path/to/JuliaMSI_MCP --threads=auto \
/home/pixel/Documents/2026/JuliaMSI_MCP/bin/run_server.jl /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_NUM_THREADS=auto` | Engine threads (also `--threads=auto`). |
| `JULIA_MSI_MCP_ARTIFACTS=/ruta` | Directorio de artefactos (por defecto `<proyecto>/artifacts`). | | `JULIA_MSI_MCP_ARTIFACTS=/path` | Artifact directory (default `<project>/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_AGE_DAYS` | Artifact lifetime before pruning at startup (default 7). |
| `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` | Presupuesto total de artefactos en bytes (default 0 = sin límite). | | `JULIA_MSI_MCP_ARTIFACT_MAX_BYTES` | Total artifact budget in bytes (default 0 = unlimited). |
| `JULIA_MSI_MCP_TOKEN` | Token compartido para `--http` (equivale a `--token`). | | `JULIA_MSI_MCP_TOKEN` | Shared token for `--http` (same as `--token`). |
| `JULIA_MSI_MCP_KEEP_STDOUT=1` | Desactiva la redirección de `stdout` (solo para depurar en local). | | `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_open_dataset` | sync | Open/switch an imzML/mzML dataset; creates or uses `.cache`; optional `precompute_analytics`. |
| `msi_close_dataset` | síncrona | Cierra handles, vacía caché y devuelve RAM al SO. | | `msi_close_dataset` | sync | Closes handles, empties the cache and returns RAM to the OS. |
| `msi_dataset_info` | síncrona | Estado de la sesión (dimensiones, rango m/z, mmap, RSS, hilos). | | `msi_dataset_info` | sync | Session state (dimensions, m/z range, mmap, RSS, threads). |
| `msi_get_dataset_stats` | síncrona | Estadísticas por espectro (TIC/BPI/NumPoints/rango m/z). | | `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_at_coord` | sync | Spectrum at `(x, y)` via the LRU cache. `representation=peaks` or `profile`. |
| `msi_get_spectrum_by_index` | síncrona | Espectro por índice lineal (útil para mzML no-imaging). | | `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_mz_slice` | sync | Immediate ion image for one mass. |
| `msi_get_multiple_mz_slices` | síncrona | Hasta 50 masas en una sola pasada (inversión de jerarquía). | | `msi_get_multiple_mz_slices` | sync | Up to 50 masses in a single pass (hierarchy inversion). |
| `msi_plan_ion_image` | planificación | Valida y genera `runspec_id` para una masa. | | `msi_plan_ion_image` | planning | Validates and mints a `runspec_id` for one mass. |
| `msi_plan_multiple_slices` | planificación | Genera `runspec_id` para un panel de hasta 5000 masas (1 pasada I/O). | | `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_preprocessing` | planning | Streaming pipeline (`process_dataset!`) → sparse matrix. |
| `msi_plan_streaming_pipeline` | planificación | Alias del anterior. | | `msi_plan_streaming_pipeline` | planning | Alias of the above. |
| `msi_plan_analytics` | planificación | Escaneo TIC/BPI/Bloom filters en segundo plano. | | `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_execute_runspec` | execution | Launches the plan in the background and returns a `task_id` (reuses tasks unless `force`). |
| `msi_get_task_status` | síncrona | Estado, progreso, tiempos y resumen. | | `msi_get_task_status` | sync | State, progress, timings and summary. |
| `msi_get_task_result` | síncrona | Resultado completo (stats, preview, artefactos, matrices opt-in). | | `msi_get_task_result` | sync | Full result (stats, preview, artifacts, opt-in matrices). |
| `msi_cancel_task` | síncrona | Cancelación cooperativa. | | `msi_cancel_task` | sync | Cooperative cancellation. |
| `msi_list_tasks` | síncrona | Lista tareas recientes (filtro por estado). | | `msi_list_tasks` | sync | List recent tasks (filter by status). |
| `msi_list_plans` | síncrona | Lista RunSpecs recientes. | | `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 ### Resources
| URI | Contenido | | URI | Content |
|-----|-----------| |-----|---------|
| `msi://dataset/metadata` | Metadatos de la sesión activa. | | `msi://dataset/metadata` | Active session metadata. |
| `msi://dataset/stats` | Agregados + primeras 100 filas (no dispara el escaneo). | | `msi://dataset/stats` | Aggregates + first 100 rows (does not trigger the scan). |
| `msi://tasks/{task_id}/status` | Estado de una tarea. | | `msi://tasks/{task_id}/status` | Task status. |
| `msi://tasks/{task_id}/result` | Resultado de una tarea. | | `msi://tasks/{task_id}/result` | Task result. |
### Prompts ### Prompts
| Prompt | Uso | | Prompt | Use |
|--------|-----| |--------|-----|
| `analyze_region_of_interest` | Forces confirmation of mass, tolerance and mask before planning. | | `analyze_region_of_interest` | Forces confirmation of mass, tolerance and mask before planning. |
| `standard_pipeline` | Open → plan → execute → poll → summarize workflow. | | `standard_pipeline` | Open → plan → execute → poll → summarize workflow. |
| `diagnose_task` | Interprets task states/errors and proposes corrective actions. | | `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 > Prompts (and their content) are in English, the project's primary language. Earlier
> anteriores del compendio: `analizar_region_de_interes`, `pipeline_estandar`, > compendium names: `analizar_region_de_interes`, `pipeline_estandar`,
> `diagnostico_de_tarea`. > `diagnostico_de_tarea`.
--- ---
## 6. Flujo típico (lo que hace el LLM) ## 6. Typical flow (what the LLM does)
```text ```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", …} │ → {"runspec_id": "a1b2…", "kind": "ion_image", …}
▼ ▼
msi_execute_runspec(runspec_id="a1b2…", wait_seconds=0) msi_execute_runspec(runspec_id="a1b2…", wait_seconds=0)
│ → {"task_id": "uuid", "status": "queued"} │ → {"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") msi_get_task_result(task_id="uuid")
│ → stats, preview, artifacts.csv/pgm │ → stats, preview, artifacts.csv/pgm
@@ -324,7 +321,7 @@ msi_get_task_result(task_id="uuid")
msi_close_dataset() msi_close_dataset()
``` ```
Resultado de una imagen iónica (resumido): Ion-image result (abridged):
```json ```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 Handlers never crash the JSON-RPC loop: every exception becomes
`CallToolResult(is_error=true)` con este cuerpo: `CallToolResult(is_error=true)` with this body:
```json ```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 | | Type | Code | Typical origin | Suggested action |
|------|--------|---------------|-----------------| |------|------|----------------|------------------|
| `InvalidParams` | `-32602` | masa/tolerancia/máscara/coordenadas | corregir argumentos | | `InvalidParams` | `-32602` | mass/tolerance/mask/coordinates | fix arguments |
| `SessionError` | `-32010` | no hay dataset abierto | `msi_open_dataset` | | `SessionError` | `-32010` | no dataset open | `msi_open_dataset` |
| `ResourceNotFound` | `-32002` | task_id/URI inexistente | listar tareas/planes | | `ResourceNotFound` | `-32002` | unknown task_id/URI | list tasks/plans |
| `InternalError` | `-32603` | I/O, `.cache` corrupta, OOM | revisar stderr; borrar `.cache`; usar streaming | | `InternalError` | `-32603` | I/O, corrupt `.cache`, OOM | check stderr; delete `.cache`; use streaming |
--- ---
## 8. Pruebas ## 8. Testing
```bash ```bash
julia --project=. -e 'using Pkg; Pkg.test()' julia --project=. -e 'using Pkg; Pkg.test()'
``` ```
La suite genera un **imzML sintético válido** (4×3, Float32, 5 picos/espectro, un pico The suite generates a **valid synthetic imzML** (4×3, Float32, 5 peaks/spectrum, one
fuerte en 300 Da) y cubre: strong peak at 300 Da) and covers:
- utilidades (hash canónico, JSON seguro, preview, estadísticas), - utilities (canonical hash, safe JSON, preview, statistics),
- apertura/cierre de sesión y `.cache`, - session open/close and `.cache`,
- espectro por coordenada e índice, - spectrum by coordinate and index,
- extracción iónica síncrona y múltiple, - synchronous single and multiple ion-image extraction,
- validación de planes y binding al dataset, - plan validation and dataset binding,
- flujo asíncrono completo (plan → execute → status → result), - the full async flow (plan → execute → status → result),
- analíticas y pipeline streaming, - analytics and the streaming pipeline,
- resources, prompts y cambio de dataset. - 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 There is also an end-to-end stdio smoke test in `test/smoke_stdio.py` (generates the
sintético, arranca el servidor y recorre initialize → tools → plan → execute → result). 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, Validated against the `Cinvestav_2025/Analisis` data (12 threads, 14 GB RAM, local disk;
disco local; los tiempos varían con la caché de página). timings vary with page cache).
### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imagen) ### `HR2MSImouseurinarybladderS096.imzML` (AP-SMALDI, imaging)
| Métrica | Resultado | | Metric | Result |
|---------|-----------| |--------|--------|
| Espectros / dimensiones | 34 840 / 260 × 134 | | Spectra / dimensions | 34,840 / 260 × 134 |
| Tamaño | `.ibd` 815 MB, `.imzML` 56 MB (con `.cache`) | | Size | `.ibd` 815 MB, `.imzML` 56 MB (with `.cache`) |
| Apertura | 2.0–3.5 s usando la `.cache` binaria | | Open | 2.0–3.5 s using the binary `.cache` |
| Escaneo de analíticas | 6.8–12.9 s | | Analytics scan | 6.8–12.9 s |
| Espectro `(130,67)` | 966 puntos, BPI 4 026.3, pico base 798.5387 | | Spectrum `(130,67)` | 966 points, BPI 4,026.3, base peak 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) | | Ion image `798.5387 ± 0.15` | 1.8 s, max 14,274.8, 21,920 pixels with signal, base peak (167,105) |
| 4–5 masas en una pasada | 2.2 s sin máscara / 3.7 s con máscara | | 4–5 masses in one pass | 2.2 s without mask / 3.7 s with mask |
| Máscara ROI (óptica → PGM) | 36 % del área; el TIFF óptico directo da ~43 % tras el parche | | ROI mask (optical → PGM) | 36% of the area; the optical TIFF directly gives ~43% after the patch |
| Streaming (12 571 espectros enmascarados) | 3.9 s; matriz 420 × 34 840; 1 424 362 nnz; `.mtx` 44 MB | | Streaming (12,571 masked spectra) | 3.9 s; matrix 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 | | 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 |
| Bins más intensos | 580.6, 443.8, 716.2 m/z | | 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 > The difference between "engine" and "wall" on the first run is mostly first-call JIT of
> compilación JIT de la ruta de analíticas/streaming y al polling cada 1 s; en llamadas > the analytics/streaming path plus 1 s polling granularity; later calls approach engine
> posteriores el tiempo de pared se acerca al del motor. Es el argumento principal para > time. That is the main argument for the Phase-4 AOT sysimage.
> el sysimage AOT de la Fase 4.
El pipeline streaming mantiene la RAM acotada: incluso con 34 840 espectros, el motor The streaming pipeline keeps RAM bounded: even with 34,840 spectra, the engine keeps one
solo conserva un espectro por hilo y ensambla una `SparseMatrixCSC`. 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 | | `T9_A1.mzML` | 10 | 0.06 s | 0.15–1.2 s |
| `Cytochrome_C.mzML` | 32 | 0.07 s | 0.15 s | | `Cytochrome_C.mzML` | 32 | 0.07 s | 0.15 s |
| `Col_1.mzML` | 800 | 0.17 s | 0.07 s | | `Col_1.mzML` | 800 | 0.17 s | 0.07 s |
- `msi_get_spectrum_by_index` y `msi_get_dataset_stats` funcionan correctamente. - `msi_get_spectrum_by_index` and `msi_get_dataset_stats` work correctly.
- Las tools de imagen (`msi_get_mz_slice`, `msi_plan_ion_image`, …) se rechazan con - Imaging tools (`msi_get_mz_slice`, `msi_plan_ion_image`, …) are rejected with
`InvalidParams` porque el dataset no tiene `coordinate_map` ni dimensiones espaciales. `InvalidParams` because the dataset has no `coordinate_map` and no spatial dimensions.
### Reproducir ### Reproduce
```bash ```bash
# Smoke test genérico (detecta imaging vs. mzML automáticamente) # Generic smoke test (auto-detects imaging vs. mzML)
python3 test/smoke_stdio.py --dataset /ruta/archivo.imzML 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 \ 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/ JuliaMSI_MCP/
@@ -464,94 +462,94 @@ JuliaMSI_MCP/
├── bin/run_server.jl # entrypoint stdio / --http [--token] ├── bin/run_server.jl # entrypoint stdio / --http [--token]
├── scripts/ ├── scripts/
│ ├── setup.jl # Pkg.develop + instantiate + precompile │ ├── setup.jl # Pkg.develop + instantiate + precompile
│ ├── build_sysimage.jl # imagen de sistema AOT (Fase 4) │ ├── build_sysimage.jl # AOT system image (Phase 4)
│ └── sysimage_warmup.jl # workload de precompilación │ └── sysimage_warmup.jl # precompile workload
├── patches/ # parches de respaldo para el motor (ver §3) ├── patches/ # fallback engine patches (see §3)
├── src/ ├── src/
│ ├── JuliaMSI_MCP.jl # módulo e includes │ ├── JuliaMSI_MCP.jl # module and includes
│ ├── util.jl # JSON seguro, hashes, previews │ ├── util.jl # safe JSON, hashes, previews
│ ├── errors.jl # MCPToolError + mapeo JSON-RPC │ ├── errors.jl # MCPToolError + JSON-RPC mapping
│ ├── session.jl # MSIData persistente + cleanup │ ├── session.jl # persistent MSIData + cleanup
│ ├── runspec.jl # planificación y validación │ ├── runspec.jl # planning and validation
│ ├── tasks.jl # ejecución asíncrona + registro │ ├── tasks.jl # async execution + registry
│ ├── artifacts.jl # CSV/PGM/MatrixMarket + retención │ ├── artifacts.jl # CSV/PGM/MatrixMarket + retention
│ ├── resources.jl # msi:// │ ├── resources.jl # msi://
│ ├── prompts.jl # flujos guiados (inglés) │ ├── prompts.jl # workflow prompts (English)
│ ├── server.jl # build_server / run_stdio / run_http (+ token) │ ├── server.jl # build_server / run_stdio / run_http (+ token)
│ └── tools/ # dataset, spectra, imaging, planning, tasks, maintenance │ └── tools/ # dataset, spectra, imaging, planning, tasks, maintenance
├── config/ # Claude Desktop, VS Code, OpenCode ├── config/ # Claude Desktop, VS Code, OpenCode
├── test/ ├── test/
│ ├── synthetic.jl # generador imzML de prueba │ ├── synthetic.jl # test imzML generator
│ ├── runtests.jl │ ├── runtests.jl
│ ├── smoke_stdio.py # smoke test end-to-end por stdio │ ├── smoke_stdio.py # end-to-end stdio smoke test
│ └── real_datasets.jl # validación reproducible con datasets reales │ └── real_datasets.jl # reproducible real-dataset validation
├── build/ # sysimage generado (ignorado por git) ├── build/ # generated sysimage (git-ignored)
└── artifacts/ # resultados (ignorado por git) └── 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 | | Compendium section | MCP implementation |
|-----------------------|--------------------| |--------------------|--------------------|
| A.1 `MSIData`, LRU, atómicos | sesión persistente + `GetSpectrum` | | A.1 `MSIData`, LRU, atomics | persistent session + `GetSpectrum` |
| A.2 slices / inversión de jerarquía | `msi_get_multiple_mz_slices`, `msi_plan_multiple_slices` | | A.2 slices / hierarchy inversion | `msi_get_multiple_mz_slices`, `msi_plan_multiple_slices` |
| A.3 parser dual + `.cache` | `msi_open_dataset` (delegado al motor) | | A.3 dual parser + `.cache` | `msi_open_dataset` (delegated to the engine) |
| A.4 handle pool | `--threads=auto`; el motor abre un handle por hilo | | A.4 handle pool | `--threads=auto`; the engine opens one handle per thread |
| A.5 Bloom filters | rechazo aplicado por `get_mz_slice` | | A.5 Bloom filters | rejection applied by `get_mz_slice` |
| A.6 mmap + `madvise` | `use_mmap=true` y `preview` acotado | | A.6 mmap + `madvise` | `use_mmap=true` and bounded `preview` |
| A.7–A.8 preprocessing/streaming | `msi_plan_preprocessing`, `process_dataset!` | | A.7–A.8 preprocessing/streaming | `msi_plan_preprocessing`, `process_dataset!` |
| A.10 máscaras ROI | `mask_path` en planes y slices | | A.10 ROI masks | `mask_path` in plans and slices |
| A.11 sysimage AOT | `scripts/build_sysimage.jl` + `--sysimage` (ver §4) | | A.11 AOT sysimage | `scripts/build_sysimage.jl` + `--sysimage` (see §4) |
| A.12 `malloc_trim` | `release_os_memory!` en cierre y tareas pesadas | | A.12 `malloc_trim` | `release_os_memory!` on close and heavy tasks |
| B.1 STDIO/HTTP | `run_stdio`, `run_http` (con token compartido opcional) | | B.1 STDIO/HTTP | `run_stdio`, `run_http` (optional shared token) |
| B.2 tools | 20 tools registradas | | B.2 tools | 20 registered tools |
| B.3 resources | `msi://dataset/*`, `msi://tasks/*` | | 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 | | Symptom | Cause / fix |
|---------|------------------| |---------|-------------|
| `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. | | `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. |
| 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`. | | 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` | Usa rutas absolutas y mantén `.imzML` + `.ibd` con el mismo basename. | | `Dataset file not found` / `.ibd not found` | Use absolute paths and keep `.imzML` + `.ibd` with the same basename. |
| Primer slice tarda mucho | Se está ejecutando el escaneo de analíticas. Usa `msi_plan_analytics` + `msi_execute_runspec` en segundo plano. | | First slice is slow | The analytics scan is running. Use `msi_plan_analytics` + `msi_execute_runspec` in the background. |
| `.cache` corrupta tras un crash | Borra `<archivo>.imzML.cache`; el parser XML se regenera. | | `.cache` corrupt after a crash | Delete `<file>.imzML.cache`; the XML parser regenerates it. |
| Error de permisos al abrir | El motor escribe `<archivo>.imzML.cache` junto al dataset; copia el `.imzML`+`.ibd` a un directorio escribible. | | Permission error on open | The engine writes `<file>.imzML.cache` next to the dataset; copy `.imzML`+`.ibd` to a writable directory. |
| 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. | | 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` 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). | | `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 1. **One dataset per process** (by engine design). Multiplexing datasets would need a
falta un pool de sesiones o un proceso por dataset. session pool or one process per dataset.
2. **Cancelación cooperativa**: no se puede interrumpir un `pread`/pasada de disco en 2. **Cooperative cancellation**: an in-flight `pread`/disk pass cannot be interrupted;
curso; la tarea se detiene en el siguiente checkpoint. the task stops at the next checkpoint.
3. **`msi_get_dataset_stats` y slices síncronos pueden bloquear** durante el primer 3. **`msi_get_dataset_stats` and sync slices can block** during the first analytics scan.
escaneo de analíticas. Para datasets grandes, usar `msi_plan_analytics` + ejecución. For large datasets, use `msi_plan_analytics` + execution.
4. **Tasks MCP nativas (SEP-1686/2663)**: se usa un registro de tareas propio, compatible 4. **Native MCP tasks (SEP-1686/2663)**: the server uses its own task registry, compatible
con cualquier cliente. Se puede añadir `task_support=:optional` y `task_detach` cuando with any client. `task_support=:optional` and `task_detach` can be added to publish
se quiera publicar el estado por `tasks/get` del SDK. state via the SDK's `tasks/get`.
5. **Huella base de memoria**: `using MSI_src` ya no carga el stack de plotting 5. **Baseline memory footprint**: `using MSI_src` no longer loads the plotting stack
(CairoMakie/GLMakie) gracias a `PlottingStubs.jl`, pero `Images` (para máscaras) sigue (CairoMakie/GLMakie) thanks to `PlottingStubs.jl`, but `Images` (for masks) still
dejando el proceso en ~1.6 GB RSS. Separar el core de datos de `ImageProcessing` leaves the process at ~1.6 GB RSS. Splitting the data core from `ImageProcessing`
reduciría arranque y RAM. would reduce startup and RAM.
6. **TLS**: el token compartido de HTTP protege el endpoint, pero el cifrado en tránsito 6. **TLS**: the HTTP shared token protects the endpoint, but transport encryption still
sigue dependiendo de un reverse proxy (Caddy/nginx) con TLS. requires a TLS reverse proxy (Caddy/nginx).
Resuelto en Fase 4: retención de artefactos (`msi_clean_artifacts` + política al Resolved in Phase 4: artifact retention (`msi_clean_artifacts` + startup policy), HTTP
arranque), autenticación HTTP por token compartido, script de sysimage AOT shared-token auth, the AOT sysimage script (`scripts/build_sysimage.jl`) and CI
(`scripts/build_sysimage.jl`) y CI (`../.github/workflows/ci.yml`). (`.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`). `tasks/get`, `notifications/progress`).
- [ ] Notificación `notifications/resources/updated` para `msi://tasks/{id}/status`. - [ ] `notifications/resources/updated` for `msi://tasks/{id}/status`.
- [ ] Verificar el arranque con `--sysimage=build/sys_mcp.so` y medir la mejora de TTFX. - [ ] Verify startup with `--sysimage=build/sys_mcp.so` and measure the TTFX improvement.
- [ ] Unit/integration en CI sobre un dataset de referencia real (benchmarks del repo). - [ ] CI unit/integration on a real reference dataset (repo benchmarks).
- [ ] `Dockerfile`/systemd para despliegue headless. - [ ] `Dockerfile`/systemd for headless deployment.