Autonomous OODA-loop pentesting agent. Hermes brain, Kali + Playwright tools over MCP, ATT&CK as the Orient language.
Python ai-agentsautonomous-agentskali-linuxllm-agentsoffensive-securityooda-looppentestingplaywrightsecurity
feat(mcp): add optional vulnerator-mcp FastMCP wrapper over :8642 (1.4.0)
irraz088dd6941e93
diff --git a/.env.example b/.env.exampleindex 5136ce4..5a16946 100644--- a/.env.example+++ b/.env.example@@ -52,6 +52,28 @@ HERMES_API_SERVER_KEY=# controlled environment. If you don't want to open the port, use 'docker compose exec' (see README).HERMES_API_HOST_PORT=+# --- vulnerator-mcp (OPTIONAL MCP front door — docker-compose.mcp.yml) --------+# These vars matter ONLY when you bring up the OPTIONAL vulnerator-mcp service with+# docker compose -f docker-compose.yml -f docker-compose.mcp.yml up -d --build+# The default 3-container stack does NOT use them, and stdio mode (local Claude Code / Kiro)+# needs neither of them.+#+# REQUIRED only for the optional streamable-HTTP service. Inbound Bearer that gates the+# clients -> vulnerator-mcp edge. Generate one with:+# openssl rand -hex 32+# It is a SEPARATE secret from HERMES_API_SERVER_KEY and protects a DIFFERENT edge (it does+# NOT re-protect the :8642 host exposure). The service is FAIL-CLOSED: it will not start+# without this, and every request must carry 'Authorization: Bearer <this>'.+VULNERATOR_MCP_INBOUND_TOKEN=++# OPTIONAL. HOST port where the vulnerator-mcp streamable-HTTP server is published. Relevant+# ONLY if you uncomment the 'ports:' block in docker-compose.mcp.yml. By DEFAULT the service+# publishes NO host port and is reachable only on the internal docker network at+# vulnerator-mcp:8700. Set this (and uncomment the block) to publish on a controlled machine.+# WARNING: publishing exposes the no-guardrails engine's trigger API to the host; do it+# deliberately and keep VULNERATOR_MCP_INBOUND_TOKEN secret.+VULNERATOR_MCP_HOST_PORT=+# --- AWS read-only (OPTIONAL) -------------------------------------------------# Only if you are going to use the cloud collection tools (Prowler/ScoutSuite/Cloudsplaining).# If you don't use them, leave these variables empty. Use read-only credentials for the accountdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 98df8cc..b877497 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,40 @@ All notable changes to Vulnerator AI are documented here.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.4.0] - 2026-10-16++### Added+- **Optional `vulnerator-mcp` MCP front door over the Hermes `:8642` runs API.** A thin+ FastMCP wrapper (`docker/mcp/`) that lets external MCP clients (Claude Code / Kiro locally+ over stdio; remote/containerized consumers like BugTraceAI over streamable-HTTP) trigger,+ observe, steer and stop a Hermes OODA pentest as MCP tools. It WRAPS, does not replace, the+ HTTP API: it exposes ONLY the runs lifecycle — five tools (`start_pentest`,+ `get_run_status`, `stream_run_events`, `steer_run`, `stop_run`) plus `health()` — so the+ client stays a trigger/observer and never the brain. It never exposes `/v1/chat/completions`+ or any raw `kali_run` pass-through. The wrapper is stateless and version-tolerant: the run+ object and events are forwarded opaquely and terminality is derived from the run booleans+ (`completed`/`interrupted`), never from the `status` string; the upstream version is read+ from `GET /health` and reported verbatim, never branched on. `stream_run_events` uses the+ event `seq` as a portable cursor (batched pages with `next_cursor`/`done`) and additionally+ emits MCP progress notifications over streamable-HTTP, degrading to pure batching on stdio.+ Shipped as a NEW **optional layered `docker-compose.mcp.yml`** — NOT part of the default+ stack, which stays 3 containers (`kali`, `ooda-agent`, `playwright-mcp`) — brought up with+ `docker compose -f docker-compose.yml -f docker-compose.mcp.yml up -d --build`. The+ streamable-HTTP service binds the internal docker network with host publication OFF by+ default (no `ports:` block; opt-in by uncommenting it and/or setting+ `VULNERATOR_MCP_HOST_PORT`) and is **fail-closed on a mandatory inbound token**+ (`VULNERATOR_MCP_INBOUND_TOKEN`): it refuses to start without one and rejects any request+ without the matching `Authorization: Bearer` (constant-time compare), with an exact-match+ carve-out for a dedicated `/healthz` route only. The same image also runs stdio for local+ Claude Code / Kiro with no token and no port (zero network surface). Upstream auth is a+ pass-through Bearer from `HERMES_API_SERVER_KEY` (no second secret for the `:8642` hop). The+ required `scope` argument is **advisory**, folded into the prompt for operator clarity — the+ MCP layer enforces NO scope and adds NO safety (the optional Kali-layer scope-guard from+ v1.3.0 is a separate, opt-in defense-in-depth layer). New `.env.example` entries+ (`VULNERATOR_MCP_INBOUND_TOKEN`, `VULNERATOR_MCP_HOST_PORT`), a README section with a+ copy-paste Claude Code / Kiro stdio `mcpServers` snippet and a loud no-guardrails warning,+ and unit tests for the SSE cursor parser and scope-folding/validation logic.+## [1.3.0] - 2026-10-16### Added@@ -77,6 +111,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the authorized-offensive pentest framing; overriding with such a model may make the agentrefuse to work.+[1.4.0]: https://github.com/irraz/vulnerator-ai/releases/tag/v1.4.0[1.3.0]: https://github.com/irraz/vulnerator-ai/releases/tag/v1.3.0[1.2.0]: https://github.com/irraz/vulnerator-ai/releases/tag/v1.2.0[1.1.0]: https://github.com/irraz/vulnerator-ai/releases/tag/v1.1.0diff --git a/README.md b/README.mdindex 91ab44d..272a997 100644--- a/README.md+++ b/README.md@@ -65,6 +65,13 @@ Three containers (the agent and two MCP servers) and the agent driving end to enThere are no `api` or `ui` services: the agent talks directly to the MCPs (Kali and browser).+There is an **OPTIONAL 4th container** you can layer on top: **vulnerator-mcp** — a thin MCP+front door over Hermes' `:8642` runs API so external MCP clients (Claude Code / Kiro,+BugTraceAI, ...) can trigger/observe/steer/stop a pentest as MCP tools. It is **not** part of+the default stack (the default `docker compose up` stays the 3 containers above); it is an+opt-in overlay, the same way the Juice Shop target is. See "Consume Hermes from an MCP client+(`vulnerator-mcp`)" below.+### Tools included in the Kali imageThe Kali image bakes in a **curated** set of pentest CLIs the skills assume exist and invoke via@@ -117,6 +124,7 @@ variables empty in the `.env`:| `AWS_SESSION_TOKEN` | No | Only for temporary credentials (STS). In the `.env`. || `AWS_REGION` | No | Default region (e.g. `us-east-1`). In the `.env`. || `OPENROUTER_MODEL` | No | Overrides the OpenRouter model Hermes reasons with. Empty = the profile default (`mistralai/mistral-large-4-0`). **Caveat:** the project uses Mistral Large on purpose because models like Claude (`anthropic/*`) refuse the authorized-offensive pentest framing (OpenRouter/Anthropic returns "violative cyber content"); overriding with such a model may make the agent refuse to work. |+| `VULNERATOR_MCP_INBOUND_TOKEN` | Only for the optional `vulnerator-mcp` HTTP service | Inbound Bearer for the opt-in `docker-compose.mcp.yml` streamable-HTTP service. Generate with `openssl rand -hex 32`. It is a **separate** secret from `HERMES_API_SERVER_KEY` and gates a different edge. The service is **fail-closed**: it will not start without this. NOT needed for the default stack or for stdio mode. See "Consume Hermes from an MCP client". |The rest of the `.env.example` variables (host ports, artifacts token, Prowlerscoping) are optional and come with defaults; leave them empty unless you need to@@ -322,6 +330,90 @@ need external access use Mode B (`exec`, without opening a port). This is consis⚠️ Warning further down: there is no scope-guard or authorization gate, responsibility for thescope rests entirely with the operator.+## Consume Hermes from an MCP client (`vulnerator-mcp`)++If your tooling speaks **MCP** rather than raw HTTP (Claude Code, Kiro, Cursor, BugTraceAI, …),+there is an OPTIONAL thin MCP server — **`vulnerator-mcp`** (`docker/mcp/`) — that wraps Hermes'+`:8642` runs API and exposes it as MCP tools. It wraps, it does **not** replace, the HTTP API: it+exposes **only** the runs lifecycle, so the client stays a trigger/observer and never the brain.++Five tools + a health check, mapped 1:1 onto `:8642`:++| Tool | Does |+| --- | --- |+| `start_pentest(input, scope, …)` | starts a run (`POST /v1/runs`); returns `{run_id, status, replayed}` |+| `get_run_status(run_id)` | the full run object (status + `completed`/`partial`/`interrupted` + output + usage) |+| `stream_run_events(run_id, cursor, …)` | pages the SSE events with a `seq` cursor (`{events, next_cursor, done}`); also emits MCP progress over streamable-HTTP |+| `steer_run(run_id, input)` | injects a correction (`POST …/steer`); surfaces the 409 `run_not_accepting_steer` verbatim |+| `stop_run(run_id)` | stops the run (`POST …/stop`); returns the full run object |+| `health()` | upstream `GET /health` (`{status, platform, version}`) |++It deliberately does **not** expose `/v1/chat/completions` or any raw `kali_run` pass-through.+Event/status/output payloads are forwarded verbatim as **untrusted data** (never interpreted).++> ⚠️ **No guardrails — same warning as the rest of the product, amplified.** The MCP layer+> enforces **no scope**, no consent and no audit; it only adds *reachability*. The `scope`+> argument on `start_pentest` is **REQUIRED but ADVISORY**: it is folded into the prompt for+> operator clarity, it is **not** an enforced constraint. For a real deterministic gate on+> raw-shell actions, enable the **optional Kali-layer scope-guard** (v1.3.0, via `scope.json` —+> see "Scope-guard (opt-in)" below); that is a different, opt-in layer and is **not** a gate on+> this runs API. Responsibility for the scope rests entirely with the operator.++### Local: stdio (recommended for Claude Code / Kiro)++stdio has **zero network surface**: the client spawns the server as a subprocess over+stdin/stdout — no listener, no inbound token, no port. Build the image once+(`docker build -f docker/mcp/Dockerfile -t vulnerator-ai-mcp:dev .`), then add an `mcpServers`+entry (copy-paste; the stdio process reaches the host-published `:8642` via+`host.docker.internal`):++```json+{+ "mcpServers": {+ "vulnerator-mcp": {+ "command": "docker",+ "args": [+ "run", "-i", "--rm",+ "-e", "HERMES_API_SERVER_KEY",+ "-e", "HERMES_API_BASE_URL=http://host.docker.internal:8642",+ "vulnerator-ai-mcp:dev"+ ],+ "env": { "HERMES_API_SERVER_KEY": "<your HERMES_API_SERVER_KEY>" }+ }+ }+}+```++The upstream Bearer is a **pass-through** of `HERMES_API_SERVER_KEY` (no second secret is minted+for the `:8642` hop).++### In-docker / remote: streamable-HTTP (optional layered service)++For an in-docker consumer (e.g. a BugTraceAI container on the same network) or a remote+orchestrator, bring up the OPTIONAL layered service — it is **not** in the default stack:++```sh+# requires VULNERATOR_MCP_INBOUND_TOKEN in .env (generate: openssl rand -hex 32)+docker compose -f docker-compose.yml -f docker-compose.mcp.yml up -d --build+```++A plain `docker compose up` is unchanged (3 containers); this adds a 4th, `vulnerator-mcp`,+reachable on the internal network at `http://vulnerator-mcp:8700` (upstream Hermes at+`http://ooda-agent:8642`). Key properties:++- **Host publication is OFF by default.** The service declares no `ports:` block (internal+ network only, like `playwright-mcp`/`juice-shop`). To publish on a **controlled** machine,+ uncomment the `ports:` block in `docker-compose.mcp.yml` (optionally set+ `VULNERATOR_MCP_HOST_PORT`).+- **Mandatory, fail-closed inbound token.** The streamable-HTTP mode refuses to start without+ `VULNERATOR_MCP_INBOUND_TOKEN`, and every request must carry+ `Authorization: Bearer <VULNERATOR_MCP_INBOUND_TOKEN>` (a dedicated `/healthz` route is the one+ exact-match exception). This token is **separate** from `HERMES_API_SERVER_KEY`.+- **Threat model (read this).** The inbound token gates only the *clients → vulnerator-mcp* edge.+ It does **not** re-protect the pre-existing `:8642` host exposure, which stays under its own+ `HERMES_API_SERVER_KEY` Bearer (see "Security note" above). Publishing the MCP port is an+ explicit operator choice; until you do, the token guards an internal-network edge.+## Start clean between exercisesSo that each pentest starts without remembering anything from the previous one (conversation historydiff --git a/VERSION b/VERSIONindex f0bb29e..88c5fb8 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-1.3.0+1.4.0diff --git a/docker-compose.mcp.yml b/docker-compose.mcp.ymlnew file mode 100644index 0000000..894f784--- /dev/null+++ b/docker-compose.mcp.yml@@ -0,0 +1,73 @@+# =============================================================================+# docker-compose.mcp.yml — OPTIONAL MCP front door over Hermes' :8642 runs API.+# =============================================================================+# OPTIONAL layered override, NOT part of the base stack (docker-compose.yml). Bring it up+# explicitly alongside the base to expose a thin MCP server (vulnerator-mcp) that external+# MCP clients (Claude Code / Kiro / BugTraceAI) can use to trigger/observe/steer/stop a+# Hermes OODA pentest as MCP tools:+#+# docker compose -f docker-compose.yml -f docker-compose.mcp.yml up -d --build+#+# A plain `docker compose up` is UNCHANGED (3 containers: kali, ooda-agent, playwright-mcp).+# This file adds a 4th container only when brought up explicitly. The service lives on the+# SAME internal docker network: it reaches Hermes at http://ooda-agent:8642, and in-docker+# MCP consumers reach it at http://vulnerator-mcp:8700 (service DNS).+#+# It wraps, does NOT replace, the HTTP API: it exposes ONLY the runs lifecycle (no raw+# kali_run, no /v1/chat/completions) so the client stays a trigger/observer, never the brain.+#+# SECURITY (read this): this service is FAIL-CLOSED on VULNERATOR_MCP_INBOUND_TOKEN — it will+# NOT start without it (both at the compose `:?` level below and inside the server). That+# token gates the clients -> vulnerator-mcp edge ONLY; it is a SEPARATE token from+# HERMES_API_SERVER_KEY and does NOT re-protect the pre-existing :8642 host exposure (which+# stays under its own Bearer). By default NO host port is published (internal network only).+# This MCP layer adds REACHABILITY, not safety: the engine has no scope-guard/consent/audit.++services:+ vulnerator-mcp:+ build:+ context: .+ dockerfile: docker/mcp/Dockerfile+ platforms:+ - linux/arm64+ - linux/amd64+ image: vulnerator-ai-mcp:dev+ environment:+ # Hop upstream a Hermes por DNS de servicio (red interna docker).+ HERMES_API_BASE_URL: "http://ooda-agent:8642"+ # Bearer de PASS-THROUGH upstream — fail-closed `:?` como el ooda-agent base.+ HERMES_API_SERVER_KEY: "${HERMES_API_SERVER_KEY:?Falta HERMES_API_SERVER_KEY - genera uno con 'openssl rand -hex 32' (min 8 chars) y ponlo en .env}"+ # Token de ENTRADA (clientes -> vulnerator-mcp). REQUERIDO, fail-closed `:?`: traer este+ # archivo sin token aborta con mensaje claro (defensa en profundidad: compose + proceso).+ # Separado de HERMES_API_SERVER_KEY (gatea otra frontera). Solo necesario para ESTE+ # servicio opt-in; el stack base de 3 contenedores no lo referencia.+ VULNERATOR_MCP_INBOUND_TOKEN: "${VULNERATOR_MCP_INBOUND_TOKEN:?Falta VULNERATOR_MCP_INBOUND_TOKEN - genera uno con 'openssl rand -hex 32' y ponlo en .env (lo exige el servicio MCP streamable-http)}"+ VULNERATOR_MCP_TRANSPORT: "streamable-http"+ # Bind DENTRO del contenedor (no es una publicacion al host).+ VULNERATOR_MCP_HOST: "0.0.0.0"+ VULNERATOR_MCP_PORT: "8700"+ # Host publication is OPT-IN and OFF by default: with NO ports: block the service is+ # reachable ONLY on the internal docker network (http://vulnerator-mcp:8700), exactly+ # like playwright-mcp/juice-shop. To publish on a CONTROLLED machine, UNCOMMENT the block+ # below (set VULNERATOR_MCP_HOST_PORT in .env or accept the 8700 default). Publishing+ # exposes the no-guardrails engine's trigger API to the host — do it deliberately and keep+ # the inbound token secret. (Do NOT use ":8700": that publishes on a RANDOM host port.)+ # ports:+ # - "${VULNERATOR_MCP_HOST_PORT:-8700}:8700"+ depends_on:+ # service_started (implicito): el ooda-agent base NO define healthcheck, asi que+ # service_healthy no es usable contra el. La readiness se maneja en la capa de tools:+ # cada tool devuelve upstream_unreachable hasta que Hermes esta vivo, asi que este+ # servidor puede arrancar antes de que Hermes termine de bootear sin romperse. NO+ # subir esto a service_healthy.+ - ooda-agent+ restart: unless-stopped+ # HEALTHCHECK: stdlib python (python:3.13-slim no trae curl) sondeando la ruta DEDICADA+ # /healthz, que el middleware de auth deja abierta con un carve-out de match exacto (no+ # necesita el token). "/" es el endpoint MCP y SI requiere token.+ healthcheck:+ test: ["CMD", "python3", "-c", "import sys,os,urllib.request; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:%s/healthz' % os.environ.get('VULNERATOR_MCP_PORT','8700'), timeout=3).status==200 else 1)"]+ interval: 15s+ timeout: 5s+ retries: 5+ start_period: 20sdiff --git a/docker/mcp/Dockerfile b/docker/mcp/Dockerfilenew file mode 100644index 0000000..55c9922--- /dev/null+++ b/docker/mcp/Dockerfile@@ -0,0 +1,61 @@+# vulnerator-mcp — front door MCP FINO sobre la API de runs de Hermes (:8642).+#+# UNA imagen, DOS modos de ejecucion (los selecciona entrypoint.sh):+# - stdio (default) : el cliente arranca el proceso (docker run -i). Superficie cero.+# - streamable-http : servicio opt-in (docker-compose.mcp.yml), fail-closed en el+# token de entrada VULNERATOR_MCP_INBOUND_TOKEN.+#+# Multi-arch (linux/arm64 + linux/amd64). Base python:3.13-slim (NO Kali): este componente+# es un wrapper HTTP fino, no necesita CLIs de pentest.+#+# Build (desde la raiz del repo):+# docker buildx build --platform linux/arm64,linux/amd64 \+# -f docker/mcp/Dockerfile -t vulnerator-ai-mcp:dev .++# syntax=docker/dockerfile:1++FROM python:3.13-slim++ENV PIP_NO_CACHE_DIR=1 \+ PIP_DISABLE_PIP_VERSION_CHECK=1++WORKDIR /opt/vulnerator-mcp++# Manifiesto de dependencias (mcp>=1.28,<2 ; httpx ; anyio>=4 ; uvicorn). Versiones y+# rationale en requirements.txt.+COPY docker/mcp/requirements.txt ./requirements.txt+RUN pip install --no-cache-dir -r requirements.txt++# Modulos del servidor. mcp_tool_logic/hermes_api_client son SDK-free (testeables sin mcp);+# vulnerator_mcp_server es el plano de control FastMCP que los importa.+COPY docker/mcp/mcp_tool_logic.py ./mcp_tool_logic.py+COPY docker/mcp/hermes_api_client.py ./hermes_api_client.py+COPY docker/mcp/vulnerator_mcp_server.py ./vulnerator_mcp_server.py+COPY docker/mcp/entrypoint.sh /entrypoint.sh+RUN chmod +x /entrypoint.sh++# Config por defecto (overridable por entorno). El default de proceso es stdio.+ENV VULNERATOR_MCP_HOST=0.0.0.0 \+ VULNERATOR_MCP_PORT=8700 \+ HERMES_API_BASE_URL=http://ooda-agent:8642 \+ VULNERATOR_MCP_TRANSPORT=stdio++# EXPOSE es documentacion; solo tiene sentido en modo streamable-http. 8700 no choca con+# 8642 (Hermes), 8900/8901 (kali-mcp + artifacts), 8931 (playwright-mcp).+EXPOSE 8700++# HEALTHCHECK: python:3.13-slim NO trae curl (la base Kali si), asi que se sondea con la+# stdlib (igual idioma que los healthchecks python/node del compose). Solo tiene sentido en+# modo streamable-http: sondea la ruta DEDICADA /healthz (el middleware de auth la deja+# abierta con un carve-out de match exacto), que devuelve 200. En stdio no hay listener y el+# contenedor lo arranca el cliente, asi que el healthcheck de compose no aplica.+HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=5 \+ CMD python3 -c "import sys,urllib.request; \+import os; \+url='http://127.0.0.1:%s/healthz' % os.environ.get('VULNERATOR_MCP_PORT','8700'); \+sys.exit(0 if urllib.request.urlopen(url, timeout=3).status==200 else 1)" || exit 1++# El entrypoint resuelve el transporte (arg o env) y arranca el servidor. CMD vacio por+# defecto -> stdio.+ENTRYPOINT ["/entrypoint.sh"]+CMD []diff --git a/docker/mcp/entrypoint.sh b/docker/mcp/entrypoint.shnew file mode 100644index 0000000..8c8a030--- /dev/null+++ b/docker/mcp/entrypoint.sh@@ -0,0 +1,34 @@+#!/bin/sh+# Entrypoint de vulnerator-mcp: UNA imagen, DOS modos de ejecucion.+#+# Selecciona el transporte y arranca el servidor. Dos fuentes equivalentes (el arg tiene+# prioridad sobre la env var):+# - Argumento $1: mcp|stdio -> stdio ; http|streamable-http -> streamable-http.+# - VULNERATOR_MCP_TRANSPORT: stdio (default) | streamable-http.+#+# stdio es el default (superficie de red cero; el cliente arranca el proceso con+# `docker run -i`). streamable-http es fail-closed: el servidor se niega a arrancar sin+# VULNERATOR_MCP_INBOUND_TOKEN (ver vulnerator_mcp_server.py).+set -eu++mode="${1:-}"++case "$mode" in+ http|streamable-http)+ VULNERATOR_MCP_TRANSPORT="streamable-http"+ ;;+ mcp|stdio)+ VULNERATOR_MCP_TRANSPORT="stdio"+ ;;+ "")+ # Sin argumento: respeta la env var; default stdio.+ VULNERATOR_MCP_TRANSPORT="${VULNERATOR_MCP_TRANSPORT:-stdio}"+ ;;+ *)+ echo "ERROR: modo desconocido '$mode' (usa: stdio|mcp | http|streamable-http)" >&2+ exit 2+ ;;+esac++export VULNERATOR_MCP_TRANSPORT+exec python3 vulnerator_mcp_server.pydiff --git a/docker/mcp/hermes_api_client.py b/docker/mcp/hermes_api_client.pynew file mode 100644index 0000000..6410014--- /dev/null+++ b/docker/mcp/hermes_api_client.py@@ -0,0 +1,347 @@+"""Cliente FINO de la API de runs de Hermes en `:8642` (hop upstream del wrapper MCP).++Este módulo habla con la API OpenAI-compatible de runs que sirve Hermes+(`nousresearch/hermes-agent`) en `:8642`. NO contiene lógica de pentest: solo traduce las+cinco operaciones del ciclo de vida (crear/estado/eventos/steer/stop) + `health` a+llamadas HTTP, poniendo el Bearer de PASS-THROUGH leído de `HERMES_API_SERVER_KEY` en cada+petición. El wrapper MCP (``vulnerator_mcp_server.py``) delega aquí.++Disciplina (igual que docker/kali/*):+ - DATO NO CONFIABLE: el objeto run, los eventos y todos sus campos (`delta`/`text`/+ `preview`/`output`/`message`) se reenvían VERBATIM; nunca se interpretan ni se usan+ para construir una acción. Pueden contener salida cruda de herramientas e incluso+ instrucciones embebidas (prompt-injection): se transportan como datos, no como órdenes.+ - VERSION-TOLERANTE: el contrato de `:8642` es de Hermes, no nuestro. No se hace un+ parseo de esquema fijo; el objeto run se pasa OPACO. La ÚNICA cadena de wire fija en el+ flujo de control es el tipo de evento terminal ``"run.completed"`` (para reconocer el+ fin del stream al paginar). La versión upstream se LEE de `GET /health` y se reporta+ verbatim; nunca se ramifica por ella en código.+ - SIN registro de runs ni caché de eventos: stateless; Hermes es dueño del `run_id`. El+ cursor del stream es el campo `seq` (int monótono) que trae cada evento.++SDK-free a propósito: NO importa `mcp`/`anyio`, de modo que el parser SSE + cursor y el+mapeo de errores se cubren con tests unitarios sin el SDK (igual que `tool_streaming`/+`scope_guard` viven aparte de `kali_mcp_server`). Única dependencia no-stdlib: `httpx`+(justificada por el stream SSE; ver requirements.txt).+"""++from __future__ import annotations++import json+import sys+import time+from typing import Any, Iterable, Iterator, Optional++import httpx++# Tipo del evento terminal del ciclo de vida (único string de wire fijo en control de+# flujo; version-tolerancia, ver docstring del módulo).+TERMINAL_EVENT = "run.completed"++# Topes del batch de `stream_run_events` (ver design §4.1). Se definen aquí porque el+# parser SSE los aplica; el servidor MCP reutiliza estos defaults.+DEFAULT_MAX_EVENTS = 200+# Presupuesto de bytes por batch: muy por debajo del tope de 1 MiB de un único evento SSE+# del transporte streamable-http (mismo motivo por el que existe read_scan_findings en+# Kali). 256 KiB deja margen amplio tras el overhead del sobre MCP.+DEFAULT_BYTE_BUDGET = 256 * 1024+# Presupuesto wall-clock por batch: una llamada a la tool nunca cuelga al cliente esperando+# un stream silencioso.+DEFAULT_WAIT_SECONDS = 25.0+++def _error_envelope(message: str, code: str, type_: str = "upstream_error") -> dict[str, Any]:+ """Construye un sobre de error OpenAI-style homogéneo (igual forma que el de Hermes).++ `message` es DATO NO CONFIABLE si proviene de upstream; aquí solo se encapsula, no se+ interpreta. El wrapper lo reenvía verbatim al cliente MCP.+ """+ return {"error": {"message": message, "type": type_, "param": None, "code": code}}+++def parse_sse_events(+ lines: Iterable[str],+ *,+ after_seq: int = 0,+ max_events: Optional[int] = None,+ byte_budget: int = DEFAULT_BYTE_BUDGET,+ wait_seconds: Optional[float] = None,+ _clock: Any = time.monotonic,+) -> Iterator[dict[str, Any]]:+ """Parser SSE PURO (sin socket): convierte líneas de wire en dicts de evento.++ Es la pieza de mayor valor de test unitario: se le alimentan líneas crudas (incluido el+ comentario ``: open``, `data:` multilínea y un evento malformado) y produce los dicts de+ evento ya filtrados por cursor. NO abre red: ``iter_events`` le pasa el iterador de+ líneas de ``httpx``.++ Protocolo de wire observado (hermes-agent 0.22.0, investigación §10.4):+ - El campo SSE ``event:`` NO se usa; el tipo vive dentro del JSON (campo ``event``).+ - Cada mensaje es ``id: <n>`` + ``data: <json>``; el stream abre con ``: open``.+ - Cada evento JSON trae ``event`` (tipo), ``run_id``, ``timestamp`` (float), ``seq``+ (int monótono). ``seq`` ES EL CURSOR.++ Reglas:+ - Se ignoran líneas en blanco (frontera de evento), comentarios (``:`` al inicio, p.+ ej. ``: open``) y la línea ``id:`` (se usa el ``seq`` del JSON, autoritativo).+ - Se acumulan las líneas ``data:`` del evento actual (SSE permite ``data:`` multilínea).+ - En la frontera de evento se hace ``json.loads``. Si falla el parseo o falta/!int el+ ``seq`` -> SE OMITE ese evento (best-effort, como read_findings salta líneas+ corruptas); nunca se rompe el stream por un payload malformado/oversized.+ - ``seq <= after_seq`` -> se omite (ya entregado): dedup entre páginas.+ - En otro caso se hace ``yield`` del dict de evento COMPLETO sin tocar (opaco).++ Condiciones de parada (frontera de batch; NO son error):+ - ``max_events`` alcanzado.+ - presupuesto de bytes (``byte_budget``) de eventos serializados acumulados superado.+ - ``wait_seconds`` (float) wall-clock agotado.+ - evento terminal visto (``event == "run.completed"``): se hace yield y se para.+ - fin del iterador de líneas (stream cerrado por upstream).+ """+ effective_max = max_events if (max_events is not None and max_events > 0) else None+ deadline = None+ if wait_seconds is not None and wait_seconds > 0:+ deadline = _clock() + wait_seconds++ emitted = 0+ bytes_seen = 0+ data_parts: list[str] = []++ def _flush() -> Optional[dict[str, Any]]:+ """Procesa el evento acumulado. Devuelve el dict a emitir o None (omitir)."""+ if not data_parts:+ return None+ raw = "\n".join(data_parts)+ try:+ event = json.loads(raw)+ except (ValueError, TypeError):+ return None # best-effort: evento malformado se omite+ if not isinstance(event, dict):+ return None+ seq = event.get("seq")+ if not isinstance(seq, int) or isinstance(seq, bool):+ return None # sin cursor usable -> se omite+ if seq <= after_seq:+ return None # ya entregado (dedup entre páginas)+ return event++ for raw_line in lines:+ line = raw_line.rstrip("\n").rstrip("\r")++ if line == "":+ # Frontera de evento: procesa lo acumulado.+ event = _flush()+ data_parts = []+ if event is None:+ # Nada que emitir: si ya se agotó el tiempo, corta aquí (no hay evento a+ # medias que perder).+ if deadline is not None and _clock() >= deadline:+ return+ continue+ bytes_seen += len(json.dumps(event))+ yield event+ emitted += 1+ if event.get("event") == TERMINAL_EVENT:+ return+ if effective_max is not None and emitted >= effective_max:+ return+ if bytes_seen >= byte_budget:+ return+ # El corte por tiempo se evalúa DESPUÉS de emitir un evento completo, de modo que+ # un evento ya totalmente bufferizado nunca se pierde por la deadline.+ if deadline is not None and _clock() >= deadline:+ return+ continue++ if line.startswith(":"):+ continue # comentario (p. ej. ": open")+ if line.startswith("id:"):+ continue # id de wire: ignorado, se usa el seq del JSON+ if line.startswith("data:"):+ # SSE: tras "data:" se quita UN espacio opcional.+ payload = line[5:]+ if payload.startswith(" "):+ payload = payload[1:]+ data_parts.append(payload)+ continue+ # Cualquier otra línea (p. ej. "event:") se ignora: el tipo vive en el JSON.++ # Fin del iterador o corte por tiempo: procesa el último evento sin frontera en blanco.+ event = _flush()+ if event is not None:+ yield event+++class HermesApiClient:+ """Cliente FINO de la API de runs de Hermes en `:8642`.++ Construido con la URL base y el Bearer de pass-through. Cada método pone+ ``Authorization: Bearer <api_key>`` (+ ``Content-Type: application/json`` en cuerpos).+ Los retornos son el payload UPSTREAM reenviado opaco, o un sobre de error estructurado+ ``{"error": {...}}`` (ver mapeo en cada método). Version-tolerante: no parsea esquema+ fijo; la terminalidad se deriva de los booleanos del objeto run, nunca del string+ ``status``.+ """++ def __init__(self, base_url: str, api_key: str, *, timeout: float = 30.0) -> None:+ self._base_url = base_url.rstrip("/")+ self._api_key = api_key+ self._timeout = timeout++ # ------------------------------------------------------------------ helpers++ def _headers(self, *, json_body: bool = False) -> dict[str, str]:+ headers = {"Authorization": "Bearer %s" % self._api_key}+ if json_body:+ headers["Content-Type"] = "application/json"+ return headers++ def _handle_response(self, resp: httpx.Response) -> dict[str, Any]:+ """Mapea una respuesta HTTP a dict (payload opaco o sobre de error).++ - 2xx con JSON -> se devuelve el JSON tal cual (opaco).+ - non-2xx con sobre de error JSON (``{"error": {...}}``) -> se devuelve verbatim.+ - non-2xx sin sobre parseable -> sobre sintetizado ``upstream_error`` con un+ snippet corto del cuerpo (recortado; no se interpola payload grande).+ - 2xx sin JSON parseable -> sobre ``upstream_error`` (forma inesperada).+ """+ try:+ body = resp.json()+ except (ValueError, json.JSONDecodeError):+ body = None++ if resp.is_success:+ if isinstance(body, dict):+ return body+ snippet = (resp.text or "")[:200]+ self._warn("respuesta 2xx no-JSON de %s: %s" % (resp.url, snippet))+ return _error_envelope(+ "upstream returned a non-JSON 2xx body: %s" % snippet,+ code="upstream_error",+ )++ # non-2xx+ if isinstance(body, dict) and isinstance(body.get("error"), dict):+ code = body["error"].get("code", "upstream_error")+ self._warn("error upstream %s (%s) en %s" % (resp.status_code, code, resp.url))+ return body # sobre OpenAI-style verbatim (run_not_found/run_not_accepting_steer/...)++ snippet = (resp.text or "")[:200]+ self._warn("non-2xx %s sin sobre en %s: %s" % (resp.status_code, resp.url, snippet))+ return _error_envelope(+ "upstream HTTP %s: %s" % (resp.status_code, snippet),+ code="upstream_error",+ )++ def _unreachable(self, exc: Exception) -> dict[str, Any]:+ """Sobre estructurado cuando no se puede alcanzar `:8642` (DNS/refused/TLS)."""+ self._warn("Hermes inalcanzable en %s: %s" % (self._base_url, exc))+ return _error_envelope(+ "cannot reach Hermes at %s: %s" % (self._base_url, exc),+ code="upstream_unreachable",+ type_="upstream_unreachable",+ )++ @staticmethod+ def _warn(message: str) -> None:+ """Log a stderr de una línea; nunca interpola payloads grandes no confiables."""+ sys.stderr.write("[vulnerator-mcp] %s\n" % message)++ def _request(self, method: str, path: str, *, json_body: Any = None,+ extra_headers: Optional[dict[str, str]] = None) -> dict[str, Any]:+ url = "%s%s" % (self._base_url, path)+ headers = self._headers(json_body=json_body is not None)+ if extra_headers:+ headers.update(extra_headers)+ try:+ resp = httpx.request(+ method, url, headers=headers, json=json_body, timeout=self._timeout+ )+ except httpx.HTTPError as exc:+ return self._unreachable(exc)+ return self._handle_response(resp)++ # ------------------------------------------------------------------ API++ def health(self) -> dict[str, Any]:+ """GET /health -> {status, platform, version} (investigación §10.1).++ ``version`` se reporta al cliente VERBATIM y NUNCA se usa para ramificar en código+ (version-tolerancia). Es el único sitio donde se expone una versión upstream.+ """+ return self._request("GET", "/health")++ def create_run(+ self,+ input: str,+ *,+ session_id: Optional[str] = None,+ instructions: Optional[str] = None,+ previous_response_id: Optional[str] = None,+ idempotency_key: Optional[str] = None,+ ) -> dict[str, Any]:+ """POST /v1/runs -> {run_id, status, replayed} (investigación §10.3).++ Envía ``Idempotency-Key`` como CABECERA (no en el cuerpo) solo cuando se pasa no+ vacía. Los opcionales vacíos/None se OMITEN del cuerpo JSON.+ ``conversation_history`` se OMITE a propósito del wrapper (design §3): la+ continuidad se expresa con ``previous_response_id``/``session_id``.+ """+ body: dict[str, Any] = {"input": input}+ if session_id:+ body["session_id"] = session_id+ if instructions:+ body["instructions"] = instructions+ if previous_response_id:+ body["previous_response_id"] = previous_response_id+ extra = {"Idempotency-Key": idempotency_key} if idempotency_key else None+ return self._request("POST", "/v1/runs", json_body=body, extra_headers=extra)++ def get_run(self, run_id: str) -> dict[str, Any]:+ """GET /v1/runs/{run_id} -> objeto hermes.run completo (opaco; §10.5).++ La terminalidad se lee de los booleanos ``completed``/``interrupted`` del objeto,+ NUNCA del string ``status``.+ """+ return self._request("GET", "/v1/runs/%s" % run_id)++ def steer_run(self, run_id: str, input: str) -> dict[str, Any]:+ """POST /v1/runs/{run_id}/steer. El 409 run_not_accepting_steer se reenvía verbatim (§10.6)."""+ return self._request("POST", "/v1/runs/%s/steer" % run_id, json_body={"input": input})++ def stop_run(self, run_id: str) -> dict[str, Any]:+ """POST /v1/runs/{run_id}/stop -> objeto run completo (terminal NO garantizado 'cancelled'; §10.5)."""+ return self._request("POST", "/v1/runs/%s/stop" % run_id)++ def iter_events(+ self,+ run_id: str,+ *,+ after_seq: int = 0,+ max_events: Optional[int] = None,+ wait_seconds: Optional[float] = None,+ ) -> Iterator[dict[str, Any]]:+ """GET /v1/runs/{run_id}/events (SSE). Hace yield de dicts de evento con seq > after_seq.++ Abre ``httpx.stream`` y delega el parseo en ``parse_sse_events`` (puro). Una+ excepción de conexión se traduce a UN único evento-error estructurado+ (``upstream_unreachable``) y se corta; un timeout de lectura es frontera de batch+ normal (no error), gestionado por ``wait_seconds`` dentro del parser.+ """+ url = "%s/v1/runs/%s/events" % (self._base_url, run_id)+ headers = self._headers()+ try:+ with httpx.stream("GET", url, headers=headers, timeout=self._timeout) as resp:+ if not resp.is_success:+ # Lee el cuerpo para mapear el sobre de error y emítelo como un evento-error.+ resp.read()+ yield {"_error": self._handle_response(resp).get("error")}+ return+ yield from parse_sse_events(+ resp.iter_lines(),+ after_seq=after_seq,+ max_events=max_events,+ wait_seconds=wait_seconds,+ )+ except httpx.HTTPError as exc:+ yield {"_error": self._unreachable(exc)["error"]}diff --git a/docker/mcp/mcp_tool_logic.py b/docker/mcp/mcp_tool_logic.pynew file mode 100644index 0000000..37d788a--- /dev/null+++ b/docker/mcp/mcp_tool_logic.py@@ -0,0 +1,92 @@+"""Lógica PURA del wrapper MCP (sin `mcp`/`httpx`): scope-folding + validación de entrada.++Vive aparte de ``vulnerator_mcp_server.py`` a propósito (igual que ``scope_guard``/+``tool_streaming`` viven aparte de ``kali_mcp_server``): ese módulo importa `mcp` (FastMCP),+que no está en el venv de dev. Estas funciones son composición de strings y validación de+forma, así que se cubren con tests unitarios SIN el SDK.++Disciplina: ``scope`` es REQUERIDO pero ADVISORY. El wrapper NO impone scope ni añade+seguridad; solo DOBLA el scope dentro del prompt como metadato de claridad del operador.+``input``/``scope``/``run_id`` son DATO NO CONFIABLE: aquí solo se validan de forma+(presencia/no-vacío) y, en el caso de ``scope``, se concatenan al prompt verbatim.+"""++from __future__ import annotations++from typing import Any, Optional++# Prefijo con el que se dobla el scope dentro del input (metadato ADVISORY, no un guard).+SCOPE_PREFIX = "AUTHORIZED SCOPE (operator-declared, advisory):"+++def invalid_request(message: str) -> dict[str, Any]:+ """Sobre de error OpenAI-style para fallos de validación LOCALES (sin llamar upstream)."""+ return {+ "error": {+ "message": message,+ "type": "invalid_request_error",+ "param": None,+ "code": "invalid_request",+ }+ }+++def fold_scope_into_input(input: str, scope: str) -> str:+ """Dobla ``scope`` dentro del ``input`` como una línea delimitada (design §5).++ NO impone nada: es un afordance de claridad para el operador que conduce el cliente MCP.+ Formato: una línea ``AUTHORIZED SCOPE ...: <scope>``, línea en blanco, luego el input+ original verbatim.+ """+ return "%s %s\n\n%s" % (SCOPE_PREFIX, scope, input)+++def validate_start_pentest(input: Any, scope: Any) -> Optional[dict[str, Any]]:+ """Valida ``input``/``scope`` de ``start_pentest``. Devuelve un sobre de error o None.++ Ambos requeridos, string no vacío (tras strip). Vacío/no-string -> ``invalid_request``+ SIN llamada upstream (fail-closed). La longitud NO se capa (Hermes es dueño de los+ límites del prompt).+ """+ if not isinstance(input, str) or not input.strip():+ return invalid_request("'input' es requerido y no puede estar vacío")+ if not isinstance(scope, str) or not scope.strip():+ return invalid_request("'scope' es requerido y no puede estar vacío (advisory)")+ return None+++def validate_run_id(run_id: Any) -> Optional[dict[str, Any]]:+ """Valida que ``run_id`` sea un string no vacío. Devuelve un sobre de error o None.++ NO valida el formato ``run_`` (Hermes es dueño del espacio de ids): se reenvía y se deja+ que upstream responda ``run_not_found`` si no existe.+ """+ if not isinstance(run_id, str) or not run_id.strip():+ return invalid_request("'run_id' es requerido y no puede estar vacío")+ return None+++def validate_steer(run_id: Any, input: Any) -> Optional[dict[str, Any]]:+ """Valida ``run_id`` + ``input`` de ``steer_run``. Devuelve un sobre de error o None."""+ err = validate_run_id(run_id)+ if err is not None:+ return err+ if not isinstance(input, str) or not input.strip():+ return invalid_request("'input' es requerido y no puede estar vacío")+ return None+++def clamp_cursor(cursor: Any) -> int:+ """Normaliza el cursor a un int >= 0 (negativo/no-int -> 0)."""+ if not isinstance(cursor, int) or isinstance(cursor, bool) or cursor < 0:+ return 0+ return cursor+++def normalize_optional_positive(value: Any) -> Optional[Any]:+ """Normaliza max_events/wait_seconds: no-positivo o no-numérico -> None (usa el default interno)."""+ if isinstance(value, bool):+ return None+ if isinstance(value, (int, float)) and value > 0:+ return value+ return Nonediff --git a/docker/mcp/requirements.txt b/docker/mcp/requirements.txtnew file mode 100644index 0000000..2a7485f--- /dev/null+++ b/docker/mcp/requirements.txt@@ -0,0 +1,34 @@+# Manifiesto de dependencias de la imagen vulnerator-mcp. Es la fuente de verdad de lo+# que se instala con pip en docker/mcp/Dockerfile. Componente FINO: envuelve la API de+# runs de Hermes (:8642); no corre lógica de pentest, así que su superficie de deps es+# mínima (stdlib pura salvo las tres entradas de abajo).++# SDK oficial de MCP (modelcontextprotocol/python-sdk). Lo usa el SERVIDOR+# vulnerator-mcp (docker/mcp/vulnerator_mcp_server.py: FastMCP + transportes+# stdio / streamable-HTTP) que consumen los clientes externos (Claude Code, Kiro,+# BugTraceAI).+#+# Se fija a la línea 1.x (<2) a propósito, IGUAL que docker/kali/requirements.txt: el+# servidor usa la API 1.x de FastMCP, que v2 renombra/elimina. Mantener servidor y+# clientes en la misma era de protocolo evita un desajuste cliente/servidor. El+# contenedor Kali vivo corre mcp==1.30.0 (dentro de este rango): prueba de que la línea+# soporta `FastMCP.run(transport="streamable-http")` y `streamable_http_app()`.+mcp>=1.28,<2++# httpx: cliente HTTP del hop a :8642. Justificado (no es stdlib pura por un motivo+# concreto): GET /v1/runs/{id}/events es un stream SSE de larga vida que httpx.stream(...)+# consume limpiamente línea a línea; urllib de la stdlib no streamea SSE de forma+# cómoda. Todo lo demás del cliente es request/response plano pero se mantiene sobre el+# mismo cliente para una única ruta de auth/transporte.+httpx++# anyio: dependencia del transporte asíncrono del SDK mcp (streamable-HTTP), igual que en+# la imagen Kali. Se fija >=4 por el mismo motivo (API async de esa era).+anyio>=4++# uvicorn: servidor ASGI con el que se sirve la app streamable-http de FastMCP CUANDO la+# envolvemos con el middleware Bearer de auth de entrada (no podemos usar+# `mcp.run(transport="streamable-http")` directamente porque necesitamos interponer el+# middleware). Es dependencia transitiva del SDK mcp (streamable-HTTP), pero se declara+# explícita porque este servidor la importa y la invoca directamente (fail-closed si falta).+uvicorndiff --git a/docker/mcp/tests/__init__.py b/docker/mcp/tests/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/docker/mcp/tests/test_hermes_api_client.py b/docker/mcp/tests/test_hermes_api_client.pynew file mode 100644index 0000000..7a7c5fd--- /dev/null+++ b/docker/mcp/tests/test_hermes_api_client.py@@ -0,0 +1,239 @@+"""Tests del cliente :8642 y el parser SSE (`docker/mcp/hermes_api_client.py`).++NO importan `mcp`/FastMCP: solo el módulo SDK-free `hermes_api_client` + httpx + pytest+(mismo patrón que `docker/kali/tests/test_scope_guard.py`). Cubren:+ - El parser SSE puro: wire `: open`/`id:`/`data:` (incl. multilínea), cursor por `seq`,+ dedup entre páginas, skip best-effort de eventos malformados, y los topes de batch+ (max_events, presupuesto de bytes, wait_seconds) + corte en el evento terminal.+ - HermesApiClient con httpx.MockTransport: Bearer puesto, Idempotency-Key solo cuando se+ da, y el mapeo de cada forma de error (sobre JSON, non-2xx sin sobre, fallo de conexión).+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++import httpx+import pytest++# El módulo bajo prueba vive en docker/mcp/ (el servidor MCP NO se importa: arrastra `mcp`).+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import hermes_api_client as hac # noqa: E402+++# ------------------------------------------------------------------ parser SSE+++def _sse_message(seq: int, event: str = "message.delta", **extra) -> str:+ """Construye un mensaje SSE `id:`+`data:` con un evento JSON de `seq`/`event`."""+ payload = {"event": event, "run_id": "run_x", "timestamp": 1.0, "seq": seq}+ payload.update(extra)+ return "id: %d\ndata: %s\n\n" % (seq, json.dumps(payload))+++def _lines(raw: str):+ """Itera líneas como lo haría httpx.Response.iter_lines (sin el '\\n' final)."""+ return iter(raw.split("\n"))+++def test_parser_basic_wire_and_cursor():+ raw = ": open\n\n" + _sse_message(1) + _sse_message(2) + _sse_message(3)+ events = list(hac.parse_sse_events(_lines(raw)))+ assert [e["seq"] for e in events] == [1, 2, 3]+ # Opaco: el dict de evento se entrega sin tocar.+ assert events[0]["event"] == "message.delta"+ assert events[0]["run_id"] == "run_x"+++def test_parser_multiline_data():+ # SSE permite `data:` multilínea: cada línea `data:` se une con '\n'. Se usa un JSON+ # pretty-printed (los '\n' entre elementos estructurales son JSON válido tras el join).+ payload = {"event": "message.interim", "run_id": "run_x", "timestamp": 1.0, "seq": 5,+ "text": "a"}+ dumped = json.dumps(payload, indent=2) # multilínea, válido+ data_lines = "".join("data: %s\n" % ln for ln in dumped.split("\n"))+ raw = "id: 5\n" + data_lines + "\n"+ events = list(hac.parse_sse_events(_lines(raw)))+ assert len(events) == 1 and events[0]["seq"] == 5 and events[0]["text"] == "a"+++def test_parser_dedup_by_after_seq():+ raw = _sse_message(1) + _sse_message(2) + _sse_message(3)+ events = list(hac.parse_sse_events(_lines(raw), after_seq=2))+ assert [e["seq"] for e in events] == [3]+++def test_parser_skips_malformed_and_missing_seq():+ good = _sse_message(1)+ bad_json = "id: 2\ndata: {not json}\n\n"+ no_seq = "id: 3\ndata: %s\n\n" % json.dumps({"event": "x", "run_id": "r"})+ good2 = _sse_message(4)+ events = list(hac.parse_sse_events(_lines(good + bad_json + no_seq + good2)))+ assert [e["seq"] for e in events] == [1, 4]+++def test_parser_stops_on_terminal_event():+ raw = _sse_message(1) + _sse_message(2, event=hac.TERMINAL_EVENT) + _sse_message(3)+ events = list(hac.parse_sse_events(_lines(raw)))+ # Se para TRAS emitir el evento terminal; el seq 3 no se entrega.+ assert [e["seq"] for e in events] == [1, 2]+ assert events[-1]["event"] == hac.TERMINAL_EVENT+++def test_parser_max_events_cap():+ raw = "".join(_sse_message(i) for i in range(1, 11))+ events = list(hac.parse_sse_events(_lines(raw), max_events=3))+ assert [e["seq"] for e in events] == [1, 2, 3]+++def test_parser_byte_budget_cap():+ # Un presupuesto de bytes diminuto corta tras el primer evento.+ raw = "".join(_sse_message(i, text="x" * 50) for i in range(1, 6))+ events = list(hac.parse_sse_events(_lines(raw), byte_budget=10))+ assert len(events) == 1 and events[0]["seq"] == 1+++def test_parser_wait_seconds_boundary():+ # Reloj simulado: la deadline se cruza antes de procesar la segunda frontera.+ ticks = iter([0.0, 0.0, 100.0, 100.0, 100.0, 100.0])+ raw = _sse_message(1) + _sse_message(2) + _sse_message(3)+ events = list(hac.parse_sse_events(+ _lines(raw), wait_seconds=1.0, _clock=lambda: next(ticks)+ ))+ # Al menos el primero se emite; el corte por tiempo impide procesar todos.+ assert events and events[0]["seq"] == 1+ assert len(events) < 3+++# ------------------------------------------------------------------ HermesApiClient+++def _client_with(handler):+ """HermesApiClient cuyo httpx usa un MockTransport con `handler`.++ Se parchea httpx.request / httpx.stream para inyectar el transporte mock, ya que el+ cliente usa las funciones de módulo de httpx (no una instancia inyectada).+ """+ transport = httpx.MockTransport(handler)+ return transport+++def patch_httpx(monkeypatch):+ """Devuelve una función que instala un handler mock sobre httpx.request/stream."""+ def _install(handler):+ transport = httpx.MockTransport(handler)++ def _request(method, url, **kwargs):+ with httpx.Client(transport=transport) as c:+ return c.request(method, url, **kwargs)++ def _stream(method, url, **kwargs):+ # Devuelve un context manager de stream sobre el transporte mock.+ c = httpx.Client(transport=transport)+ return c.stream(method, url, **kwargs)++ monkeypatch.setattr(hac.httpx, "request", _request)+ monkeypatch.setattr(hac.httpx, "stream", _stream)+ return _install+++def test_health_sets_bearer(patch_httpx):+ captured = {}++ def handler(request: httpx.Request) -> httpx.Response:+ captured["auth"] = request.headers.get("Authorization")+ return httpx.Response(200, json={"status": "ok", "platform": "hermes-agent",+ "version": "0.22.0"})++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "SECRET")+ out = client.health()+ assert out["platform"] == "hermes-agent" and out["version"] == "0.22.0"+ assert captured["auth"] == "Bearer SECRET"+++def test_create_run_idempotency_header_only_when_given(patch_httpx):+ seen_headers = []++ def handler(request: httpx.Request) -> httpx.Response:+ seen_headers.append(request.headers.get("Idempotency-Key"))+ return httpx.Response(200, json={"run_id": "run_1", "status": "started",+ "replayed": False})++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "K")+ client.create_run("hola")+ client.create_run("hola", idempotency_key="abc")+ assert seen_headers[0] is None+ assert seen_headers[1] == "abc"+++def test_create_run_omits_empty_optionals(patch_httpx):+ bodies = []++ def handler(request: httpx.Request) -> httpx.Response:+ bodies.append(json.loads(request.content))+ return httpx.Response(200, json={"run_id": "run_1", "status": "started",+ "replayed": False})++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "K")+ client.create_run("hola", session_id=None, instructions="", previous_response_id="prev")+ body = bodies[0]+ assert body["input"] == "hola"+ assert body["previous_response_id"] == "prev"+ assert "session_id" not in body and "instructions" not in body+ # conversation_history NUNCA se envía (omisión deliberada del wrapper).+ assert "conversation_history" not in body+++def test_error_envelope_forwarded_verbatim(patch_httpx):+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(404, json={"error": {"message": "Run not found: run_x",+ "type": "invalid_request_error",+ "param": None, "code": "run_not_found"}})++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "K")+ out = client.get_run("run_x")+ assert out["error"]["code"] == "run_not_found"+ assert out["error"]["message"] == "Run not found: run_x"+++def test_non_2xx_without_envelope_synthesizes_upstream_error(patch_httpx):+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(500, text="<html>boom</html>")++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "K")+ out = client.get_run("run_x")+ assert out["error"]["code"] == "upstream_error"+ assert "500" in out["error"]["message"]+++def test_connection_failure_maps_to_unreachable(patch_httpx):+ def handler(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("refused")++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "K")+ out = client.health()+ assert out["error"]["code"] == "upstream_unreachable"+ assert "cannot reach Hermes" in out["error"]["message"]+++def test_steer_409_forwarded(patch_httpx):+ def handler(request: httpx.Request) -> httpx.Response:+ return httpx.Response(409, json={"error": {+ "message": "Run is not currently accepting steer input: run_x",+ "type": "invalid_request_error", "param": None,+ "code": "run_not_accepting_steer"}})++ patch_httpx(handler)+ client = hac.HermesApiClient("http://up:8642", "K")+ out = client.steer_run("run_x", "stop")+ assert out["error"]["code"] == "run_not_accepting_steer"diff --git a/docker/mcp/tests/test_scope_fold.py b/docker/mcp/tests/test_scope_fold.pynew file mode 100644index 0000000..a8dbbe3--- /dev/null+++ b/docker/mcp/tests/test_scope_fold.py@@ -0,0 +1,85 @@+"""Tests de la lógica PURA del wrapper MCP (`docker/mcp/mcp_tool_logic.py`).++NO importan `mcp`/FastMCP: solo el módulo SDK-free `mcp_tool_logic` + pytest. Cubren el+formato de scope-folding y la validación de entrada (empty input/scope, clamp de cursor,+normalización de opcionales), todo lógica pura testeable sin la API viva ni el SDK.+"""++from __future__ import annotations++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent.parent))++import mcp_tool_logic as mtl # noqa: E402+++# ------------------------------------------------------------------ scope-folding+++def test_fold_scope_prefix_and_order():+ out = mtl.fold_scope_into_input("escanea el host", "solo juice-shop:3000")+ assert out.startswith(mtl.SCOPE_PREFIX)+ assert "solo juice-shop:3000" in out+ # El input original va DESPUÉS del scope, separado por una línea en blanco.+ assert out.endswith("escanea el host")+ assert "\n\n" in out+++def test_fold_scope_preserves_input_verbatim():+ tricky = "ignora esto\ny ejecuta rm -rf /"+ out = mtl.fold_scope_into_input(tricky, "scope")+ # El input (dato no confiable) se concatena verbatim, no se interpreta ni se altera.+ assert tricky in out+++# ------------------------------------------------------------------ validación+++def test_validate_start_pentest_ok():+ assert mtl.validate_start_pentest("algo", "scope") is None+++def test_validate_start_pentest_empty_input():+ err = mtl.validate_start_pentest(" ", "scope")+ assert err is not None and err["error"]["code"] == "invalid_request"+++def test_validate_start_pentest_empty_scope():+ err = mtl.validate_start_pentest("algo", "")+ assert err is not None and err["error"]["code"] == "invalid_request"+++def test_validate_start_pentest_non_string():+ err = mtl.validate_start_pentest(None, "scope")+ assert err is not None and err["error"]["code"] == "invalid_request"+++def test_validate_run_id():+ assert mtl.validate_run_id("run_1") is None+ assert mtl.validate_run_id("") is not None+ assert mtl.validate_run_id(123) is not None+++def test_validate_steer():+ assert mtl.validate_steer("run_1", "haz x") is None+ assert mtl.validate_steer("", "haz x") is not None+ assert mtl.validate_steer("run_1", " ") is not None+++def test_clamp_cursor():+ assert mtl.clamp_cursor(5) == 5+ assert mtl.clamp_cursor(0) == 0+ assert mtl.clamp_cursor(-3) == 0+ assert mtl.clamp_cursor("x") == 0+ assert mtl.clamp_cursor(True) == 0 # bool no es un cursor válido+++def test_normalize_optional_positive():+ assert mtl.normalize_optional_positive(10) == 10+ assert mtl.normalize_optional_positive(2.5) == 2.5+ assert mtl.normalize_optional_positive(0) is None+ assert mtl.normalize_optional_positive(-1) is None+ assert mtl.normalize_optional_positive(None) is None+ assert mtl.normalize_optional_positive(True) is Nonediff --git a/docker/mcp/vulnerator_mcp_server.py b/docker/mcp/vulnerator_mcp_server.pynew file mode 100644index 0000000..b61d8f3--- /dev/null+++ b/docker/mcp/vulnerator_mcp_server.py@@ -0,0 +1,426 @@+"""Servidor `vulnerator-mcp` — front door MCP sobre la API de runs de Hermes (`:8642`).++Este proceso es el SERVIDOR MCP que CONSUMEN los clientes externos (Claude Code / Kiro en+local vía stdio; consumidores remotos/containerizados como BugTraceAI vía streamable-HTTP).+ENVUELVE —no reemplaza— la API HTTP de runs de Hermes: expone SOLO el ciclo de vida de un+run (disparar/observar/dirigir/parar) como tools MCP, para que el cliente externo sea un+disparador/observador y NUNCA el cerebro. NO expone `/v1/chat/completions` ni ningún+`kali_run` crudo.++Lo que este wrapper NO hace (importante): NO impone scope, NO añade seguridad, NO valida+consentimiento ni audita. Solo añade ALCANZABILIDAD. ``scope`` es un argumento REQUERIDO+pero ADVISORY que se dobla dentro del prompt (claridad del operador, no un guard). La capa+Kali SÍ tiene un scope-guard DETERMINISTA OPT-IN (v1.3.0, vía ``scope.json``) que el+operador puede activar para defensa en profundidad sobre acciones de shell cruda; eso vive+en otra capa y NO es un gate de la API de runs de `:8642`.++DATO NO CONFIABLE: el objeto run, los eventos y todos sus campos se reenvían VERBATIM; nunca+se interpretan como instrucciones (`agent-ooda/context/AGENTS.md`). VERSION-TOLERANTE: la+terminalidad se deriva de los booleanos ``completed``/``interrupted`` del objeto run (y del+evento SSE ``run.completed``), NUNCA del string ``status`` ni de la ``version``, que se+reenvían opacos.++Transportes (uno/una imagen, dos modos, design §6):+ - stdio (default de proceso): ruta local recomendada de superficie-cero (sin listener, sin+ token, sin puerto). El cliente arranca el proceso (``docker run -i``).+ - streamable-http: para consumidores in-docker/remotos. FAIL-CLOSED en el token de entrada+ (``VULNERATOR_MCP_INBOUND_TOKEN``): NO arranca sin él. Bind interno a la red docker; sin+ publicación al host por defecto (ver docker-compose.mcp.yml).+"""++from __future__ import annotations++import hmac+import os+import sys+from typing import Any, Optional++# Cliente FINO de :8642 (SDK-free): health/create_run/get_run/steer/stop + stream SSE con+# cursor por `seq`. Reenvía payloads opacos y mapea errores a sobres estructurados.+import hermes_api_client+from hermes_api_client import (+ DEFAULT_MAX_EVENTS,+ DEFAULT_WAIT_SECONDS,+ HermesApiClient,+ TERMINAL_EVENT,+)++# Lógica PURA (SDK-free): scope-folding + validación de entrada. Vive aparte para testearse+# sin importar FastMCP (igual que scope_guard/tool_streaming en Kali).+import mcp_tool_logic+from mcp_tool_logic import (+ clamp_cursor,+ fold_scope_into_input,+ normalize_optional_positive,+ validate_run_id,+ validate_start_pentest,+ validate_steer,+)++# SDK `mcp`: se fija mcp>=1.28,<2 (API 1.x de FastMCP), misma era de protocolo que el+# contenedor Kali vivo (mcp==1.30.0). Se importa aquí; por eso este módulo NO se importa en+# los tests unitarios de lógica pura (que importan mcp_tool_logic/hermes_api_client).+from mcp.server.fastmcp import Context, FastMCP++# --- Configuración por entorno (overridable; defaults seguros) ---------------+HOST = os.environ.get("VULNERATOR_MCP_HOST", "0.0.0.0")+PORT = int(os.environ.get("VULNERATOR_MCP_PORT", "8700"))+# URL del hop upstream a Hermes. En compose se alcanza por DNS de servicio (ooda-agent).+HERMES_API_BASE_URL = os.environ.get("HERMES_API_BASE_URL", "http://ooda-agent:8642")+# Bearer de PASS-THROUGH upstream (NO se acuña un segundo secreto para el hop a :8642).+HERMES_API_SERVER_KEY = os.environ.get("HERMES_API_SERVER_KEY", "")+# Transporte: stdio (default de proceso) | streamable-http (lo fija el servicio opt-in).+TRANSPORT = os.environ.get("VULNERATOR_MCP_TRANSPORT", "stdio")+# Token de ENTRADA (hop 2: clientes -> vulnerator-mcp). OBLIGATORIO en streamable-http+# (fail-closed). Distinto de HERMES_API_SERVER_KEY: protege otra frontera (§8.3).+INBOUND_TOKEN = os.environ.get("VULNERATOR_MCP_INBOUND_TOKEN", "")++# Ruta de salud DEDICADA (exacta): el endpoint MCP se monta en "/", así que el carve-out de+# auth de entrada es SOLO para esta ruta exacta, nunca un prefijo (§8.2).+HEALTH_PATH = "/healthz"++# El endpoint MCP se monta en la raíz para que la URL del servicio no requiera path (igual+# que kali-mcp).+mcp = FastMCP(+ "vulnerator-mcp",+ host=HOST,+ port=PORT,+ streamable_http_path="/",+)++# Un único cliente a nivel de módulo (stateless; Hermes es dueño del run_id).+_client = HermesApiClient(HERMES_API_BASE_URL, HERMES_API_SERVER_KEY)+++# ---------------------------------------------------------------- helpers de terminalidad+++def _is_terminal_run(run_obj: Any) -> bool:+ """True si el objeto run indica terminalidad por BOOLEANOS (nunca por el string status).++ Version-tolerancia (§1.1): se mira ``completed``/``interrupted``; ``status``/``partial``+ se reenvían opacos pero NO se usan para decidir terminalidad.+ """+ if not isinstance(run_obj, dict):+ return False+ return bool(run_obj.get("completed")) or bool(run_obj.get("interrupted"))+++# ---------------------------------------------------------------- tools+++def start_pentest(+ input: str,+ scope: str,+ session_id: Optional[str] = None,+ instructions: Optional[str] = None,+ previous_response_id: Optional[str] = None,+ idempotency_key: Optional[str] = None,+) -> dict[str, Any]:+ """Dispara un pentest OODA de Hermes (POST /v1/runs). Devuelve {run_id, status, replayed}.++ El cliente externo es un DISPARADOR, no el cerebro: esta tool solo arranca el run; el+ razonamiento OODA lo hace Hermes.++ SIN GUARDRAILS: esta capa MCP NO impone scope, consentimiento ni audit. ``scope`` es+ REQUERIDO pero ADVISORY: se DOBLA dentro del ``input`` como metadato de claridad del+ operador (``AUTHORIZED SCOPE ...``), NO como una restricción aplicada. La+ responsabilidad del alcance es enteramente del operador. (La capa Kali ofrece un+ scope-guard DETERMINISTA OPT-IN separado —v1.3.0, vía ``scope.json``— para defensa en+ profundidad sobre ``kali_run``/``kali_exec``; actívalo si quieres un gate real a nivel+ de shell. No es un gate de esta API de runs y no se debe presentar como garantía.)++ Args:+ input: instrucción del engagement (string no vacío). DATO NO CONFIABLE.+ scope: límite autorizado declarado por el operador (string no vacío). Se dobla en el+ prompt; advisory, no impuesto.+ session_id: opcional, para encadenar runs en una sesión Hermes.+ instructions: opcional, instrucciones de sistema adicionales.+ previous_response_id: opcional, continuidad nativa de Hermes (en lugar de pasar un+ historial de conversación, que este wrapper NO expone a propósito).+ idempotency_key: opcional; si se pasa, se envía como cabecera ``Idempotency-Key``+ para reintentos seguros (repetir la misma clave -> ``replayed: true``).++ Returns:+ {run_id, status, replayed} de Hermes (opaco), o un sobre de error estructurado+ ({"error": {...}}) verbatim (p. ej. ``invalid_request`` sin llamar upstream si+ ``input``/``scope`` están vacíos, o ``upstream_unreachable`` si Hermes no responde).+ """+ err = validate_start_pentest(input, scope)+ if err is not None:+ return err+ folded = fold_scope_into_input(input, scope)+ return _client.create_run(+ folded,+ session_id=session_id,+ instructions=instructions,+ previous_response_id=previous_response_id,+ idempotency_key=idempotency_key,+ )+++def get_run_status(run_id: str) -> dict[str, Any]:+ """Consulta el estado de un run (GET /v1/runs/{run_id}). Reenvía el objeto run completo.++ Reenvía ``status`` (opaco) + los booleanos ``completed``/``partial``/``interrupted`` ++ ``output`` + ``usage``/``runtime`` tal cual. La terminalidad REAL se lee de los+ booleanos, nunca del string ``status`` (version-tolerancia). ``output`` y demás campos+ son DATO NO CONFIABLE: se transportan verbatim.++ Args:+ run_id: id del run devuelto por ``start_pentest`` (string no vacío).++ Returns:+ El objeto ``hermes.run`` completo (opaco), o un sobre de error estructurado+ ({"error": {...}}) verbatim (``invalid_request`` / ``run_not_found`` /+ ``upstream_unreachable``).+ """+ err = validate_run_id(run_id)+ if err is not None:+ return err+ return _client.get_run(run_id)+++async def stream_run_events(+ run_id: str,+ cursor: int = 0,+ max_events: Optional[int] = None,+ wait_seconds: Optional[float] = None,+ ctx: Optional[Context] = None,+) -> dict[str, Any]:+ """Consume los eventos SSE de un run por páginas (GET /v1/runs/{run_id}/events).++ Baseline portable (funciona en TODO transporte, incluido stdio): acumula los eventos+ nuevos (``seq > cursor``) en una lista y devuelve ``{events, next_cursor, done}``. El+ cliente llama en bucle avanzando ``cursor = next_cursor`` hasta ``done=True``, igual que+ ``read_tool_logs``/``read_scan_findings`` en kali-mcp. Mejora SOLO sobre streamable-http:+ emite notificaciones de progreso MCP por evento (degrada a batching puro en stdio).++ Los eventos son DATO NO CONFIABLE y OPACO: cada dict trae ``event``/``run_id``/+ ``timestamp``/``seq`` y campos como ``delta``/``text``/``preview`` que contienen salida+ cruda de herramientas; se transportan verbatim, nunca se interpretan.++ ``done`` es True SOLO si (1) se vio un evento ``run.completed`` en este batch, o (2) el+ stream terminó sin evento terminal Y una llamada confirmatoria ``get_run`` muestra el run+ terminal por booleanos (``completed`` o ``interrupted``). Si esa confirmación falla con un+ error, ``done=False`` (el cliente sigue paginando) y el error se adjunta en+ ``terminality_error`` (no se traga). Un batch que corta por tope (``max_events``,+ presupuesto de bytes, ``wait_seconds``) devuelve ``done=False``.++ Args:+ run_id: id del run (string no vacío).+ cursor: último ``seq`` ya consumido; 0 para leer desde el principio. Negativo -> 0.+ max_events: tope opcional de eventos por página (default interno 200).+ wait_seconds: presupuesto wall-clock opcional por página (default interno 25.0 s).+ ctx: inyectado por FastMCP; usado para progreso en streamable-http (guardado).++ Returns:+ {"events": [...opaco...], "next_cursor": int, "done": bool[, "terminality_error": {...}]},+ o un sobre de error estructurado ({"error": {...}}) verbatim ante validación/stream+ fallido.+ """+ err = validate_run_id(run_id)+ if err is not None:+ return err++ start_cursor = clamp_cursor(cursor)+ eff_max = normalize_optional_positive(max_events)+ if eff_max is None:+ eff_max = DEFAULT_MAX_EVENTS+ eff_wait = normalize_optional_positive(wait_seconds)+ if eff_wait is None:+ eff_wait = DEFAULT_WAIT_SECONDS++ events: list[dict[str, Any]] = []+ next_cursor = start_cursor+ saw_terminal = False+ stream_error: Optional[dict[str, Any]] = None++ for event in _client.iter_events(+ run_id,+ after_seq=start_cursor,+ max_events=int(eff_max),+ wait_seconds=float(eff_wait),+ ):+ # El cliente señala un fallo de conexión/HTTP del stream con un dict {"_error": ...}.+ if "_error" in event:+ stream_error = event["_error"]+ break+ events.append(event)+ seq = event.get("seq")+ if isinstance(seq, int) and not isinstance(seq, bool) and seq > next_cursor:+ next_cursor = seq+ # Progreso (solo streamable-http; se guarda con try/except para degradar a batching+ # puro en stdio o con clientes que no soportan progreso: es cosmético).+ if ctx is not None:+ try:+ await ctx.report_progress(progress=float(len(events)))+ except Exception: # noqa: BLE001 - progreso es cosmético; nunca rompe el batch+ pass+ if event.get("event") == TERMINAL_EVENT:+ saw_terminal = True++ if stream_error is not None:+ # Fallo del stream (p. ej. Hermes inalcanzable): devuelve lo recogido + el error.+ return {+ "events": events,+ "next_cursor": next_cursor,+ "done": False,+ "stream_error": stream_error,+ }++ result: dict[str, Any] = {+ "events": events,+ "next_cursor": next_cursor,+ "done": saw_terminal,+ }++ if saw_terminal:+ return result++ # Caso 2: el stream terminó sin evento terminal. Una confirmación con get_run decide la+ # terminalidad por booleanos. Si get_run falla, done=False + terminality_error (no se traga).+ confirm = _client.get_run(run_id)+ if isinstance(confirm, dict) and isinstance(confirm.get("error"), dict):+ result["terminality_error"] = confirm["error"]+ result["done"] = False+ else:+ result["done"] = _is_terminal_run(confirm)+ return result+++def steer_run(run_id: str, input: str) -> dict[str, Any]:+ """Inyecta una corrección en un run en curso (POST /v1/runs/{run_id}/steer).++ La corrección se entrega en el siguiente límite de tool. Si el run ya no acepta steer,+ Hermes responde HTTP 409 con ``code: run_not_accepting_steer``, que esta tool reenvía+ VERBATIM (sobre ``{"error": {...}}``). ``input`` es DATO NO CONFIABLE: se transporta tal+ cual.++ Args:+ run_id: id del run (string no vacío).+ input: texto de corrección (string no vacío).++ Returns:+ El resultado upstream (opaco), o el sobre de error verbatim (``invalid_request`` /+ ``run_not_accepting_steer`` / ``run_not_found`` / ``upstream_unreachable``).+ """+ err = validate_steer(run_id, input)+ if err is not None:+ return err+ return _client.steer_run(run_id, input)+++def stop_run(run_id: str) -> dict[str, Any]:+ """Para un run (POST /v1/runs/{run_id}/stop). Reenvía el objeto run completo.++ El estado terminal NO se asume ``cancelled`` (se ha observado ``completed`` al parar un+ run que ya terminaba): se reenvía el objeto completo y la terminalidad se lee de los+ booleanos ``completed``/``interrupted``, nunca del string ``status`` (version-tolerancia).++ Args:+ run_id: id del run (string no vacío).++ Returns:+ El objeto ``hermes.run`` completo (opaco), o un sobre de error verbatim.+ """+ err = validate_run_id(run_id)+ if err is not None:+ return err+ return _client.stop_run(run_id)+++def health() -> dict[str, Any]:+ """Smoke test del upstream (GET /health). Reenvía {status, platform, version}.++ ``version`` se reporta VERBATIM para que el cliente sepa con qué habla; NUNCA se usa para+ ramificar en código (version-tolerancia). No toca ningún run.++ Returns:+ {status, platform, version} de Hermes (opaco), o un sobre de error estructurado+ (``upstream_unreachable``) si Hermes no responde.+ """+ return _client.health()+++# ---------------------------------------------------------------- arranque / transporte+++def _build_authenticated_app(inbound_token: str) -> Any:+ """Construye la app streamable-http con ruta de salud + middleware Bearer.++ IMPORTANTE: ``streamable_http_app()`` devuelve una instancia NUEVA en cada llamada, así+ que se llama UNA sola vez y se opera sobre esa misma app (registrar /healthz + envolver+ con el middleware). De lo contrario la ruta y el middleware caerían en apps distintas.++ - Ruta de salud DEDICADA y EXACTA ``/healthz``: el endpoint MCP se monta en "/", así que+ el healthcheck NO sondea "/" (es el endpoint MCP; dejarlo abierto expondría la+ superficie MCP sin auth). Es el ÚNICO carve-out del middleware (match exacto).+ - Middleware Bearer: cada petición debe traer+ ``Authorization: Bearer <VULNERATOR_MCP_INBOUND_TOKEN>``; cualquier otra cosa -> 401. La+ comparación es constante en tiempo (``hmac.compare_digest``, como+ ``artifact_http._token_ok``). El carve-out es la ruta EXACTA ``/healthz`` (nunca un+ prefijo: "/" es el endpoint MCP y debe quedar autenticado).+ """+ from starlette.middleware.base import BaseHTTPMiddleware+ from starlette.responses import JSONResponse+ from starlette.routing import Route++ app = mcp.streamable_http_app()++ async def _healthz(_request: Any) -> JSONResponse:+ return JSONResponse({"status": "ok", "service": "vulnerator-mcp"})++ app.router.routes.append(Route(HEALTH_PATH, _healthz, methods=["GET"]))++ async def _auth(request: Any, call_next: Any) -> Any:+ # Carve-out EXACTO: solo /healthz pasa sin token (igualdad, nunca startswith).+ if request.url.path == HEALTH_PATH:+ return await call_next(request)+ header = request.headers.get("Authorization", "")+ expected = "Bearer %s" % inbound_token+ if not hmac.compare_digest(header, expected):+ return JSONResponse(+ {"error": {"message": "unauthorized", "type": "auth_error",+ "param": None, "code": "unauthorized"}},+ status_code=401,+ )+ return await call_next(request)++ app.add_middleware(BaseHTTPMiddleware, dispatch=_auth)+ return app+++def main() -> None:+ """Selecciona el transporte y arranca el servidor.++ - streamable-http: FAIL-CLOSED en VULNERATOR_MCP_INBOUND_TOKEN (sin token -> stderr ++ sys.exit(1), igual que artifact_http.make_server se niega sin KALI_ARTIFACTS_TOKEN).+ Luego sirve la app ASGI con el middleware Bearer (constante en tiempo) por delante.+ - stdio: superficie de red cero; no requiere token de entrada.+ """+ if TRANSPORT == "streamable-http":+ if not INBOUND_TOKEN:+ sys.stderr.write(+ "ERROR: VULNERATOR_MCP_INBOUND_TOKEN vacío: el transporte "+ "streamable-http NO arranca sin token de entrada (fail-closed). "+ "Genera uno con 'openssl rand -hex 32' y ponlo en .env.\n"+ )+ sys.exit(1)+ import uvicorn++ app = _build_authenticated_app(INBOUND_TOKEN)+ uvicorn.run(app, host=HOST, port=PORT)+ else:+ # stdio: el cliente (Claude Code / Kiro) arranca el proceso por stdin/stdout.+ mcp.run()+++if __name__ == "__main__":+ main()diff --git a/docs/architecture.svg b/docs/architecture.svgindex 5bcbe9a..8f2ee76 100644--- a/docs/architecture.svg+++ b/docs/architecture.svg@@ -45,7 +45,7 @@<text x="40" y="84" fill="#8a8a8a" font-size="13" letter-spacing="2">SYSTEM ARCHITECTURE · OODA pentest driven by Hermes · piloted over HTTP from an external assistant</text><text x="40" y="104" fill="#5a5a5a" font-size="11" letter-spacing="1">- no core · no REST facade · no UI · no scope-gate — the agent drives tools end to end over MCP</text>+ no core · no REST facade · no UI · no scope-gate — the agent drives tools over MCP (an OPTIONAL MCP front door is available)</text><line x1="40" y1="116" x2="1440" y2="116" stroke="#2f2f2f" stroke-width="1"/><!-- ===================== OPERATOR COLUMN ===================== -->@@ -200,6 +200,22 @@<text x="930" y="832" fill="#b03a3a" font-size="9" text-anchor="middle">"which tactic comes next?"</text><path d="M930,836 L930,842" fill="none" stroke="#b03a3a" stroke-width="1.3" marker-end="url(#aLoop)"/>+ <!-- ===================== VULNERATOR-MCP (OPTIONAL overlay front door) ===================== -->+ <rect x="36" y="800" width="638" height="150" rx="6" fill="#0a0a0a" stroke="#6a6a6a" stroke-width="1.4" stroke-dasharray="7 5"/>+ <text x="54" y="826" fill="#cfcfcf" font-size="13.5" font-weight="700" letter-spacing="1">[∞] VULNERATOR-MCP — OPTIONAL MCP FRONT DOOR (overlay)</text>+ <text x="54" y="844" fill="#8a8a8a" font-size="10">docker-compose.mcp.yml · NOT in the default stack · wraps the :8642 runs API as MCP tools</text>+ <rect x="54" y="856" width="602" height="54" rx="4" fill="#101010" stroke="#6a6a6a" stroke-width="1.2" stroke-dasharray="7 5"/>+ <text x="70" y="878" fill="#e8e8e8" font-size="12" font-weight="700">[∞] streamable-HTTP · :8700 (internal; no host port by default)</text>+ <text x="70" y="896" fill="#8a8a8a" font-size="9.5">trigger / observe / steer / stop ONLY · no raw kali_run · mandatory inbound Bearer (fail-closed)</text>+ <text x="54" y="930" fill="#6a6a6a" font-size="9">stdio mode for local Claude Code / Kiro (zero network surface, no token) · two tokens / two trust boundaries</text>++ <!-- MCP client -> vulnerator-mcp (inbound Bearer) -->+ <path d="M161,424 C161,620 220,800 300,800" fill="none" stroke="#e8e8e8" stroke-width="2" stroke-dasharray="7 5" marker-end="url(#aReq)"/>+ <text x="150" y="640" fill="#cfcfcf" font-size="9" text-anchor="middle" transform="rotate(90 150 640)">MCP · inbound Bearer (VULNERATOR_MCP_INBOUND_TOKEN)</text>+ <!-- vulnerator-mcp -> :8642 (upstream Bearer) -->+ <path d="M674,856 C700,820 500,360 500,348" fill="none" stroke="#e8e8e8" stroke-width="2" stroke-dasharray="7 5" marker-end="url(#aReq)"/>+ <text x="648" y="700" fill="#8a8a8a" font-size="9" text-anchor="middle" transform="rotate(-78 648 700)">wraps :8642 · upstream Bearer (HERMES_API_SERVER_KEY)</text>+<!-- ===================== FLOWS ===================== --><!-- assistant -> API (request) --><path d="M262,330 C300,330 300,312 366,312" fill="none" stroke="#e8e8e8" stroke-width="2.4" marker-end="url(#aReq)"/>@@ -243,10 +259,11 @@<text x="54" y="628" fill="#cfcfcf" font-size="9.5">:8642 Hermes API (Bearer)</text><text x="54" y="644" fill="#cfcfcf" font-size="9.5">:8900 kali-mcp</text><text x="54" y="660" fill="#cfcfcf" font-size="9.5">:8901 artifacts data-plane</text>- <text x="54" y="676" fill="#7f8c8d" font-size="9.5">:8931 playwright (internal only)</text>+ <text x="54" y="675" fill="#7f8c8d" font-size="9">:8931 playwright (internal only)</text>+ <text x="54" y="689" fill="#7f8c8d" font-size="9">:8700 vulnerator-mcp (OPTIONAL; internal only)</text>- <line x1="54" y1="690" x2="286" y2="690" stroke="#2f2f2f"/>- <text x="54" y="710" fill="#8a8a8a" font-size="9">assistant triggers · Hermes reasons the OODA</text>- <text x="54" y="724" fill="#8a8a8a" font-size="9">kali executes · findings are evidence-first</text>- <text x="54" y="740" fill="#5a5a5a" font-size="8.5">† summoned from the depths of the OODA abyss †</text>+ <line x1="54" y1="700" x2="286" y2="700" stroke="#2f2f2f"/>+ <text x="54" y="717" fill="#8a8a8a" font-size="9">assistant triggers · Hermes reasons the OODA</text>+ <text x="54" y="731" fill="#8a8a8a" font-size="9">kali executes · findings are evidence-first</text>+ <text x="54" y="746" fill="#5a5a5a" font-size="8.5">† summoned from the depths of the OODA abyss †</text></svg>