Skip to content

Autonomous OODA-loop pentesting agent. Hermes brain, Kali + Playwright tools over MCP, ATT&CK as the Orient language.

fix(mcp): harden stream_run_events + run_id, fix all 7 review findings

irraz494942c5a24d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b877497..889095c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -38,6 +38,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
(`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.
+ `stream_run_events` paging is hardened: a batch cut short by any cap (`max_events`, the
+ ~256 KiB byte budget, or the `wait_seconds` wall-clock budget) returns `done: false` and the
+ confirming `get_run` runs ONLY on a genuine stream drain, so a client looping until `done`
+ never drops the tail of a multi-page terminal run; the byte budget is checked BEFORE adding
+ an event (never overshoots the transport limit by a whole event); the SSE read is async with
+ a deadline-aware cancellation so a quiet upstream ends the batch at `wait_seconds` instead of
+ stalling on the network timeout; terminality requires the literal boolean `True`; a stream
+ failure preserves the full `{"error": {...}}` envelope; and the untrusted `run_id` is encoded
+ as a single path segment (route-traversal rejected before any upstream call).
## [1.3.0] - 2026-10-16
diff --git a/docker/mcp/hermes_api_client.py b/docker/mcp/hermes_api_client.py
index 6410014..22827a3 100644
--- a/docker/mcp/hermes_api_client.py
+++ b/docker/mcp/hermes_api_client.py
@@ -18,20 +18,26 @@ Disciplina (igual que docker/kali/*):
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).
+ - FRONTERA DE URL: el ``run_id`` es DATO NO CONFIABLE. Se codifica como UN ÚNICO segmento
+ de path (``encode_run_id_segment``), rechazando delimitadores de ruta (``/`` ``\\`` ``?``
+ ``#`` y ``..``) incluso tras decodificar, de modo que un id malicioso no pueda saltar a
+ otra ruta de Hermes (p. ej. ``../runs`` para crear un run sin el scope advisory).
+
+SDK-free a propósito: NO importa `mcp`, de modo que el parser SSE + cursor, la codificación
+del run_id 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`). Dependencias no-stdlib:
+``httpx`` (stream SSE del hop a :8642, cliente ASYNC con deadline) y ``anyio`` (cancelación
+por deadline del stream; ver requirements.txt).
"""
from __future__ import annotations
import json
import sys
-import time
-from typing import Any, Iterable, Iterator, Optional
+from typing import Any, Iterable, Optional
+from urllib.parse import quote, unquote
+import anyio
import httpx
# Tipo del evento terminal del ciclo de vida (único string de wire fijo en control de
@@ -49,6 +55,15 @@ DEFAULT_BYTE_BUDGET = 256 * 1024
# un stream silencioso.
DEFAULT_WAIT_SECONDS = 25.0
+# Razones de parada del batcher SSE (design §4.1). Distinguen un corte por TOPE (cap/
+# deadline -> hay más datos pendientes, el batch NO es terminal) de un DRENADO real del
+# stream (upstream cerró la conexión), que es la ÚNICA condición que habilita la
+# confirmación de terminalidad por `get_run` en el servidor.
+STOP_CAP = "cap" # max_events o presupuesto de bytes agotado
+STOP_DEADLINE = "deadline" # presupuesto wall-clock agotado (stream silencioso)
+STOP_TERMINAL = "terminal" # se vio el evento run.completed
+STOP_DRAINED = "drained" # el iterador de líneas se agotó (upstream cerró el stream)
+
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).
@@ -59,21 +74,64 @@ def _error_envelope(message: str, code: str, type_: str = "upstream_error") -> d
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.
+class RunIdError(ValueError):
+ """El ``run_id`` no es un segmento de path seguro (contiene delimitadores de ruta)."""
- 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``.
+
+# Delimitadores que, tras decodificar, permitirían a un run_id saltar a otra ruta/host de
+# Hermes o inyectar query/fragment. Se rechazan explícitamente (defensa en profundidad
+# sobre el quote por-segmento), incluido ``..`` (segmento de recorrido).
+_FORBIDDEN_IN_RUN_ID = ("/", "\\", "?", "#")
+
+
+def encode_run_id_segment(run_id: str) -> str:
+ """Codifica ``run_id`` como UN ÚNICO segmento de path seguro (fija review Finding `run_id`).
+
+ El ``run_id`` es DATO NO CONFIABLE: interpolarlo crudo en la URL deja que
+ ``steer_run(run_id="../runs?x", ...)`` normalice a ``POST /v1/runs`` (creando un run sin
+ el scope advisory) o que alcance otra ruta de Hermes. Para evitarlo:
+
+ 1. Se DECODIFICA el valor (``unquote``) y se comprueba que NI el crudo NI el decodificado
+ contienen un delimitador de ruta (``/`` ``\\`` ``?`` ``#``) ni ``..`` ni NUL. Así se
+ rechaza también la variante percent-encoded (``%2F`` -> ``/`` tras decodificar).
+ 2. Se ``quote`` con ``safe=""`` para que el resultado sea un único segmento (cualquier
+ carácter especial queda percent-encoded y NO cambia de ruta).
+
+ No valida el formato ``run_`` (Hermes es dueño del espacio de ids; version-tolerancia):
+ solo garantiza que el valor no es sintaxis de URL que cambie de ruta. Lanza
+ ``RunIdError`` si el id no es un segmento seguro.
+ """
+ if not isinstance(run_id, str) or not run_id:
+ raise RunIdError("run_id vacío o no-string")
+ # Se mira tanto el crudo como el decodificado: un cliente podría enviar ya el separador
+ # literal o su forma percent-encoded.
+ decoded = unquote(run_id)
+ for candidate in (run_id, decoded):
+ if "\x00" in candidate:
+ raise RunIdError("run_id contiene NUL")
+ if ".." in candidate:
+ raise RunIdError("run_id contiene '..' (recorrido de ruta)")
+ for bad in _FORBIDDEN_IN_RUN_ID:
+ if bad in candidate:
+ raise RunIdError("run_id contiene delimitador de ruta prohibido: %r" % bad)
+ # safe="": todo lo demás se percent-encodea; el resultado es un único segmento de path.
+ return quote(run_id, safe="")
+
+
+class SseBatcher:
+ """Batcher SSE PURO e INCREMENTAL (sin socket): acumula UNA página de eventos.
+
+ Se le alimentan líneas de wire UNA A UNA con :meth:`feed`; cada ``feed`` devuelve una
+ razón de parada (``STOP_CAP``/``STOP_TERMINAL``) en cuanto la página debe cerrarse, o
+ ``None`` si puede seguir aceptando líneas. Es la pieza de mayor valor de test unitario:
+ se le dan líneas crudas (incluido el comentario ``: open``, ``data:`` multilínea y un
+ evento malformado) y expone ``events``/``next_cursor`` ya filtrados por cursor. NO abre
+ red: ``iter_events`` le pasa las líneas que lee de la red y puede PARAR en cuanto el
+ batcher señala un tope (sin bufferizar el stream entero en memoria).
+
+ El servidor usa la razón de parada para decidir ``done`` (design §4.1): SOLO
+ ``STOP_TERMINAL`` o ``STOP_DRAINED`` (iterador agotado) terminan la paginación;
+ ``STOP_CAP``/``STOP_DEADLINE`` significan "hay más datos, sigue paginando" -> ``done=false``.
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``).
@@ -82,36 +140,44 @@ def parse_sse_events(
(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 ignoran comentarios (``:`` al inicio, p. ej. ``: open``) y la línea ``id:`` (se
+ usa el ``seq`` del JSON, autoritativo). La línea en blanco es frontera de evento.
- 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).
+
+ Presupuesto de bytes (fija review Finding "byte budget overshoots"): el tamaño del evento
+ se mide ANTES de añadirlo. Si al añadirlo la página YA NO VACÍA cruzaría ``byte_budget``,
+ se cierra la página SIN incluirlo (``STOP_CAP``) y queda para la siguiente (no se pierde:
+ su ``seq`` no avanza). Un ÚNICO evento mayor que ``byte_budget`` con la página vacía SÍ se
+ incluye (anti-starvation deliberada) y cierra la página tras él, de modo que un batch
+ devuelva como mucho UN evento por encima del presupuesto, nunca dos. 256 KiB deja margen
+ bajo el 1 MiB del transporte incluso para ese único evento + overhead del sobre MCP.
"""
- 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:
+
+ def __init__(
+ self,
+ *,
+ after_seq: int = 0,
+ max_events: Optional[int] = None,
+ byte_budget: int = DEFAULT_BYTE_BUDGET,
+ ) -> None:
+ self._after_seq = after_seq
+ self._max = max_events if (max_events is not None and max_events > 0) else None
+ self._byte_budget = byte_budget
+ self.events: list[dict[str, Any]] = []
+ self.next_cursor = after_seq
+ self._bytes_seen = 0
+ self._data_parts: list[str] = []
+
+ def _parse(self) -> Optional[dict[str, Any]]:
+ """Procesa el evento acumulado en el buffer. Devuelve el dict a emitir o None."""
+ if not self._data_parts:
return None
- raw = "\n".join(data_parts)
+ raw = "\n".join(self._data_parts)
+ self._data_parts = []
try:
event = json.loads(raw)
except (ValueError, TypeError):
@@ -121,55 +187,88 @@ def parse_sse_events(
seq = event.get("seq")
if not isinstance(seq, int) or isinstance(seq, bool):
return None # sin cursor usable -> se omite
- if seq <= after_seq:
+ if seq <= self._after_seq:
return None # ya entregado (dedup entre páginas)
return event
- for raw_line in lines:
- line = raw_line.rstrip("\n").rstrip("\r")
+ def _emit(self, event: dict[str, Any]) -> Optional[str]:
+ """Intenta añadir ``event`` a la página. Devuelve una razón de parada o None.
+ Mide el tamaño ANTES de añadir (fija el overshoot): si la página no vacía cruzaría el
+ presupuesto, NO lo añade y devuelve ``STOP_CAP`` (el evento queda para el próximo
+ batch). Un único evento oversized con la página vacía SÍ se añade (anti-starvation),
+ y entonces se cierra la página tras él.
+ """
+ size = len(json.dumps(event))
+ if self.events and self._bytes_seen + size > self._byte_budget:
+ return STOP_CAP # cerrar ANTES de cruzar el tope; el evento no se incluye
+ self.events.append(event)
+ self._bytes_seen += size
+ seq = event["seq"]
+ if seq > self.next_cursor:
+ self.next_cursor = seq
+ if event.get("event") == TERMINAL_EVENT:
+ return STOP_TERMINAL
+ if self._max is not None and len(self.events) >= self._max:
+ return STOP_CAP
+ if self._bytes_seen >= self._byte_budget:
+ # Un único evento ya por encima del presupuesto (o justo en el límite): se incluyó
+ # por anti-starvation, pero se cierra la página aquí para no acumular un segundo.
+ return STOP_CAP
+ return None
+
+ def feed(self, raw_line: str) -> Optional[str]:
+ """Alimenta UNA línea de wire. Devuelve una razón de parada o None (sigue aceptando)."""
+ 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
-
+ event = self._parse()
+ if event is not None:
+ return self._emit(event)
+ return None
if line.startswith(":"):
- continue # comentario (p. ej. ": open")
+ return None # comentario (p. ej. ": open")
if line.startswith("id:"):
- continue # id de wire: ignorado, se usa el seq del JSON
+ return None # 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
+ self._data_parts.append(payload)
+ return None
# Cualquier otra línea (p. ej. "event:") se ignora: el tipo vive en el JSON.
+ return None
- # Fin del iterador o corte por tiempo: procesa el último evento sin frontera en blanco.
- event = _flush()
- if event is not None:
- yield event
+ def flush(self) -> Optional[str]:
+ """Procesa el último evento SIN frontera en blanco (stream drenado por upstream)."""
+ event = self._parse()
+ if event is not None:
+ return self._emit(event)
+ return None
+
+
+def batch_sse_events(
+ lines: Iterable[str],
+ *,
+ after_seq: int = 0,
+ max_events: Optional[int] = None,
+ byte_budget: int = DEFAULT_BYTE_BUDGET,
+) -> tuple[list[dict[str, Any]], int, str]:
+ """Batchea un ITERABLE de líneas en UNA página (helper puro para tests + ruta de error).
+
+ Envuelve :class:`SseBatcher`: alimenta las líneas hasta que el batcher señala parada
+ (``STOP_CAP``/``STOP_TERMINAL``) o se agota el iterable (``STOP_DRAINED``). Devuelve
+ ``(events, next_cursor, stop_reason)``. El corte por DEADLINE (stream silencioso) lo
+ gestiona ``iter_events`` con cancelación async, no este helper síncrono.
+ """
+ batcher = SseBatcher(after_seq=after_seq, max_events=max_events, byte_budget=byte_budget)
+ for raw_line in lines:
+ reason = batcher.feed(raw_line)
+ if reason is not None:
+ return batcher.events, batcher.next_cursor, reason
+ reason = batcher.flush()
+ if reason is not None:
+ return batcher.events, batcher.next_cursor, reason
+ return batcher.events, batcher.next_cursor, STOP_DRAINED
class HermesApiClient:
@@ -196,6 +295,22 @@ class HermesApiClient:
headers["Content-Type"] = "application/json"
return headers
+ def _run_path(self, run_id: str, suffix: str = "") -> dict[str, Any] | str:
+ """Construye ``/v1/runs/<seg>[/suffix]`` con el run_id como UN segmento seguro.
+
+ Devuelve el path (str) o, si el run_id no es un segmento seguro, un sobre de error
+ ``invalid_request`` (fail-closed, SIN llamada upstream). El llamador comprueba el tipo.
+ """
+ try:
+ seg = encode_run_id_segment(run_id)
+ except RunIdError as exc:
+ self._warn("run_id rechazado como segmento de path: %s" % exc)
+ return _error_envelope(
+ "'run_id' no es un identificador válido", code="invalid_request",
+ type_="invalid_request_error",
+ )
+ return "/v1/runs/%s%s" % (seg, suffix)
+
def _handle_response(self, resp: httpx.Response) -> dict[str, Any]:
"""Mapea una respuesta HTTP a dict (payload opaco o sobre de error).
@@ -301,47 +416,111 @@ class HermesApiClient:
"""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``.
+ NUNCA del string ``status``. El ``run_id`` se codifica como un segmento seguro.
"""
- return self._request("GET", "/v1/runs/%s" % run_id)
+ path = self._run_path(run_id)
+ if isinstance(path, dict):
+ return path
+ return self._request("GET", path)
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})
+ path = self._run_path(run_id, "/steer")
+ if isinstance(path, dict):
+ return path
+ return self._request("POST", path, 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)
+ path = self._run_path(run_id, "/stop")
+ if isinstance(path, dict):
+ return path
+ return self._request("POST", path)
- def iter_events(
+ async 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.
+ ) -> tuple[list[dict[str, Any]], int, Optional[dict[str, Any]], str]:
+ """GET /v1/runs/{run_id}/events (SSE). Devuelve UNA página batcheada (ASYNC).
+
+ Es ASYNC y con deadline propio (fija review Finding "quiet SSE wait"): abre
+ ``httpx.AsyncClient.stream`` y lee líneas de forma asíncrona bajo un
+ ``anyio.move_on_after(wait_seconds)``. Así un stream SILENCIOSO tras ``: open`` se
+ corta en el presupuesto wall-clock (frontera de batch NORMAL, ``done=false``), SIN
+ esperar al read-timeout de httpx y SIN bloquear el event loop de streamable-HTTP.
+
+ Un corte por deadline es DISTINTO de un fallo de conexión/HTTP:
+ - deadline/cap -> ``stop_reason`` ``STOP_DEADLINE``/``STOP_CAP`` y ``error=None``
+ (el cliente sigue paginando).
+ - non-2xx o excepción de conexión -> ``error`` es el sobre ``{"error": {...}}``
+ COMPLETO (fija review Finding "streaming errors lose the envelope"): se preserva
+ la MISMA forma que request/response, no un ``_error`` sintético.
+
+ Returns:
+ ``(events, next_cursor, error, stop_reason)``. Si ``error`` no es None, es el
+ sobre de error completo y ``stop_reason`` es ``"error"``.
"""
- url = "%s/v1/runs/%s/events" % (self._base_url, run_id)
+ path = self._run_path(run_id, "/events")
+ if isinstance(path, dict):
+ return [], after_seq, path, "error" # run_id inválido: sobre invalid_request
+
+ url = "%s%s" % (self._base_url, path)
headers = self._headers()
+
+ if wait_seconds is not None and wait_seconds > 0:
+ effective_wait = wait_seconds
+ else:
+ effective_wait = DEFAULT_WAIT_SECONDS
+
+ batcher = SseBatcher(after_seq=after_seq, max_events=max_events)
+ cap_reason: Optional[str] = None # STOP_CAP/STOP_TERMINAL si un tope cerró la página
+ hit_deadline = False
+
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,
- )
+ # Read-timeout de httpx = None: el corte REAL por tiempo lo hace
+ # anyio.move_on_after (deadline wall-clock del batch), no el read-timeout, para no
+ # confundir un stream LENTO/silencioso con un fallo de conexión. El connect timeout
+ # sí es corto (fail-fast si :8642 no está).
+ stream_timeout = httpx.Timeout(
+ connect=min(self._timeout, 10.0),
+ read=None, write=self._timeout, pool=self._timeout,
+ )
+ async with httpx.AsyncClient(timeout=stream_timeout) as client:
+ async with client.stream("GET", url, headers=headers) as resp:
+ if not resp.is_success:
+ await resp.aread()
+ error = self._handle_response(resp)
+ return [], after_seq, error, "error"
+ # Lectura asíncrona de líneas bajo deadline wall-clock. Al expirar, se
+ # cancela el aiter (frontera de batch NORMAL, no error). Se para también
+ # en cuanto el batcher señala un tope, SIN bufferizar el resto del stream.
+ with anyio.move_on_after(effective_wait) as scope:
+ async for line in resp.aiter_lines():
+ cap_reason = batcher.feed(line)
+ if cap_reason is not None:
+ break
+ if scope.cancelled_caught:
+ hit_deadline = True
except httpx.HTTPError as exc:
- yield {"_error": self._unreachable(exc)["error"]}
+ # Fallo de conexión/HTTP: sobre {"error": {...}} COMPLETO (misma forma que el
+ # resto del cliente), nunca un dict sintético {"_error": ...}. Los eventos
+ # parciales ya acumulados en el batcher se devuelven igualmente (no se pierden).
+ error = self._unreachable(exc)
+ return batcher.events, batcher.next_cursor, error, "error"
+
+ if cap_reason is not None:
+ # Un tope (max_events/byte_budget) o el evento terminal cerró la página.
+ return batcher.events, batcher.next_cursor, None, cap_reason
+ if hit_deadline:
+ # El deadline wall-clock cortó un stream aún abierto: frontera de batch NORMAL.
+ # NO es STOP_DRAINED (podría haber más eventos tras el silencio), así que el
+ # servidor NO debe confirmar terminalidad a partir de este batch.
+ return batcher.events, batcher.next_cursor, None, STOP_DEADLINE
+ # El aiter se agotó: upstream cerró el stream. Procesa el último evento sin frontera.
+ drain_reason = batcher.flush()
+ stop_reason = drain_reason if drain_reason is not None else STOP_DRAINED
+ return batcher.events, batcher.next_cursor, None, stop_reason
diff --git a/docker/mcp/mcp_tool_logic.py b/docker/mcp/mcp_tool_logic.py
index 37d788a..b2a803f 100644
--- a/docker/mcp/mcp_tool_logic.py
+++ b/docker/mcp/mcp_tool_logic.py
@@ -1,4 +1,4 @@
-"""Lógica PURA del wrapper MCP (sin `mcp`/`httpx`): scope-folding + validación de entrada.
+"""Lógica PURA del wrapper MCP (sin `mcp`/`httpx`): scope-folding, validación y `done`.
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),
@@ -90,3 +90,65 @@ def normalize_optional_positive(value: Any) -> Optional[Any]:
if isinstance(value, (int, float)) and value > 0:
return value
return None
+
+
+# ------------------------------------------------------------------ terminalidad / done
+
+
+def is_terminal_run(run_obj: Any) -> bool:
+ """True SOLO si el objeto run indica terminalidad por BOOLEANOS LITERALES ``True``.
+
+ Version-tolerancia (§1.1) + dato NO CONFIABLE (fija review Finding "truthy terminal"):
+ se mira ``completed``/``interrupted`` y se exige que sean EXACTAMENTE ``True`` (``is
+ True``), nunca ``bool(...)``. Un payload malformado o cambiado (``{"completed": "false"}``
+ o ``1`` o ``"true"``) NO cuenta como terminal: valores ausentes, numéricos, string o
+ contenedor se tratan como NO terminales (seguir paginando), manteniendo el resto de
+ campos opacos. El string ``status`` NUNCA se usa para decidir terminalidad.
+ """
+ if not isinstance(run_obj, dict):
+ return False
+ return run_obj.get("completed") is True or run_obj.get("interrupted") is True
+
+
+def decide_stream_done(
+ *,
+ saw_terminal_event: bool,
+ stream_drained: bool,
+ confirm_run: Any,
+ confirm_is_error: bool,
+) -> tuple[bool, bool]:
+ """Decide ``done`` de un batch de ``stream_run_events`` (lógica PURA; design §4.1).
+
+ Separada del servidor (que importa ``mcp``) para poder TESTEAR el contrato de ``done``
+ sin el SDK (fija review Finding "done untested"). Reglas (design §4.1):
+
+ - Si se vio un evento ``run.completed`` en el batch -> ``done=True`` (caso 1).
+ - Si el stream se DRENÓ sin evento terminal, se hace UNA confirmación ``get_run``:
+ * si falló (sobre de error) -> ``done=False`` y se adjunta ``terminality_error``
+ (el cliente sigue paginando; el error NO se traga). (caso 2 / revisión-3 F5)
+ * si no, ``done = is_terminal_run(confirm_run)``.
+ - Si el batch cerró por un TOPE (cap/deadline) y NO drenó -> ``done=False`` SIN confirmar
+ (fija el blocking Finding de opus: nunca declarar done con eventos pendientes tras el
+ cursor). La confirmación ``get_run`` solo corre en un drenado real del stream.
+
+ Args:
+ saw_terminal_event: True si el batch contuvo un ``run.completed``.
+ stream_drained: True solo si el stream se cerró por upstream (STOP_DRAINED), NO por
+ un tope (STOP_CAP/STOP_DEADLINE).
+ confirm_run: resultado de ``get_run`` (solo relevante en drenado sin evento terminal).
+ confirm_is_error: True si ``confirm_run`` es un sobre de error.
+
+ Returns:
+ ``(done, needs_terminality_error)``: ``done`` es el booleano final; si
+ ``needs_terminality_error`` es True el servidor debe adjuntar ``confirm_run["error"]``
+ bajo ``terminality_error``.
+ """
+ if saw_terminal_event:
+ return True, False
+ if not stream_drained:
+ # Tope (cap/deadline): hay datos pendientes -> no terminal, no se confirma.
+ return False, False
+ # Drenado real sin evento terminal: una confirmación get_run decide.
+ if confirm_is_error:
+ return False, True # error de confirmación: no terminal + adjuntar terminality_error
+ return is_terminal_run(confirm_run), False
diff --git a/docker/mcp/tests/test_hermes_api_client.py b/docker/mcp/tests/test_hermes_api_client.py
index 7a7c5fd..285aae5 100644
--- a/docker/mcp/tests/test_hermes_api_client.py
+++ b/docker/mcp/tests/test_hermes_api_client.py
@@ -1,12 +1,19 @@
-"""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.
+"""Tests del cliente :8642 y el batcher SSE (`docker/mcp/hermes_api_client.py`).
+
+NO importan `mcp`/FastMCP: solo el módulo SDK-free `hermes_api_client` + httpx + anyio +
+pytest (mismo patrón que `docker/kali/tests/test_scope_guard.py`). Cubren:
+ - El batcher SSE puro (`batch_sse_events`): 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 SIN overshoot) + razón de parada
+ (STOP_CAP/STOP_TERMINAL/STOP_DRAINED).
+ - `encode_run_id_segment`: el run_id (dato no confiable) se codifica como UN segmento y se
+ rechaza cualquier intento de recorrido/salto de ruta (fija review Finding "run_id route
+ escape"), incluida la variante percent-encoded; y que un run_id de recorrido NO toca red.
+ - `iter_events` (async, httpx.AsyncClient + MockTransport): stream/dedup, corte en el
+ evento terminal, y preservación del sobre {"error": {...}} COMPLETO en non-2xx/invalid.
- 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).
+ da, el mapeo de cada forma de error (sobre JSON, non-2xx sin sobre, fallo de conexión), y
+ que la ruta construida es el target exacto esperado.
"""
from __future__ import annotations
@@ -15,6 +22,7 @@ import json
import sys
from pathlib import Path
+import anyio
import httpx
import pytest
@@ -41,8 +49,10 @@ def _lines(raw: str):
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)))
+ events, next_cursor, reason = hac.batch_sse_events(_lines(raw))
assert [e["seq"] for e in events] == [1, 2, 3]
+ assert next_cursor == 3
+ assert reason == hac.STOP_DRAINED # el iterador se agotó sin evento terminal
# Opaco: el dict de evento se entrega sin tocar.
assert events[0]["event"] == "message.delta"
assert events[0]["run_id"] == "run_x"
@@ -56,14 +66,15 @@ def test_parser_multiline_data():
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)))
+ events, _, _ = hac.batch_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))
+ events, next_cursor, _ = hac.batch_sse_events(_lines(raw), after_seq=2)
assert [e["seq"] for e in events] == [3]
+ assert next_cursor == 3
def test_parser_skips_malformed_and_missing_seq():
@@ -71,41 +82,61 @@ def test_parser_skips_malformed_and_missing_seq():
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)))
+ events, _, _ = hac.batch_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)))
+ events, next_cursor, reason = hac.batch_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
+ assert reason == hac.STOP_TERMINAL
+ assert next_cursor == 2
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))
+ events, next_cursor, reason = hac.batch_sse_events(_lines(raw), max_events=3)
assert [e["seq"] for e in events] == [1, 2, 3]
+ assert reason == hac.STOP_CAP # cap -> hay más datos, el servidor NO declara done
+ assert next_cursor == 3
-def test_parser_byte_budget_cap():
- # Un presupuesto de bytes diminuto corta tras el primer evento.
+def test_parser_byte_budget_cap_single_event():
+ # Un presupuesto de bytes diminuto deja pasar UN único evento (anti-starvation) y corta.
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))
+ events, _, reason = hac.batch_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
+ assert reason == hac.STOP_CAP
+
+
+def test_parser_byte_budget_closes_page_before_overshoot():
+ # Fija review Finding "byte budget overshoots by one event": con DOS eventos grandes y un
+ # presupuesto que cabe el primero pero no la suma, el segundo NO se incluye (se mide ANTES
+ # de añadir). El batch devuelve solo el primero y el segundo queda para la próxima página.
+ big = "y" * 200
+ one = _sse_message(1, text=big)
+ two = _sse_message(2, text=big)
+ size_one = len(json.dumps(json.loads(one.split("data: ", 1)[1].split("\n\n")[0])))
+ # Presupuesto: cabe el primero, pero el primero+segundo lo cruza.
+ budget = size_one + 10
+ events, next_cursor, reason = hac.batch_sse_events(
+ _lines(one + two), byte_budget=budget
+ )
+ assert [e["seq"] for e in events] == [1] # el segundo NO se incluyó (sin overshoot)
+ assert next_cursor == 1 # el seq del segundo NO avanza: se re-leerá en la próxima página
+ assert reason == hac.STOP_CAP
+
+
+def test_parser_byte_budget_two_small_events_both_fit():
+ # Control: si ambos caben, los dos salen (no se corta de más).
+ one = _sse_message(1, text="a")
+ two = _sse_message(2, text="b")
+ events, _, reason = hac.batch_sse_events(_lines(one + two), byte_budget=10_000)
+ assert [e["seq"] for e in events] == [1, 2]
+ assert reason == hac.STOP_DRAINED
# ------------------------------------------------------------------ HermesApiClient
@@ -237,3 +268,151 @@ def test_steer_409_forwarded(patch_httpx):
client = hac.HermesApiClient("http://up:8642", "K")
out = client.steer_run("run_x", "stop")
assert out["error"]["code"] == "run_not_accepting_steer"
+
+
+# ------------------------------------------------------------------ run_id como segmento
+
+
+def test_encode_run_id_segment_normal():
+ # Un id normal pasa tal cual (es ya un segmento seguro).
+ assert hac.encode_run_id_segment("run_36998a15") == "run_36998a15"
+
+
+def test_encode_run_id_segment_percent_encodes_specials():
+ # Un espacio u otros caracteres se percent-encodean (siguen siendo UN segmento).
+ assert hac.encode_run_id_segment("run with space") == "run%20with%20space"
+
+
+ "../runs?ignored", # el PoC del review: saltaría a POST /v1/runs
+ "../runs",
+ "a/b", # slash crudo
+ "a\\b", # backslash
+ "run?x=1", # query
+ "run#frag", # fragment
+ "%2e%2e%2fruns", # ".." + "/" percent-encoded -> se decodifica y se rechaza
+ "%2fetc%2fpasswd", # "/" percent-encoded
+ "run\x00id", # NUL
+])
+def test_encode_run_id_segment_rejects_route_escape(evil):
+ with pytest.raises(hac.RunIdError):
+ hac.encode_run_id_segment(evil)
+
+
+def test_run_id_route_escape_is_blocked_before_network(patch_httpx):
+ # Fija el blocking Finding "run_id route escape": un run_id de recorrido NO debe tocar la
+ # red; debe devolver invalid_request SIN hacer la petición (no crear un run via steer).
+ called = {"n": 0}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ called["n"] += 1
+ return httpx.Response(200, json={"run_id": "run_leak", "status": "started"})
+
+ patch_httpx(handler)
+ client = hac.HermesApiClient("http://up:8642", "K")
+ out = client.steer_run("../runs?ignored", "please create a run")
+ assert out["error"]["code"] == "invalid_request"
+ assert called["n"] == 0 # NUNCA se llamó a upstream
+
+
+def test_run_id_safe_hits_exact_target(patch_httpx):
+ # "Test the final request target": un run_id normal construye la ruta esperada.
+ targets = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ targets.append(str(request.url))
+ return httpx.Response(200, json={"ok": True})
+
+ patch_httpx(handler)
+ client = hac.HermesApiClient("http://up:8642", "K")
+ client.get_run("run_abc")
+ client.stop_run("run_abc")
+ assert targets[0] == "http://up:8642/v1/runs/run_abc"
+ assert targets[1] == "http://up:8642/v1/runs/run_abc/stop"
+
+
+# ------------------------------------------------------------------ iter_events (async)
+
+
+def _async_mock_client(hac_module, monkeypatch, handler):
+ """Parchea httpx.AsyncClient para que iter_events use un MockTransport async."""
+ orig_async_client = httpx.AsyncClient
+
+ def _factory(*args, **kwargs):
+ kwargs["transport"] = httpx.MockTransport(handler)
+ return orig_async_client(*args, **kwargs)
+
+ monkeypatch.setattr(hac_module.httpx, "AsyncClient", _factory)
+
+
+def test_iter_events_non_2xx_preserves_full_envelope(monkeypatch):
+ # Fija el blocking Finding "streaming errors lose the common error envelope": un run
+ # desconocido en el endpoint de eventos devuelve el sobre {"error": {...}} COMPLETO como
+ # `error`, con stop_reason "error" (misma forma que request/response).
+ 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"}})
+
+ _async_mock_client(hac, monkeypatch, handler)
+ client = hac.HermesApiClient("http://up:8642", "K")
+ events, next_cursor, error, reason = anyio.run(
+ lambda: client.iter_events("run_x", after_seq=0)
+ )
+ assert events == [] and next_cursor == 0
+ assert reason == "error"
+ assert error == {"error": {"message": "Run not found: run_x",
+ "type": "invalid_request_error", "param": None,
+ "code": "run_not_found"}}
+
+
+def test_iter_events_streams_and_dedup(monkeypatch):
+ body = ": open\n\n" + _sse_message(1) + _sse_message(2) + _sse_message(3)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, text=body,
+ headers={"content-type": "text/event-stream"})
+
+ _async_mock_client(hac, monkeypatch, handler)
+ client = hac.HermesApiClient("http://up:8642", "K")
+ events, next_cursor, error, reason = anyio.run(
+ lambda: client.iter_events("run_x", after_seq=1)
+ )
+ assert error is None
+ assert [e["seq"] for e in events] == [2, 3]
+ assert next_cursor == 3
+ assert reason == hac.STOP_DRAINED
+
+
+def test_iter_events_terminal_event_stops(monkeypatch):
+ body = _sse_message(1) + _sse_message(2, event=hac.TERMINAL_EVENT) + _sse_message(3)
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, text=body,
+ headers={"content-type": "text/event-stream"})
+
+ _async_mock_client(hac, monkeypatch, handler)
+ client = hac.HermesApiClient("http://up:8642", "K")
+ events, _, error, reason = anyio.run(
+ lambda: client.iter_events("run_x", after_seq=0)
+ )
+ assert error is None
+ assert [e["seq"] for e in events] == [1, 2] # para en el terminal
+ assert reason == hac.STOP_TERMINAL
+
+
+def test_iter_events_invalid_run_id_no_network(monkeypatch):
+ called = {"n": 0}
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ called["n"] += 1
+ return httpx.Response(200, text="")
+
+ _async_mock_client(hac, monkeypatch, handler)
+ client = hac.HermesApiClient("http://up:8642", "K")
+ events, _, error, reason = anyio.run(
+ lambda: client.iter_events("../runs", after_seq=0)
+ )
+ assert reason == "error"
+ assert error["error"]["code"] == "invalid_request"
+ assert called["n"] == 0
diff --git a/docker/mcp/tests/test_scope_fold.py b/docker/mcp/tests/test_scope_fold.py
index a8dbbe3..72bb1fc 100644
--- a/docker/mcp/tests/test_scope_fold.py
+++ b/docker/mcp/tests/test_scope_fold.py
@@ -1,8 +1,11 @@
"""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.
+formato de scope-folding, la validación de entrada (empty input/scope, clamp de cursor,
+normalización de opcionales), la terminalidad por booleanos LITERALES (`is_terminal_run`,
+fija review Finding "truthy terminal") y el contrato de `done` de `stream_run_events`
+(`decide_stream_done`, fija los Findings "done on cap-truncated batches" + "done untested"),
+todo lógica pura testeable sin la API viva ni el SDK.
"""
from __future__ import annotations
@@ -83,3 +86,76 @@ def test_normalize_optional_positive():
assert mtl.normalize_optional_positive(-1) is None
assert mtl.normalize_optional_positive(None) is None
assert mtl.normalize_optional_positive(True) is None
+
+
+# ------------------------------------------------------------------ terminalidad (is_terminal_run)
+
+
+def test_is_terminal_run_requires_literal_true():
+ # Fija el blocking Finding "truthy terminal": SOLO el booleano literal True cuenta.
+ assert mtl.is_terminal_run({"completed": True}) is True
+ assert mtl.is_terminal_run({"interrupted": True}) is True
+ assert mtl.is_terminal_run({"completed": False, "interrupted": True}) is True
+
+
+def test_is_terminal_run_rejects_truthy_non_bool():
+ # Valores "verdaderos" que NO son el booleano True NO son terminales (dato no confiable).
+ assert mtl.is_terminal_run({"completed": "false"}) is False # string -> NO terminal
+ assert mtl.is_terminal_run({"completed": "true"}) is False
+ assert mtl.is_terminal_run({"completed": 1}) is False
+ assert mtl.is_terminal_run({"completed": [1]}) is False
+ assert mtl.is_terminal_run({"interrupted": "yes"}) is False
+
+
+def test_is_terminal_run_non_terminal_shapes():
+ assert mtl.is_terminal_run({}) is False
+ assert mtl.is_terminal_run({"completed": False, "interrupted": False}) is False
+ assert mtl.is_terminal_run({"status": "cancelled"}) is False # status NO decide
+ assert mtl.is_terminal_run(None) is False
+ assert mtl.is_terminal_run("completed") is False
+
+
+# ------------------------------------------------------------------ decide_stream_done (done §4.1)
+
+
+def test_done_true_on_terminal_event():
+ done, needs_err = mtl.decide_stream_done(
+ saw_terminal_event=True, stream_drained=False,
+ confirm_run=None, confirm_is_error=False,
+ )
+ assert done is True and needs_err is False
+
+
+def test_done_false_on_cap_without_confirm():
+ # Fija el blocking Finding "done on cap-truncated batches": un batch cortado por tope
+ # (no drenado) NUNCA es done, SIN confirmar get_run (hay cola pendiente tras next_cursor).
+ done, needs_err = mtl.decide_stream_done(
+ saw_terminal_event=False, stream_drained=False,
+ confirm_run={"completed": True}, # aunque el run YA esté terminal upstream...
+ confirm_is_error=False,
+ )
+ assert done is False and needs_err is False # ...el cap manda: seguir paginando
+
+
+def test_done_from_confirm_on_drain():
+ done, needs_err = mtl.decide_stream_done(
+ saw_terminal_event=False, stream_drained=True,
+ confirm_run={"completed": True}, confirm_is_error=False,
+ )
+ assert done is True and needs_err is False
+
+
+def test_done_false_on_drain_non_terminal_confirm():
+ done, needs_err = mtl.decide_stream_done(
+ saw_terminal_event=False, stream_drained=True,
+ confirm_run={"completed": False, "partial": True}, confirm_is_error=False,
+ )
+ assert done is False and needs_err is False # partial==true NO es terminal
+
+
+def test_done_false_and_terminality_error_on_confirm_failure():
+ done, needs_err = mtl.decide_stream_done(
+ saw_terminal_event=False, stream_drained=True,
+ confirm_run={"error": {"code": "upstream_unreachable"}}, confirm_is_error=True,
+ )
+ assert done is False and needs_err is True # error no se traga: terminality_error
diff --git a/docker/mcp/vulnerator_mcp_server.py b/docker/mcp/vulnerator_mcp_server.py
index b61d8f3..ed24d4f 100644
--- a/docker/mcp/vulnerator_mcp_server.py
+++ b/docker/mcp/vulnerator_mcp_server.py
@@ -37,19 +37,19 @@ 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,
+ STOP_DRAINED,
+ STOP_TERMINAL,
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
+# Lógica PURA (SDK-free): scope-folding, validación de entrada y la decisión de `done`.
+# Vive aparte para testearse sin importar FastMCP (igual que scope_guard/tool_streaming en Kali).
from mcp_tool_logic import (
clamp_cursor,
+ decide_stream_done,
fold_scope_into_input,
normalize_optional_positive,
validate_run_id,
@@ -92,20 +92,6 @@ mcp = FastMCP(
_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
@@ -204,11 +190,20 @@ async def stream_run_events(
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``.
+ stream se DRENÓ (upstream cerró la conexión) sin evento terminal Y una confirmación
+ ``get_run`` muestra el run terminal por booleanos LITERALES (``completed is True`` o
+ ``interrupted is True``). Si esa confirmación falla, ``done=False`` (el cliente sigue
+ paginando) y el error se adjunta en ``terminality_error`` (no se traga). Un batch que
+ corta por un TOPE (``max_events``, presupuesto de bytes, o el presupuesto wall-clock
+ ``wait_seconds`` sobre un stream silencioso) devuelve ``done=False`` SIN confirmar: hay
+ eventos pendientes tras ``next_cursor`` y el cliente debe seguir paginando (esto evita el
+ bug de declarar ``done`` dejando la cola —incluido ``output`` y ``run.completed``— sin leer).
+
+ Un FALLO de stream (non-2xx o conexión caída) se devuelve con el sobre ``{"error": {...}}``
+ COMPLETO bajo ``stream_error`` (misma forma que el resto de errores de la API), más los
+ eventos parciales que llegaran antes del fallo. ``wait_seconds`` NO es un error: corta el
+ batch de forma asíncrona (cancelación por deadline) sin esperar al timeout de red ni
+ bloquear el event loop de streamable-http.
Args:
run_id: id del run (string no vacío).
@@ -219,8 +214,9 @@ async def stream_run_events(
Returns:
{"events": [...opaco...], "next_cursor": int, "done": bool[, "terminality_error": {...}]},
- o un sobre de error estructurado ({"error": {...}}) verbatim ante validación/stream
- fallido.
+ o {"events": [...], "next_cursor": int, "done": false, "stream_error": {"error": {...}}}
+ ante un fallo de stream, o un sobre de error estructurado ({"error": {...}}) verbatim
+ ante validación fallida (p. ej. ``run_id`` inválido).
"""
err = validate_run_id(run_id)
if err is not None:
@@ -234,61 +230,63 @@ async def stream_run_events(
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(
+ events, next_cursor, error, stop_reason = await _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.
+ )
+
+ # Progreso (solo streamable-http; try/except para degradar a batching puro en stdio o con
+ # clientes sin soporte de progreso: es cosmético y nunca rompe el batch).
+ if ctx is not None and events:
+ try:
+ await ctx.report_progress(progress=float(len(events)))
+ except Exception: # noqa: BLE001 - progreso es cosmético; nunca rompe el batch
+ pass
+
+ if error is not None:
+ code = error.get("error", {}).get("code") if isinstance(error, dict) else None
+ if code == "invalid_request" and not events:
+ # run_id no es un segmento de path seguro: fail-closed ANTES de tocar la red,
+ # mismo sobre directo que el resto de validaciones (no es un fallo de stream).
+ return error
+ # Fallo del stream (non-2xx o Hermes inalcanzable): se devuelven los eventos parciales
+ # + el sobre {"error": {...}} COMPLETO bajo stream_error (misma forma que el resto de
+ # la API; nunca una forma sintética distinta). done=False -> el cliente puede reintentar.
return {
"events": events,
"next_cursor": next_cursor,
"done": False,
- "stream_error": stream_error,
+ "stream_error": error,
}
+ saw_terminal = stop_reason == STOP_TERMINAL
+ stream_drained = stop_reason == STOP_DRAINED
+
+ # Caso 2 (solo en DRENADO real sin evento terminal): una confirmación get_run decide la
+ # terminalidad por booleanos. Un batch cortado por tope/deadline no confirma (done=False).
+ confirm: Any = None
+ confirm_is_error = False
+ if stream_drained and not saw_terminal:
+ confirm = _client.get_run(run_id)
+ confirm_is_error = isinstance(confirm, dict) and isinstance(confirm.get("error"), dict)
+
+ done, needs_terminality_error = decide_stream_done(
+ saw_terminal_event=saw_terminal,
+ stream_drained=stream_drained,
+ confirm_run=confirm,
+ confirm_is_error=confirm_is_error,
+ )
+
result: dict[str, Any] = {
"events": events,
"next_cursor": next_cursor,
- "done": saw_terminal,
+ "done": done,
}
-
- 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):
+ if needs_terminality_error and isinstance(confirm, dict):
+ # No se traga el error de confirmación: se adjunta su sobre {"error": {...}}.
result["terminality_error"] = confirm["error"]
- result["done"] = False
- else:
- result["done"] = _is_terminal_run(confirm)
return result