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
docs(plugins): translate plugin-system docs and comments to English for repo consistency
irraz699e2bdb3c50
diff --git a/agent-ooda/profile/config.yaml b/agent-ooda/profile/config.yamlindex 2c3aa1a..e19c9ba 100644--- a/agent-ooda/profile/config.yaml+++ b/agent-ooda/profile/config.yaml@@ -88,17 +88,17 @@ mcp_servers:# aislamiento de la red interna de docker.url: "http://kali:8900"tools:- # POSTURA (el SERVIDOR MCP es la FUENTE DE VERDAD: "lo que el servidor expone = lo que- # Hermes ve"). Se RETIRA la `tools.include` que antes hacia whitelist exacta de las tools- # de la Kali. Consecuencias deliberadas (decision del usuario):- # - La superficie VISIBLE pasa de 10 tools a las 15 nativas que el servidor publica por- # introspeccion (server_info ya deriva su lista del registro de FastMCP).- # - Cualquier tool que el servidor anada MAS ADELANTE (incluidas las aportadas por un- # plugin de terceros) entra en la superficie de Hermes SIN pasar por un gate aqui: no- # hay revision caso por caso en este archivo.- # Si se quisiera volver a revisar tool por tool, la via es REANADIR una `include:` con la- # whitelist exacta de nombres (tal como los expone el servidor) bajo esta misma clave- # `tools:`. NO se hace ahora: la fuente de verdad es el servidor.+ # POSTURE (the MCP SERVER is the SOURCE OF TRUTH: "what the server exposes = what+ # Hermes sees"). The `tools.include` that previously did an exact whitelist of the Kali's+ # tools is REMOVED. Deliberate consequences (user's decision):+ # - The VISIBLE surface goes from 10 tools to the 15 native ones that the server+ # publishes by introspection (server_info already derives its list from FastMCP's registry).+ # - Any tool that the server adds LATER (including those contributed by a third-party+ # plugin) enters Hermes's surface WITHOUT passing through a gate here: there is no+ # case-by-case review in this file.+ # If one wanted to review tool by tool again, the way is to RE-ADD an `include:` with the+ # exact whitelist of names (as the server exposes them) under this same `tools:` key.+ # It is NOT done now: the source of truth is the server.# Desactiva los wrappers de utilidad que Hermes anadiria (list_prompts/get_prompt,# list_resources/read_resource). Verificado en mcp.md ("Filter utility tools too").prompts: falsediff --git a/docker/kali/Dockerfile b/docker/kali/Dockerfileindex 6bea4f6..c34cfb8 100644--- a/docker/kali/Dockerfile+++ b/docker/kali/Dockerfile@@ -190,20 +190,20 @@ COPY docker/kali/report_gen.py ./report_gen.py# DEBE estar en la imagen aunque el guard esté desactivado por defecto; sin este COPY el# servidor aborta al arrancar con ModuleNotFoundError: No module named 'scope_guard'.COPY docker/kali/scope_guard.py ./scope_guard.py-# Subsistema de PLUGINS (CORE). plugin_api.py (contrato: PluginContext, DISABLED_SUFFIX,-# tipos del reporte) y plugin_loader.py (descubrimiento + load_plugins + LAST_REPORT) son-# STDLIB PURA pero los importa kali_mcp_server (import plugin_loader dentro de __main__ y-# el bloque de plugins de server_info). Se copian SIEMPRE, con el mismo patrón per-file que-# los módulos nativos; sin estos COPY el servidor abortaría al cargar el reporte de plugins.+# PLUGINS subsystem (CORE). plugin_api.py (contract: PluginContext, DISABLED_SUFFIX,+# report types) and plugin_loader.py (discovery + load_plugins + LAST_REPORT) are+# PURE STDLIB but kali_mcp_server imports them (import plugin_loader inside __main__ and+# the plugins block of server_info). They are copied ALWAYS, with the same per-file pattern as+# the native modules; without these COPY the server would abort when loading the plugins report.COPY docker/kali/plugin_api.py ./plugin_api.pyCOPY docker/kali/plugin_loader.py ./plugin_loader.pyCOPY docker/kali/kali_mcp_server.py ./kali_mcp_server.py-# Árbol de plugins versionado (SOLO plugins). Se congela DENTRO de la imagen en-# /opt/kali-mcp/plugins (WORKDIR): es la ruta que lee load_plugins (PLUGINS_DIR default-# "plugins"). Activar/desactivar un plugin aquí exige REBUILD de la Kali. Esta ruta es-# DISTINTA del bind-mount vivo /opt/plugins de Hermes (ver docs/plugins/discovery.md).-# No hay .dockerignore, así que el árbol versionado plugins/ DEBE existir o el build falla.+# Versioned plugins tree (plugins ONLY). It is frozen INSIDE the image at+# /opt/kali-mcp/plugins (WORKDIR): it is the path that load_plugins reads (PLUGINS_DIR default+# "plugins"). Enabling/disabling a plugin here requires a REBUILD of the Kali. This path is+# DIFFERENT from Hermes's live bind-mount /opt/plugins (see docs/plugins/discovery.md).+# There is no .dockerignore, so the versioned plugins/ tree MUST exist or the build fails.COPY plugins/ ./plugins/# Puerto del servidor kali-mcp. Overridable por entorno (KALI_MCP_PORT) sindiff --git a/docker/kali/kali_mcp_server.py b/docker/kali/kali_mcp_server.pyindex 42564be..ce6b051 100644--- a/docker/kali/kali_mcp_server.py+++ b/docker/kali/kali_mcp_server.py@@ -239,49 +239,49 @@ def server_info() -> dict[str, Any]:"dnsdumpster_key_present": bool(os.environ.get(dnsdumpster_client.API_KEY_ENV, "")),- # `tools` se deriva por INTROSPECCIÓN del registro real de FastMCP, de modo que- # incluye tanto las tools nativas como las aportadas por plugins cargados, sin una- # lista estática que se desincronice. Opción D: una sola fuente de verdad.+ # `tools` is derived by INTROSPECTION of FastMCP's real registry, so that it+ # includes both the native tools and those contributed by loaded plugins, without a+ # static list that gets out of sync. Option D: a single source of truth."tools": _introspect_tool_names(),- # Bloque de observabilidad de plugins (esquema cerrado) leído del reporte de- # `load_plugins`. Vacío y coherente si nunca se cargaron plugins (import suelto).+ # Plugin observability block (closed schema) read from the `load_plugins` report.+ # Empty and coherent if plugins were never loaded (bare import)."plugins": _plugins_block(),}def _introspect_tool_names() -> Any:- """Nombres de tool por introspección SÍNCRONA del registro de FastMCP.+ """Tool names via SYNCHRONOUS introspection of FastMCP's registry.- Usa ``mcp._tool_manager.list_tools()`` (SÍNCRONO; devuelve objetos con ``.name``). NO- se usa el ``FastMCP.list_tools`` público porque es ``async`` y requeriría un event loop- dentro de esta tool. MEDIUM-2: si la API interna no existe o lanza, se DEGRADA con un- marcador en vez de propagar la excepción y tumbar ``server_info``.+ It uses ``mcp._tool_manager.list_tools()`` (SYNCHRONOUS; returns objects with ``.name``).+ The public ``FastMCP.list_tools`` is NOT used because it is ``async`` and would require an+ event loop inside this tool. MEDIUM-2: if the internal API does not exist or raises, it+ DEGRADES with a marker instead of propagating the exception and taking down ``server_info``."""try:return sorted(t.name for t in mcp._tool_manager.list_tools())- except Exception: # noqa: BLE001 - degradar, no tumbar la tool (MEDIUM-2)+ except Exception: # noqa: BLE001 - degrade, do not take down the tool (MEDIUM-2)return "introspección no disponible"def _plugins_block() -> dict[str, Any]:- """Bloque ``plugins`` de ``server_info`` con el esquema CERRADO.+ """``plugins`` block of ``server_info`` with the CLOSED schema.- Lee ``plugin_loader.LAST_REPORT`` (singleton publicado por ``load_plugins``). Clasifica- cada ``PluginRecord`` por ``status``:+ It reads ``plugin_loader.LAST_REPORT`` (singleton published by ``load_plugins``). It+ classifies each ``PluginRecord`` by ``status``:- ``loaded`` -> loaded[]={name,tools[],skill:bool,volumes[]}- - ``degraded`` -> degraded[]={name,collisions[]} (y también cuenta como cargado parcial)+ - ``degraded`` -> degraded[]={name,collisions[]} (and also counts as partially loaded)- ``failed`` -> failed[]={name,phase,error}- Import local de ``plugin_loader`` para no forzar su presencia a nivel de módulo (HIGH-1):- si el módulo no está o ``LAST_REPORT`` es None/ausente, se devuelve un bloque VACÍO- coherente (compat idéntica a hoy).+ Local import of ``plugin_loader`` so as not to force its presence at module level (HIGH-1):+ if the module is absent or ``LAST_REPORT`` is None/missing, a coherent EMPTY block is+ returned (compat identical to today)."""empty: dict[str, Any] = {"loaded": [], "failed": [], "degraded": []}try:import plugin_loaderreport = getattr(plugin_loader, "LAST_REPORT", None)- except Exception: # noqa: BLE001 - sin loader -> bloque vacío coherente+ except Exception: # noqa: BLE001 - no loader -> coherent empty blockreturn emptyif report is None or not getattr(report, "plugins", None):return empty@@ -981,11 +981,11 @@ def _start_artifacts_http() -> None:if __name__ == "__main__":- # Carga de plugins por descubrimiento ANTES de abrir ningún plano. Se invoca SOLO aquí- # (HIGH-1): NUNCA a nivel de módulo, para no correr en cada import ni en los tests sin- # SDK. `load_plugins` publica el reporte en `plugin_loader.LAST_REPORT`, que lee- # `server_info`. Import local a este guard por la misma razón (el loader es STDLIB-pure,- # pero mantenerlo aquí deja el import fuera del camino de los tests de inspección).+ # Plugin loading by discovery BEFORE opening any plane. It is invoked ONLY here+ # (HIGH-1): NEVER at module level, so it does not run on every import nor in the tests+ # without the SDK. `load_plugins` publishes the report in `plugin_loader.LAST_REPORT`,+ # which `server_info` reads. Local import to this guard for the same reason (the loader is+ # STDLIB-pure, but keeping it here keeps the import out of the inspection tests' path).import plugin_loaderplugin_loader.load_plugins(mcp, os.environ.get("PLUGINS_DIR", "plugins"))diff --git a/docker/kali/plugin_api.py b/docker/kali/plugin_api.pyindex 9f2172d..4280aca 100644--- a/docker/kali/plugin_api.py+++ b/docker/kali/plugin_api.py@@ -1,23 +1,24 @@-"""Contrato público del mecanismo de plugins de kali-mcp (STDLIB PURA, SIN ``mcp``).+"""Public contract of the kali-mcp plugin mechanism (PURE STDLIB, NO ``mcp``).-Es la cara del contrato que ven los autores de plugins y que comparten el cargador-(``plugin_loader``) y —por inspección de texto— el ``for`` de skills del compose. Vive en-un módulo aparte que usa SOLO la librería estándar para poder cubrirse con tests unitarios-en el venv de dev, donde el SDK ``mcp`` no está instalado (igual que ``shell_exec`` /+It is the face of the contract seen by plugin authors and shared by the loader+(``plugin_loader``) and —by text inspection— the skills ``for`` of the compose. It lives in+a separate module that uses ONLY the standard library so it can be covered by unit tests in+the dev venv, where the ``mcp`` SDK is not installed (just like ``shell_exec`` /``collector_runner`` / ``scope_guard``).-Qué expone:- - ``SUPPORTED_PLUGIN_API`` / ``DISABLED_SUFFIX`` / ``PLUGIN_DIR_NAME_RE``: constantes de- contrato. ``DISABLED_SUFFIX`` es la ÚNICA fuente del sufijo de deshabilitado en el- código Python (NIT-6): loader y shell del compose lo comparten.- - ``PluginRecord`` / ``PluginLoadReport``: tipos del reporte que lee ``server_info``.- - ``PluginContext``: el handle con firmas fijas (``PLUGIN_API=1``) que el plugin recibe- en su ``register(ctx)``. Detecta colisiones ANTES de registrar una tool y valida que- la skill no escape del directorio del plugin (MEDIUM-4). Es declarativo: ``needs_volume``- NO monta ni habilita nada, solo anota para ``server_info``.--Este módulo NO importa ``mcp``: ``PluginContext`` delega en el objeto ``mcp`` que recibe-(FastMCP real en la imagen, un doble en los tests).+What it exposes:+ - ``SUPPORTED_PLUGIN_API`` / ``DISABLED_SUFFIX`` / ``PLUGIN_DIR_NAME_RE``: contract+ constants. ``DISABLED_SUFFIX`` is the SINGLE source of the disabled suffix in the+ Python code (NIT-6): loader and compose shell share it.+ - ``PluginRecord`` / ``PluginLoadReport``: types of the report that ``server_info`` reads.+ - ``PluginContext``: the handle with fixed signatures (``PLUGIN_API=1``) that the plugin+ receives in its ``register(ctx)``. It detects collisions BEFORE registering a tool and+ validates that the skill does not escape the plugin's directory (MEDIUM-4). It is+ declarative: ``needs_volume`` does NOT mount or enable anything, it only annotates for+ ``server_info``.++This module does NOT import ``mcp``: ``PluginContext`` delegates to the ``mcp`` object it+receives (real FastMCP in the image, a double in the tests)."""from __future__ import annotations@@ -27,35 +28,35 @@ import refrom dataclasses import dataclass, fieldfrom typing import Any-# Versión del contrato que este core soporta. Un plugin declara su ``PLUGIN_API`` y el-# loader exige igualdad exacta (fase 'api'); así una ruptura de contrato falla claro en-# lugar de cargar un plugin incompatible a medias.+# Version of the contract that this core supports. A plugin declares its ``PLUGIN_API`` and+# the loader requires exact equality (phase 'api'); that way a contract break fails cleanly+# instead of loading an incompatible plugin halfway.SUPPORTED_PLUGIN_API = 1-# Sufijo que marca un directorio de plugin como DESHABILITADO. FUENTE ÚNICA (NIT-6): el-# loader lo usa para ignorar el dir y el ``for`` del compose lo compara por inspección.+# Suffix that marks a plugin directory as DISABLED. SINGLE SOURCE (NIT-6): the loader uses+# it to ignore the dir and the compose ``for`` compares it by inspection.DISABLED_SUFFIX = ".disabled"-# Nombre de directorio de plugin permitido (MEDIUM-4): solo alfanuméricos y ``._-`` para-# evitar que un nombre raro se cuele como módulo o rompa el ``sys.path`` insert.+# Allowed plugin directory name (MEDIUM-4): only alphanumerics and ``._-`` to avoid a weird+# name sneaking in as a module or breaking the ``sys.path`` insert.PLUGIN_DIR_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")-# Versión del contrato de ``PluginContext`` (firmas fijas). Se expone como atributo de-# clase e instancia para que un plugin pueda afirmarla si quisiera.+# Version of the ``PluginContext`` contract (fixed signatures). Exposed as a class and+# instance attribute so a plugin can assert it if it wants.PLUGIN_API = 1-# Prefijo común de los logs del subsistema de plugins (loader y contexto).+# Common prefix of the plugin subsystem logs (loader and context)._LOG_PREFIX = "[kali-mcp][plugins]"@dataclassclass PluginRecord:- """Resultado por plugin descubierto, para el reporte y ``server_info``.+ """Per-discovered-plugin result, for the report and ``server_info``.- ``phase`` describe HASTA DÓNDE llegó: ``loaded`` (ok), ``degraded`` (cargó pero con- colisiones) o la fase donde falló (``name``/``import``/``api``/``register-missing``/- ``register``). ``error`` guarda SOLO ``str(exc)`` (una línea, sin rutas); el traceback- completo va a stdout/stderr, no al reporte.+ ``phase`` describes HOW FAR it got: ``loaded`` (ok), ``degraded`` (loaded but with+ collisions) or the phase where it failed (``name``/``import``/``api``/``register-missing``/+ ``register``). ``error`` stores ONLY ``str(exc)`` (a single line, without paths); the full+ traceback goes to stdout/stderr, not to the report."""name: str@@ -70,7 +71,7 @@ class PluginRecord:@dataclassclass PluginLoadReport:- """Reporte agregado de una pasada de ``load_plugins`` (lo lee ``server_info``)."""+ """Aggregate report of a ``load_plugins`` pass (``server_info`` reads it)."""plugins: list[PluginRecord] = field(default_factory=list)@@ -79,11 +80,12 @@ class PluginLoadReport:class PluginContext:- """Handle que el plugin recibe en ``register(ctx)``. Firmas fijas: ``PLUGIN_API=1``.+ """Handle the plugin receives in ``register(ctx)``. Fixed signatures: ``PLUGIN_API=1``.- Es el único punto por el que un plugin toca el servidor: registra tools (con detección- de colisión), declara UNA skill (validada contra escapes de ruta) y anota volúmenes que- necesita (declarativo). No ejecuta efectos de montaje ni habilita nada por sí mismo.+ It is the only point through which a plugin touches the server: it registers tools (with+ collision detection), declares ONE skill (validated against path escapes) and annotates+ the volumes it needs (declarative). It does not run mount effects or enable anything on+ its own."""PLUGIN_API = PLUGIN_API@@ -92,41 +94,41 @@ class PluginContext:self._mcp = mcpself._plugin_dir = os.path.abspath(plugin_dir)self.PLUGIN_API = PLUGIN_API- # Anotaciones recogidas por el loader tras ``register(ctx)``.+ # Annotations collected by the loader after ``register(ctx)``.self.tools: list[str] = []self.collisions: list[str] = []self.volumes: list[str] = []- # Ruta validada de la (única) skill del plugin. Atributo DISTINTO del método- # ``skill()`` para no sombrearlo; el loader lo lee como ``ctx.skill_path``.+ # Validated path of the plugin's (single) skill. A DIFFERENT attribute from the+ # ``skill()`` method so as not to shadow it; the loader reads it as ``ctx.skill_path``.self.skill_path: str | None = Nonedef _existing_tool_names(self) -> set[str]:- """Nombres de tool ya registradas vía la API interna de FastMCP.+ """Names of tools already registered via FastMCP's internal API.- MEDIUM-2: si ``mcp._tool_manager.list_tools()`` no existe o lanza, se PROPAGA la- excepción para que el registro FALLE en vez de delegar a ciegas (no se puede- detectar colisión sin la lista fiable de nombres).+ MEDIUM-2: if ``mcp._tool_manager.list_tools()`` does not exist or raises, the+ exception is PROPAGATED so that the registration FAILS instead of delegating blindly+ (a collision cannot be detected without the reliable list of names)."""tool_manager = self._mcp._tool_managertools = tool_manager.list_tools()return {t.name for t in tools}def tool(self, *args: Any, **kwargs: Any):- """Decorador de tool con DETECCIÓN DE COLISIÓN previa a delegar.+ """Tool decorator with COLLISION DETECTION prior to delegating.- Resuelve el nombre objetivo (kwarg ``name=`` o ``fn.__name__``) y consulta los- nombres existentes. Si ya existe -> NO delega, anota la colisión y devuelve la- función intacta. Si no existe -> delega literalmente en ``mcp.tool(*a, **k)`` y- anota el nombre registrado. MEDIUM-2: si no se puede obtener la lista de nombres,- el registro FALLA (``_existing_tool_names`` propaga).+ It resolves the target name (kwarg ``name=`` or ``fn.__name__``) and queries the+ existing names. If it already exists -> it does NOT delegate, records the collision+ and returns the function untouched. If it does not exist -> it delegates literally to+ ``mcp.tool(*a, **k)`` and records the registered name. MEDIUM-2: if the list of names+ cannot be obtained, the registration FAILS (``_existing_tool_names`` propagates)."""def _decorator(fn: Any) -> Any:name = kwargs.get("name") or getattr(fn, "__name__", None)existing = self._existing_tool_names()if name in existing:- # Colisión: no se pisa la tool existente (add_tool sería un no-op silencioso- # de FastMCP, pero aquí se anota explícitamente como colisión -> degraded).+ # Collision: the existing tool is not overwritten (add_tool would be a silent+ # no-op in FastMCP, but here it is explicitly recorded as a collision -> degraded).self.collisions.append(name)print(f"{_LOG_PREFIX} collision: tool '{name}' ya existe; "@@ -141,11 +143,11 @@ class PluginContext:return _decoratordef skill(self, path: str) -> None:- """Declara la ÚNICA skill del plugin (ruta relativa al dir del plugin).+ """Declares the plugin's SINGLE skill (path relative to the plugin dir).- MEDIUM-4: valida con ``os.path.realpath`` que la ruta resuelta queda BAJO- ``plugin_dir``; si escapa -> warning NO fatal y NO se anota. Una segunda llamada es- un error de contrato (máximo una skill por plugin): se loguea y se ignora.+ MEDIUM-4: it validates with ``os.path.realpath`` that the resolved path stays UNDER+ ``plugin_dir``; if it escapes -> a NON-fatal warning and it is NOT annotated. A second+ call is a contract error (at most one skill per plugin): it is logged and ignored."""if self.skill_path is not None:print(@@ -166,13 +168,13 @@ class PluginContext:self.skill_path = resolveddef needs_volume(self, name: str) -> None:- """Declara (solo anota) que el plugin necesita un volumen. NO monta nada."""+ """Declares (only annotates) that the plugin needs a volume. Mounts NOTHING."""self.volumes.append(name)def plugin_dir(self) -> str:- """Ruta absoluta del directorio del plugin. SIEMPRE devuelve ruta, exista o no."""+ """Absolute path of the plugin's directory. ALWAYS returns a path, exist or not."""return self._plugin_dirdef vendor_dir(self) -> str:- """Ruta absoluta de ``<plugin_dir>/vendor``. SIEMPRE devuelve ruta, exista o no."""+ """Absolute path of ``<plugin_dir>/vendor``. ALWAYS returns a path, exist or not."""return os.path.join(self._plugin_dir, "vendor")diff --git a/docker/kali/plugin_loader.py b/docker/kali/plugin_loader.pyindex ca0f5eb..7d4841e 100644--- a/docker/kali/plugin_loader.py+++ b/docker/kali/plugin_loader.py@@ -1,17 +1,18 @@-"""Cargador por DESCUBRIMIENTO de plugins de kali-mcp (STDLIB PURA, SIN ``mcp``).+"""kali-mcp plugin loader by DISCOVERY (PURE STDLIB, NO ``mcp``).-Enumera los subdirectorios inmediatos de ``plugins_root`` que contienen ``plugin.py``, los-importa AISLADOS (cada uno namespaced bajo ``vuln_plugin_<dir>``) y les da un-``PluginContext`` para que registren tools/skill/volúmenes. Cada plugin se procesa dentro-de su propio ``try/except`` para que uno roto no tumbe a los demás ni al arranque del-servidor. El resultado se guarda en el singleton de módulo ``LAST_REPORT`` (HIGH-1) para-que ``server_info`` lo lea de forma fiable.+It enumerates the immediate subdirectories of ``plugins_root`` that contain ``plugin.py``,+imports them ISOLATED (each namespaced under ``vuln_plugin_<dir>``) and gives them a+``PluginContext`` so they register tools/skill/volumes. Each plugin is processed inside its+own ``try/except`` so a broken one does not take down the others or the server startup. The+result is stored in the module singleton ``LAST_REPORT`` (HIGH-1) so that ``server_info``+reads it reliably.-Compatibilidad idéntica a hoy: si ``plugins_root`` no existe o no es un directorio, el-reporte es VACÍO y no se toca el servidor.+Compatibility identical to today: if ``plugins_root`` does not exist or is not a directory,+the report is EMPTY and the server is not touched.-Este módulo usa SOLO la librería estándar (no importa ``mcp``) para cubrirse con tests en-el venv de dev; ``load_plugins`` recibe el objeto ``mcp`` (FastMCP real o un doble).+This module uses ONLY the standard library (it does not import ``mcp``) so it can be covered+by tests in the dev venv; ``load_plugins`` receives the ``mcp`` object (real FastMCP or a+double)."""from __future__ import annotations@@ -30,21 +31,22 @@ from plugin_api import (PluginRecord,)-# Prefijo de logs del subsistema de carga (tracebacks completos a stdout/stderr).+# Log prefix of the loading subsystem (full tracebacks to stdout/stderr)._LOG_PREFIX = "[kali-mcp][plugins]"-# Singleton de módulo con el ÚLTIMO reporte de carga. ``server_info`` lo lee (HIGH-1).-# Arranca vacío para que, si nunca se llamó a ``load_plugins``, ``server_info`` vea cero-# plugins (compat idéntica a hoy).+# Module singleton with the LAST loading report. ``server_info`` reads it (HIGH-1). It+# starts empty so that, if ``load_plugins`` was never called, ``server_info`` sees zero+# plugins (compat identical to today).LAST_REPORT = PluginLoadReport()def _iter_plugin_dirs(plugins_root: str) -> list[tuple[str, str]]:- """Devuelve ``(name, plugin_dir)`` de los candidatos, en orden ALFABÉTICO determinista.+ """Returns ``(name, plugin_dir)`` of the candidates, in deterministic ALPHABETICAL order.- Ignora: no-directorios, ocultos (prefijo ``.``), dirs terminados en ``DISABLED_SUFFIX``- y dirs sin ``plugin.py``. NO filtra por regex de nombre aquí: un nombre inválido pero- con ``plugin.py`` debe reportarse como fallo de fase 'name' (MEDIUM-4), no omitirse.+ It ignores: non-directories, hidden ones (``.`` prefix), dirs ending in+ ``DISABLED_SUFFIX`` and dirs without ``plugin.py``. It does NOT filter by name regex+ here: an invalid name but with ``plugin.py`` must be reported as a phase 'name' failure+ (MEDIUM-4), not skipped."""candidates: list[tuple[str, str]] = []for name in sorted(os.listdir(plugins_root)):@@ -62,14 +64,14 @@ def _iter_plugin_dirs(plugins_root: str) -> list[tuple[str, str]]:def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:- """Carga un plugin AISLADO aplicando el micro-algoritmo MEDIUM-3/NIT-8.+ """Loads a plugin ISOLATED applying the MEDIUM-3/NIT-8 micro-algorithm.- Fases: 'name' (regex de dir) -> 'import' (exec del cuerpo, dispara los ``import- <hermano>`` vía el ``sys.path`` insert) -> 'api' (PLUGIN_API) -> 'register-missing'- (callable ausente) -> 'register' (``register(ctx)``). En fallo de 'register' se- REVIERTEN las tools ya montadas (NIT-8) para no dejar tools huérfanas visibles.+ Phases: 'name' (dir regex) -> 'import' (exec of the body, triggers the ``import+ <sibling>`` via the ``sys.path`` insert) -> 'api' (PLUGIN_API) -> 'register-missing'+ (callable absent) -> 'register' (``register(ctx)``). On a 'register' failure the+ already-mounted tools are ROLLED BACK (NIT-8) so as not to leave visible orphan tools."""- # (fase name) El nombre de dir debe casar el regex ANTES de tocar sys.path/import.+ # (phase name) The dir name must match the regex BEFORE touching sys.path/import.if not PLUGIN_DIR_NAME_RE.match(name):print(f"{_LOG_PREFIX} plugin '{name}' rechazado: nombre de directorio inválido",@@ -86,22 +88,22 @@ def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:mod_name = f"vuln_plugin_{name}"ctx = PluginContext(mcp, plugin_dir)- # (a) sys.path insert ANTES de ejecutar el cuerpo, para que ``import <hermano>`` dentro- # de plugin.py resuelva contra el propio directorio del plugin (MEDIUM-3).+ # (a) sys.path insert BEFORE executing the body, so that ``import <sibling>`` inside+ # plugin.py resolves against the plugin's own directory (MEDIUM-3).sys.path.insert(0, plugin_dir)try:- # (b) fase 'import': spec_from_file_location + exec_module ejecuta el cuerpo y- # dispara los imports de hermanos; su fallo cae aquí.+ # (b) phase 'import': spec_from_file_location + exec_module runs the body and+ # triggers the sibling imports; its failure lands here.try:spec = importlib.util.spec_from_file_location(mod_name, plugin_py)module = importlib.util.module_from_spec(spec)sys.modules[spec.name] = modulespec.loader.exec_module(module)- except Exception as exc: # noqa: BLE001 - aislado: un plugin roto no tumba al resto+ except Exception as exc: # noqa: BLE001 - isolated: a broken plugin does not take down the resttraceback.print_exc()return PluginRecord(name=name, status="failed", phase="import", error=str(exc))- # (c) fase 'api': el plugin debe declarar un PLUGIN_API compatible (igualdad exacta).+ # (c) phase 'api': the plugin must declare a compatible PLUGIN_API (exact equality).plugin_api_version = getattr(module, "PLUGIN_API", None)if plugin_api_version != SUPPORTED_PLUGIN_API:msg = (@@ -111,7 +113,7 @@ def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:print(f"{_LOG_PREFIX} plugin '{name}' rechazado: {msg}", flush=True)return PluginRecord(name=name, status="failed", phase="api", error=msg)- # (d) fase 'register-missing': debe exponer un ``register`` callable.+ # (d) phase 'register-missing': it must expose a callable ``register``.register = getattr(module, "register", None)if not callable(register):msg = "falta un callable register(ctx)"@@ -120,21 +122,21 @@ def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:name=name, status="failed", phase="register-missing", error=msg)- # (e) fase 'register': ejecutar register(ctx). Si lanza, NIT-8: revertir tools.+ # (e) phase 'register': run register(ctx). If it raises, NIT-8: roll back tools.try:register(ctx)- except Exception as exc: # noqa: BLE001 - aislado+ except Exception as exc: # noqa: BLE001 - isolatedtraceback.print_exc()for tool_name in ctx.tools:try:mcp._tool_manager.remove_tool(tool_name)- except Exception: # noqa: BLE001 - best-effort de reversión+ except Exception: # noqa: BLE001 - best-effort rollbacktraceback.print_exc()return PluginRecord(name=name, status="failed", phase="register", error=str(exc))- # (f) recoger lo anotado; colisiones -> degraded (cargó, pero no todo entró).+ # (f) collect what was annotated; collisions -> degraded (loaded, but not all entered).if ctx.collisions:status, phase = "degraded", "register"else:@@ -149,7 +151,7 @@ def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:collisions=list(ctx.collisions),)finally:- # (g) restaurar sys.path tras cada plugin (quitar SOLO la entrada insertada).+ # (g) restore sys.path after each plugin (remove ONLY the inserted entry).try:sys.path.remove(plugin_dir)except ValueError:@@ -157,10 +159,11 @@ def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:def load_plugins(mcp, plugins_root: str) -> PluginLoadReport:- """Descubre y carga los plugins bajo ``plugins_root``. Devuelve y publica el reporte.+ """Discovers and loads the plugins under ``plugins_root``. Returns and publishes the report.- Si ``plugins_root`` no existe o no es un directorio -> reporte VACÍO (compat idéntica a- hoy). Antes de devolver, asigna ``plugin_loader.LAST_REPORT = report`` (HIGH-1).+ If ``plugins_root`` does not exist or is not a directory -> EMPTY report (compat+ identical to today). Before returning, it assigns ``plugin_loader.LAST_REPORT = report``+ (HIGH-1)."""global LAST_REPORTreport = PluginLoadReport()diff --git a/docker/kali/tests/fixtures/plugins/README.md b/docker/kali/tests/fixtures/plugins/README.mdindex 2f4cc79..7615ae1 100644--- a/docker/kali/tests/fixtures/plugins/README.md+++ b/docker/kali/tests/fixtures/plugins/README.md@@ -1,18 +1,18 @@-# Fixtures de plugins para `test_plugin_loader`+# Plugin fixtures for `test_plugin_loader`-Árbol de plugins de ejemplo que `test_plugin_loader.py` apunta como `plugins_root`. Cada-subdirectorio ejercita un camino del cargador:+Example plugin tree that `test_plugin_loader.py` points at as `plugins_root`. Each+subdirectory exercises one loader path:-- `aaa_first` / `zzz_last`: plugins válidos (comprueban orden alfabético determinista).-- `sibling_import`: `plugin.py` que hace `import helper` (hermano) — demuestra MEDIUM-3.-- `broken_import.src` → se renombra en test a un dir con import roto (ver nota). En su- lugar usamos `broken_import` con un `import` inexistente (fase 'import').-- `no_api`: sin `PLUGIN_API` (fase 'api').-- `bad_api`: `PLUGIN_API` incompatible (fase 'api').-- `no_register`: sin callable `register` (fase 'register-missing').-- `raises_register`: `register` que registra una tool y luego lanza (fase 'register' + NIT-8).-- `example.disabled`: dir deshabilitado (ignorado).-- `not_a_plugin`: dir sin `plugin.py` (omitido).+- `aaa_first` / `zzz_last`: valid plugins (check deterministic alphabetical order).+- `sibling_import`: `plugin.py` that does `import helper` (sibling) — demonstrates MEDIUM-3.+- `broken_import.src` → renamed in the test to a dir with a broken import (see note). Instead+ we use `broken_import` with a nonexistent `import` (phase 'import').+- `no_api`: without `PLUGIN_API` (phase 'api').+- `bad_api`: incompatible `PLUGIN_API` (phase 'api').+- `no_register`: without a callable `register` (phase 'register-missing').+- `raises_register`: `register` that registers a tool and then raises (phase 'register' + NIT-8).+- `example.disabled`: disabled dir (ignored).+- `not_a_plugin`: dir without `plugin.py` (skipped).-Los nombres inválidos de directorio (MEDIUM-4) NO pueden existir como carpeta portable en-todos los FS, así que ese caso se crea en caliente dentro del test con `tmp_path`.+Invalid directory names (MEDIUM-4) CANNOT exist as a portable folder on all FS, so that case+is created on the fly inside the test with `tmp_path`.diff --git a/docker/kali/tests/fixtures/plugins/aaa_first/plugin.py b/docker/kali/tests/fixtures/plugins/aaa_first/plugin.pyindex 4bea07f..322654c 100644--- a/docker/kali/tests/fixtures/plugins/aaa_first/plugin.py+++ b/docker/kali/tests/fixtures/plugins/aaa_first/plugin.py@@ -1,4 +1,4 @@-"""Plugin válido mínimo (fixture). Registra una tool y declara su skill."""+"""Minimal valid plugin (fixture). Registers a tool and declares its skill."""PLUGIN_API = 1diff --git a/docker/kali/tests/fixtures/plugins/bad_api/plugin.py b/docker/kali/tests/fixtures/plugins/bad_api/plugin.pyindex a5ad641..40a1c11 100644--- a/docker/kali/tests/fixtures/plugins/bad_api/plugin.py+++ b/docker/kali/tests/fixtures/plugins/bad_api/plugin.py@@ -1,7 +1,7 @@-"""Fixture fase 'api': PLUGIN_API incompatible (distinto de SUPPORTED_PLUGIN_API)."""+"""Phase 'api' fixture: incompatible PLUGIN_API (different from SUPPORTED_PLUGIN_API)."""PLUGIN_API = 999-def register(ctx): # pragma: no cover - nunca se alcanza+def register(ctx): # pragma: no cover - never reachedpassdiff --git a/docker/kali/tests/fixtures/plugins/broken_import/plugin.py b/docker/kali/tests/fixtures/plugins/broken_import/plugin.pyindex d89e452..3ca49a3 100644--- a/docker/kali/tests/fixtures/plugins/broken_import/plugin.py+++ b/docker/kali/tests/fixtures/plugins/broken_import/plugin.py@@ -1,9 +1,9 @@-"""Fixture fase 'import': importa un módulo inexistente -> exec_module lanza."""+"""Phase 'import' fixture: imports a nonexistent module -> exec_module raises."""import this_module_does_not_exist_anywhere # noqa: F401PLUGIN_API = 1-def register(ctx): # pragma: no cover - nunca se alcanza+def register(ctx): # pragma: no cover - never reachedpassdiff --git a/docker/kali/tests/fixtures/plugins/example.disabled/plugin.py b/docker/kali/tests/fixtures/plugins/example.disabled/plugin.pyindex 9c4472d..9900aeb 100644--- a/docker/kali/tests/fixtures/plugins/example.disabled/plugin.py+++ b/docker/kali/tests/fixtures/plugins/example.disabled/plugin.py@@ -1,9 +1,9 @@-"""Fixture: dir terminado en .disabled -> el loader lo IGNORA (no debe cargarse)."""+"""Fixture: dir ending in .disabled -> the loader IGNORES it (must not be loaded)."""PLUGIN_API = 1-def register(ctx): # pragma: no cover - nunca se alcanza: el dir está deshabilitado+def register(ctx): # pragma: no cover - never reached: the dir is disabled@ctx.tool(name="should_not_appear")def should_not_appear():return "nope"diff --git a/docker/kali/tests/fixtures/plugins/no_api/plugin.py b/docker/kali/tests/fixtures/plugins/no_api/plugin.pyindex 4eb9a5e..f8088a7 100644--- a/docker/kali/tests/fixtures/plugins/no_api/plugin.py+++ b/docker/kali/tests/fixtures/plugins/no_api/plugin.py@@ -1,5 +1,5 @@-"""Fixture fase 'api': no declara PLUGIN_API."""+"""Phase 'api' fixture: it does not declare PLUGIN_API."""-def register(ctx): # pragma: no cover - nunca se alcanza+def register(ctx): # pragma: no cover - never reachedpassdiff --git a/docker/kali/tests/fixtures/plugins/no_register/plugin.py b/docker/kali/tests/fixtures/plugins/no_register/plugin.pyindex 927eb60..7f97fc8 100644--- a/docker/kali/tests/fixtures/plugins/no_register/plugin.py+++ b/docker/kali/tests/fixtures/plugins/no_register/plugin.py@@ -1,4 +1,4 @@-"""Fixture fase 'register-missing': no expone un callable register."""+"""Phase 'register-missing' fixture: it does not expose a callable register."""PLUGIN_API = 1diff --git a/docker/kali/tests/fixtures/plugins/not_a_plugin/README.md b/docker/kali/tests/fixtures/plugins/not_a_plugin/README.mdindex a4b9f99..1a126bc 100644--- a/docker/kali/tests/fixtures/plugins/not_a_plugin/README.md+++ b/docker/kali/tests/fixtures/plugins/not_a_plugin/README.md@@ -1 +1 @@-Dir SIN plugin.py: el loader lo omite (no es candidato).+Dir WITHOUT plugin.py: the loader skips it (it is not a candidate).diff --git a/docker/kali/tests/fixtures/plugins/raises_register/plugin.py b/docker/kali/tests/fixtures/plugins/raises_register/plugin.pyindex e3afc12..93767f6 100644--- a/docker/kali/tests/fixtures/plugins/raises_register/plugin.py+++ b/docker/kali/tests/fixtures/plugins/raises_register/plugin.py@@ -1,6 +1,6 @@-"""Fixture fase 'register' + NIT-8: registra una tool y luego LANZA.+"""Phase 'register' + NIT-8 fixture: registers a tool and then RAISES.-El loader debe revertir la tool ya montada vía ``_tool_manager.remove_tool``.+The loader must roll back the already-mounted tool via ``_tool_manager.remove_tool``."""PLUGIN_API = 1diff --git a/docker/kali/tests/fixtures/plugins/sibling_import/helper.py b/docker/kali/tests/fixtures/plugins/sibling_import/helper.pyindex 21b013a..1330cd1 100644--- a/docker/kali/tests/fixtures/plugins/sibling_import/helper.py+++ b/docker/kali/tests/fixtures/plugins/sibling_import/helper.py@@ -1,4 +1,4 @@-"""Módulo HERMANO del fixture ``sibling_import`` (MEDIUM-3)."""+"""SIBLING module of the ``sibling_import`` fixture (MEDIUM-3)."""TOOL_NAME = "sibling_tool"VALUE = "from-helper"diff --git a/docker/kali/tests/fixtures/plugins/sibling_import/plugin.py b/docker/kali/tests/fixtures/plugins/sibling_import/plugin.pyindex 0d0b55c..cc9b4ed 100644--- a/docker/kali/tests/fixtures/plugins/sibling_import/plugin.py+++ b/docker/kali/tests/fixtures/plugins/sibling_import/plugin.py@@ -1,10 +1,10 @@-"""Fixture MEDIUM-3: plugin.py que importa un HERMANO (``helper``) del mismo dir.+"""MEDIUM-3 fixture: plugin.py that imports a SIBLING (``helper``) from the same dir.-Si el ``sys.path`` insert del loader no estuviera, este ``import helper`` fallaría y el-plugin caería en fase 'import'. Con el insert, resuelve contra el propio directorio.+If the loader's ``sys.path`` insert were not there, this ``import helper`` would fail and the+plugin would fall into phase 'import'. With the insert, it resolves against its own directory."""-import helper # noqa: F401 - hermano del mismo dir del plugin+import helper # noqa: F401 - sibling from the plugin's own dirPLUGIN_API = 1diff --git a/docker/kali/tests/fixtures/plugins/zzz_last/plugin.py b/docker/kali/tests/fixtures/plugins/zzz_last/plugin.pyindex 6bf1a15..41a1baf 100644--- a/docker/kali/tests/fixtures/plugins/zzz_last/plugin.py+++ b/docker/kali/tests/fixtures/plugins/zzz_last/plugin.py@@ -1,4 +1,4 @@-"""Segundo plugin válido (fixture) para comprobar orden alfabético determinista."""+"""Second valid plugin (fixture) to check deterministic alphabetical order."""PLUGIN_API = 1diff --git a/docker/kali/tests/test_disabled_parity.py b/docker/kali/tests/test_disabled_parity.pyindex 84529b1..4478339 100644--- a/docker/kali/tests/test_disabled_parity.py+++ b/docker/kali/tests/test_disabled_parity.py@@ -1,19 +1,19 @@-"""Test de PARIDAD del sufijo .disabled entre las dos capas (NIT-6).--El sufijo que apaga un plugin vive en DOS sitios que NO deben divergir:- - la capa Python: ``plugin_api.DISABLED_SUFFIX`` (lo usa ``plugin_loader`` para ignorar el- directorio en el servidor kali-mcp);- - la capa shell: el ``for`` de skills de plugins del ``command`` de ``ooda-agent`` en- ``docker-compose.yml``, que salta los directorios ``*.disabled`` antes de copiar su skill.--Si una capa cambiara el sufijo y la otra no, un plugin quedaría "medio apagado" (apagado en-una capa y vivo en la otra). Este test fija que:- 1. ``plugin_api.DISABLED_SUFFIX == '.disabled'`` (fuente única del lado Python);- 2. el ``command`` de ``ooda-agent`` contiene la regla shell que salta ``*.disabled``,- por INSPECCIÓN del texto fuente del compose (no se levanta el stack).--Restricción de entorno (igual que el resto del core): STDLIB PURA, sin importar el SDK-``mcp`` ni el servidor; ``plugin_api`` es STDLIB PURA y sí se puede importar.+"""PARITY test of the .disabled suffix between the two layers (NIT-6).++The suffix that turns off a plugin lives in TWO places that must NOT diverge:+ - the Python layer: ``plugin_api.DISABLED_SUFFIX`` (``plugin_loader`` uses it to ignore the+ directory in the kali-mcp server);+ - the shell layer: the plugin skills ``for`` of the ``ooda-agent`` ``command`` in+ ``docker-compose.yml``, which skips ``*.disabled`` directories before copying their skill.++If one layer changed the suffix and the other did not, a plugin would end up "half off" (off+in one layer and alive in the other). This test pins that:+ 1. ``plugin_api.DISABLED_SUFFIX == '.disabled'`` (single source on the Python side);+ 2. the ``ooda-agent`` ``command`` contains the shell rule that skips ``*.disabled``, by+ INSPECTION of the compose source text (the stack is not brought up).++Environment constraint (like the rest of the core): PURE STDLIB, without importing the+``mcp`` SDK or the server; ``plugin_api`` is PURE STDLIB and can indeed be imported."""from __future__ import annotations@@ -26,28 +26,28 @@ sys.path.insert(0, str(_PARENT))import plugin_api # noqa: E402-# Raíz del worktree = dos niveles por encima de docker/kali/.+# Worktree root = two levels above docker/kali/._COMPOSE_PATH = _PARENT.parent.parent / "docker-compose.yml"def test_disabled_suffix_es_punto_disabled():- """La fuente única del lado Python es exactamente '.disabled'."""+ """The single source on the Python side is exactly '.disabled'."""assert plugin_api.DISABLED_SUFFIX == ".disabled"def test_compose_salta_disabled_en_el_bucle_de_skills():- """El command de ooda-agent salta los plugins *.disabled con el MISMO sufijo."""+ """The ooda-agent command skips *.disabled plugins with the SAME suffix."""source = _COMPOSE_PATH.read_text(encoding="utf-8")- # La regla shell que apaga un plugin por nombre de directorio. Comparte el sufijo- # '.disabled' con plugin_api.DISABLED_SUFFIX: ambas capas deben usar el mismo.+ # The shell rule that turns off a plugin by directory name. It shares the '.disabled'+ # suffix with plugin_api.DISABLED_SUFFIX: both layers must use the same one.assert 'case "$$name" in *.disabled) continue' in source- # El sufijo del compose coincide literalmente con la constante del lado Python.+ # The compose suffix matches the Python-side constant literally.assert f"*{plugin_api.DISABLED_SUFFIX})" in sourcedef test_bucle_de_skills_blindado():- """El bucle de skills de plugins está blindado (no puede abortar el arranque)."""+ """The plugin skills loop is shielded (it cannot abort startup)."""source = _COMPOSE_PATH.read_text(encoding="utf-8")- # Gateado en que el directorio exista y ejecutado en un subshell con `set +e`.+ # Gated on the directory existing and run in a subshell with `set +e`.assert "if [ -d /opt/plugins ]; then (" in sourceassert "set +e;" in sourcediff --git a/docker/kali/tests/test_example_hello.py b/docker/kali/tests/test_example_hello.pyindex b4fbbdd..76269a3 100644--- a/docker/kali/tests/test_example_hello.py+++ b/docker/kali/tests/test_example_hello.py@@ -1,12 +1,12 @@-"""Test del plugin de EJEMPLO ``example-hello`` (STDLIB PURA, con doble de ``mcp``).+"""Test of the EXAMPLE plugin ``example-hello`` (PURE STDLIB, with an ``mcp`` double).-El directorio del plugin termina en ``.disabled``, por lo que NO es importable por nombre:-se carga su ``plugin.py`` POR RUTA con ``importlib.util.spec_from_file_location`` (igual que-hace el cargador real). Se ejecuta ``register(ctx)`` con un ``PluginContext`` real sobre un-doble de ``mcp`` (el SDK no está en el venv de dev), siguiendo el patrón de ``test_plugin_api``.+The plugin's directory ends in ``.disabled``, so it is NOT importable by name: its+``plugin.py`` is loaded BY PATH with ``importlib.util.spec_from_file_location`` (just like+the real loader does). ``register(ctx)`` is run with a real ``PluginContext`` over an ``mcp``+double (the SDK is not in the dev venv), following the ``test_plugin_api`` pattern.-Verifica que el plugin monta la tool ``hello``, declara la skill y el volumen, y que la tool-capturada devuelve el saludo inocuo esperado.+It verifies that the plugin mounts the ``hello`` tool, declares the skill and the volume,+and that the captured tool returns the expected harmless greeting."""from __future__ import annotations@@ -21,7 +21,7 @@ sys.path.insert(0, str(_PARENT))import plugin_api # noqa: E402-# Ruta al plugin.py del ejemplo (directorio .disabled -> solo cargable por ruta).+# Path to the example's plugin.py (.disabled directory -> only loadable by path)._PLUGIN_DIR = _PARENT.parent.parent / "plugins" / "example-hello.disabled"_PLUGIN_PY = _PLUGIN_DIR / "plugin.py"@@ -43,7 +43,7 @@ class _FakeToolManager:class _FakeMcp:- """Doble de FastMCP que CAPTURA la función decorada por ``tool()`` para invocarla."""+ """Double of FastMCP that CAPTURES the function decorated by ``tool()`` to invoke it."""def __init__(self, existing=None) -> None:self._tool_manager = _FakeToolManager(existing)@@ -80,15 +80,15 @@ def test_register_monta_hello_skill_y_volumen():module.register(ctx)- # Monta la tool 'hello'.+ # Mounts the 'hello' tool.assert ctx.tools == ["hello"]assert ctx.collisions == []assert "hello" in mcp.registered- # Declara la skill (directorio skill/ bajo el plugin).+ # Declares the skill (skill/ directory under the plugin).assert ctx.skill_path == os.path.realpath(str(_PLUGIN_DIR / "skill"))- # Declara (anota) el volumen de artefactos.+ # Declares (annotates) the artifacts volume.assert ctx.volumes == ["kali-artifacts"]diff --git a/docker/kali/tests/test_plugin_api.py b/docker/kali/tests/test_plugin_api.pyindex 590a8f3..58c4d9a 100644--- a/docker/kali/tests/test_plugin_api.py+++ b/docker/kali/tests/test_plugin_api.py@@ -1,9 +1,9 @@-"""Tests de ``PluginContext`` (STDLIB PURA, con un doble de ``mcp`` — SIN el SDK).+"""Tests of ``PluginContext`` (PURE STDLIB, with a ``mcp`` double — WITHOUT the SDK).-El contrato se valida con un doble de ``mcp`` que imita la parte de la API interna de-FastMCP que ``PluginContext`` toca: ``mcp.tool(*a, **k)`` (decorador) y-``mcp._tool_manager.list_tools()`` (nombres existentes). No se importa el SDK ``mcp``-(no está en el venv de dev), igual que el resto de tests del core.+The contract is validated with an ``mcp`` double that mimics the part of FastMCP's internal+API that ``PluginContext`` touches: ``mcp.tool(*a, **k)`` (decorator) and+``mcp._tool_manager.list_tools()`` (existing names). The ``mcp`` SDK is not imported+(it is not in the dev venv), just like the rest of the core tests."""from __future__ import annotations@@ -26,7 +26,7 @@ class _FakeTool:class _FakeToolManager:- """Doble del ``_tool_manager`` de FastMCP: lista y elimina tools por nombre."""+ """Double of FastMCP's ``_tool_manager``: lists and removes tools by name."""def __init__(self, names=None) -> None:self._names = list(names or [])@@ -39,7 +39,7 @@ class _FakeToolManager:class _FakeMcp:- """Doble de FastMCP: ``tool(*a, **k)`` registra el nombre al aplicarse al fn."""+ """Double of FastMCP: ``tool(*a, **k)`` records the name when applied to the fn."""def __init__(self, existing=None) -> None:self._tool_manager = _FakeToolManager(existing)@@ -54,7 +54,7 @@ class _FakeMcp:class _McpWithoutListTools:- """Doble SIN ``_tool_manager.list_tools`` para probar el fallback MEDIUM-2."""+ """Double WITHOUT ``_tool_manager.list_tools`` to test the MEDIUM-2 fallback."""class _TM:pass@@ -62,7 +62,7 @@ class _McpWithoutListTools:def __init__(self) -> None:self._tool_manager = self._TM()- def tool(self, *args, **kwargs): # pragma: no cover - no debe llegar a delegar+ def tool(self, *args, **kwargs): # pragma: no cover - must not reach delegationdef _decorator(fn):return fn@@ -79,7 +79,7 @@ def test_tool_delega_y_registra_el_nombre():assert ctx.tools == ["my_scan"]assert ctx.collisions == []- # La tool quedó efectivamente registrada en el doble.+ # The tool was effectively registered in the double.assert "my_scan" in {t.name for t in mcp._tool_manager.list_tools()}@@ -96,7 +96,7 @@ def test_tool_colision_con_nativa_no_delega():def test_tool_colision_con_otro_plugin_no_delega():- # Dos contextos sobre el MISMO mcp: el primero registra 'shared', el segundo colisiona.+ # Two contexts over the SAME mcp: the first registers 'shared', the second collides.mcp = _FakeMcp()ctx_a = plugin_api.PluginContext(mcp, "/opt/plugins/a")ctx_b = plugin_api.PluginContext(mcp, "/opt/plugins/b")@@ -153,7 +153,7 @@ def test_skill_segunda_llamada_es_error_de_contrato(tmp_path):ctx.skill("a.md")ctx.skill("b.md")- # Se queda con la primera; la segunda se ignora.+ # It keeps the first; the second is ignored.assert ctx.skill_path == os.path.realpath(str(plugin_dir / "a.md"))@@ -173,7 +173,7 @@ def test_plugin_dir_y_vendor_dir_siempre_absolutos():def test_vendor_dir_absoluto_aunque_no_exista(tmp_path):- # vendor/ no existe pero vendor_dir() devuelve ruta absoluta igualmente (nunca None).+ # vendor/ does not exist but vendor_dir() returns an absolute path anyway (never None).plugin_dir = tmp_path / "p"plugin_dir.mkdir()ctx = plugin_api.PluginContext(_FakeMcp(), str(plugin_dir))diff --git a/docker/kali/tests/test_plugin_introspection.py b/docker/kali/tests/test_plugin_introspection.pyindex 01387a6..5ca53b9 100644--- a/docker/kali/tests/test_plugin_introspection.py+++ b/docker/kali/tests/test_plugin_introspection.py@@ -1,19 +1,20 @@-"""Guardia EJECUTABLE de la API interna de FastMCP de la que depende el plugin system.--Este es el ÚNICO test que valida §5.3 DE VERDAD: ejecuta contra el SDK ``mcp`` real las-cuatro asunciones sobre la API interna/pública de ``FastMCP`` en las que se apoyan el-cargador de plugins (``plugin_loader`` / ``plugin_api``) y ``server_info``:-- 1. ``mcp._tool_manager.list_tools()`` existe, es SÍNCRONO (no es coroutine function) y- devuelve objetos con atributo ``.name``.- 2. El ``FastMCP.list_tools`` PÚBLICO es ``async`` (por eso ``server_info`` usa el interno).- 3. Registrar DOS veces una tool con el mismo nombre es un no-op SILENCIOSO (no lanza y no- reemplaza la primera) — base de la detección explícita de colisiones.- 4. ``_tool_manager.remove_tool(name)`` existe y funciona — base del revert NIT-8.--Si el SDK NO está instalado (venv dev) -> ``pytest.skip`` EXPLÍCITO: el skip es sólo para-el entorno sin SDK. EN CI/IMAGEN CON SDK NO DEBE SALTARSE: un fallo real de API no puede-quedar enmascarado por el skip local.+"""EXECUTABLE guard of the FastMCP internal API that the plugin system depends on.++This is the ONLY test that validates §5.3 FOR REAL: it runs against the real ``mcp`` SDK the+four assumptions about ``FastMCP``'s internal/public API on which the plugin loader+(``plugin_loader`` / ``plugin_api``) and ``server_info`` rely:++ 1. ``mcp._tool_manager.list_tools()`` exists, is SYNCHRONOUS (not a coroutine function) and+ returns objects with a ``.name`` attribute.+ 2. The PUBLIC ``FastMCP.list_tools`` is ``async`` (that is why ``server_info`` uses the+ internal one).+ 3. Registering a tool TWICE with the same name is a SILENT no-op (it does not raise and does+ not replace the first) — the basis of explicit collision detection.+ 4. ``_tool_manager.remove_tool(name)`` exists and works — the basis of the NIT-8 rollback.++If the SDK is NOT installed (dev venv) -> EXPLICIT ``pytest.skip``: the skip is only for the+environment without the SDK. IN CI/IMAGE WITH THE SDK IT MUST NOT BE SKIPPED: a real API+failure cannot be masked by the local skip."""from __future__ import annotations@@ -23,10 +24,10 @@ import inspectimport pytest-# El SDK sólo está en la imagen Kali / un venv con mcp>=1.28,<2. Sin él, skip explícito.+# The SDK is only in the Kali image / a venv with mcp>=1.28,<2. Without it, explicit skip.fastmcp_mod = pytest.importorskip("mcp.server.fastmcp",- reason="SDK 'mcp' no instalado (venv dev); en imagen/CI con SDK NO debe saltarse",+ reason="'mcp' SDK not installed (dev venv); in image/CI with the SDK it must NOT be skipped",)FastMCP = fastmcp_mod.FastMCP@@ -40,23 +41,23 @@ def test_tool_manager_list_tools_es_sincrono_y_da_objetos_con_name():@mcp.tool()def alpha() -> str:- """tool de prueba."""+ """test tool."""return "alpha"tool_manager = mcp._tool_manager- # Existe y NO es una coroutine function (es SÍNCRONO).+ # It exists and is NOT a coroutine function (it is SYNCHRONOUS).assert hasattr(tool_manager, "list_tools")assert not inspect.iscoroutinefunction(tool_manager.list_tools)tools = tool_manager.list_tools()assert not inspect.iscoroutine(tools), "list_tools() no debe devolver una corutina"- names = {t.name for t in tools} # cada objeto expone .name+ names = {t.name for t in tools} # each object exposes .nameassert "alpha" in namesdef test_fastmcp_list_tools_publico_es_async():- # El método público de FastMCP es async: por eso server_info usa el tool_manager interno- # (síncrono) en vez de este (requeriría un event loop).+ # FastMCP's public method is async: that is why server_info uses the internal (synchronous)+ # tool_manager instead of this one (which would require an event loop).assert inspect.iscoroutinefunction(FastMCP.list_tools)@@ -65,20 +66,20 @@ def test_add_tool_duplicado_es_noop_silencioso():@mcp.tool(name="dup")def first() -> str:- """primera."""+ """first."""return "first"before = {t.name for t in mcp._tool_manager.list_tools()}assert "dup" in before- # Registrar otra con el MISMO nombre no debe lanzar...+ # Registering another with the SAME name must not raise...@mcp.tool(name="dup")def second() -> str:- """segunda (misma clave)."""+ """second (same key)."""return "second"after = [t for t in mcp._tool_manager.list_tools() if t.name == "dup"]- # ...ni duplicar la entrada (sigue habiendo exactamente una 'dup').+ # ...nor duplicate the entry (there is still exactly one 'dup').assert len(after) == 1@@ -87,7 +88,7 @@ def test_remove_tool_existe_y_funciona():@mcp.tool(name="temp")def temp() -> str:- """tool temporal."""+ """temporary tool."""return "temp"assert "temp" in {t.name for t in mcp._tool_manager.list_tools()}@@ -97,12 +98,12 @@ def test_remove_tool_existe_y_funciona():def test_server_puede_listar_tools_via_api_publica_async():- # Sanity: la API pública async también funciona (confirma que el objeto es usable).+ # Sanity: the async public API also works (confirms the object is usable).mcp = _new_server()@mcp.tool()def beta() -> str:- """tool de prueba."""+ """test tool."""return "beta"tools = asyncio.run(mcp.list_tools())diff --git a/docker/kali/tests/test_plugin_loader.py b/docker/kali/tests/test_plugin_loader.pyindex c9da99e..c56e944 100644--- a/docker/kali/tests/test_plugin_loader.py+++ b/docker/kali/tests/test_plugin_loader.py@@ -1,8 +1,8 @@-"""Tests de ``load_plugins`` (STDLIB PURA, con un doble de ``mcp`` — SIN el SDK).+"""Tests of ``load_plugins`` (PURE STDLIB, with a ``mcp`` double — WITHOUT the SDK).-Usan el árbol de fixtures en ``tests/fixtures/plugins/`` como ``plugins_root`` y un doble de-``mcp`` cuyo ``_tool_manager`` registra las llamadas a ``remove_tool`` (para probar la-reversión NIT-8). No se importa el SDK ``mcp`` (no está en el venv de dev).+They use the fixtures tree in ``tests/fixtures/plugins/`` as ``plugins_root`` and an ``mcp``+double whose ``_tool_manager`` records the calls to ``remove_tool`` (to test the NIT-8+rollback). The ``mcp`` SDK is not imported (it is not in the dev venv)."""from __future__ import annotations@@ -58,7 +58,7 @@ def test_raiz_inexistente_reporte_vacio_y_last_report(tmp_path):missing = str(tmp_path / "nope")report = plugin_loader.load_plugins(mcp, missing)assert report.plugins == []- # LAST_REPORT quedó asignado al reporte vacío (HIGH-1).+ # LAST_REPORT was assigned to the empty report (HIGH-1).assert plugin_loader.LAST_REPORT is report@@ -74,12 +74,12 @@ def test_orden_determinista_y_omisiones():report = plugin_loader.load_plugins(mcp, str(_FIXTURES))names = [r.name for r in report.plugins]- # Orden alfabético estricto entre los candidatos presentes.+ # Strict alphabetical order among the present candidates.assert names == sorted(names)- # Dir .disabled ignorado y dir sin plugin.py omitido.+ # .disabled dir ignored and dir without plugin.py skipped.assert "example.disabled" not in namesassert "not_a_plugin" not in names- # 'aaa_first' va antes que 'zzz_last'.+ # 'aaa_first' comes before 'zzz_last'.assert names.index("aaa_first") < names.index("zzz_last")@@ -105,7 +105,7 @@ def test_import_roto_cae_en_fase_import():rec = _by_name(report)["broken_import"]assert rec.status == "failed"assert rec.phase == "import"- # El reporte guarda SOLO el mensaje corto (una línea, sin rutas ni traceback).+ # The report stores ONLY the short message (a single line, without paths or traceback).assert rec.error and "\n" not in rec.error@@ -131,7 +131,7 @@ def test_register_que_lanza_revierte_tools_nit8():rec = _by_name(report)["raises_register"]assert rec.status == "failed"assert rec.phase == "register"- # NIT-8: la tool parcial 'partial_tool' se revirtió vía _tool_manager.remove_tool.+ # NIT-8: the partial tool 'partial_tool' was rolled back via _tool_manager.remove_tool.assert "partial_tool" in mcp._tool_manager.removedassert "partial_tool" not in mcp._tool_manager._names@@ -143,7 +143,7 @@ def test_sys_path_restaurado_tras_la_pasada():def test_nombre_invalido_cae_en_fase_name(tmp_path):- # Un nombre de dir inválido se crea en caliente (no portable como fixture versionado).+ # An invalid dir name is created on the fly (not portable as a versioned fixture).bad = tmp_path / "bad name!"bad.mkdir()(bad / "plugin.py").write_text("PLUGIN_API = 1\n\ndef register(ctx):\n pass\n", encoding="utf-8")@@ -156,4 +156,4 @@ def test_nombre_invalido_cae_en_fase_name(tmp_path):def test_last_report_asignado_tras_pasada_no_vacia():report = plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))assert plugin_loader.LAST_REPORT is report- assert report.plugins # hubo candidatos+ assert report.plugins # there were candidatesdiff --git a/docker/kali/tests/test_server_info.py b/docker/kali/tests/test_server_info.pyindex 1027eb7..12b6133 100644--- a/docker/kali/tests/test_server_info.py+++ b/docker/kali/tests/test_server_info.py@@ -1,14 +1,15 @@-"""Tests de FORMA del cableado de `server_info` y del cargador de plugins.+"""SHAPE tests of the `server_info` wiring and of the plugin loader.-Restricción del entorno (igual que ``test_server_recon_tools``): ``kali_mcp_server.py``-exige ``mcp<2`` (FastMCP 1.x) y en el venv dev no está, así que NO se importa el servidor:-se inspecciona su TEXTO fuente. Aquí se fija que ``server_info``:- - deriva ``tools`` por INTROSPECCIÓN síncrona (``mcp._tool_manager.list_tools()``), no de- una lista estática;- - ya NO contiene la antigua lista estática de 15 nombres de tool;- - añade un bloque ``plugins`` leído del reporte del cargador;-y que ``plugin_loader.load_plugins`` se invoca SOLO dentro del guard ``__main__`` (HIGH-1),-nunca a nivel de módulo (correría en cada import y en los tests sin SDK).+Environment constraint (like ``test_server_recon_tools``): ``kali_mcp_server.py`` requires+``mcp<2`` (FastMCP 1.x) and it is not in the dev venv, so the server is NOT imported: its+source TEXT is inspected. Here it is pinned that ``server_info``:+ - derives ``tools`` by synchronous INTROSPECTION (``mcp._tool_manager.list_tools()``), not+ from a static list;+ - no longer contains the old static list of 15 tool names;+ - adds a ``plugins`` block read from the loader's report;+and that ``plugin_loader.load_plugins`` is invoked ONLY inside the ``__main__`` guard+(HIGH-1), never at module level (it would run on every import and in the tests without the+SDK)."""from __future__ import annotations@@ -24,16 +25,16 @@ def _source() -> str:def test_tools_por_introspeccion_sincrona():source = _source()- # Deriva de la API interna SÍNCRONA del tool manager.+ # Derives from the tool manager's SYNCHRONOUS internal API.assert "mcp._tool_manager.list_tools()" in source- # NO usa el FastMCP.list_tools público (async): no debe aparecer como `mcp.list_tools(`.+ # Does NOT use the public FastMCP.list_tools (async): must not appear as `mcp.list_tools(`.assert "mcp.list_tools(" not in sourcedef test_lista_estatica_de_15_nombres_eliminada():source = _source()- # La vieja lista estática enumeraba estas constantes como elementos de `tools`- # (con coma final). Esa forma ya no debe existir en ningún sitio del servidor.+ # The old static list enumerated these constants as elements of `tools`+ # (with a trailing comma). That form must no longer exist anywhere in the server.for const in ("START_COLLECTION_TOOL_NAME,","SCAN_STATUS_TOOL_NAME,",@@ -49,14 +50,14 @@ def test_lista_estatica_de_15_nombres_eliminada():"WEBTECH_SCAN_TOOL_NAME,",):assert const not in source, f"la lista estática aún referencia {const!r}"- # El marcador textual de la vieja lista inline (`"server_info",` como elemento) tampoco.+ # The textual marker of the old inline list (`"server_info",` as an element) neither.assert '"server_info",' not in sourcedef test_bloque_plugins_en_server_info():source = _source()assert '"plugins": _plugins_block()' in source- # El bloque usa el esquema cerrado leído de LAST_REPORT.+ # The block uses the closed schema read from LAST_REPORT.assert "plugin_loader.LAST_REPORT" in source or "LAST_REPORT" in source@@ -64,11 +65,11 @@ def test_load_plugins_bajo_guard_main_y_no_a_nivel_modulo():source = _source()assert 'if __name__ == "__main__":' in sourceguard_idx = source.index('if __name__ == "__main__":')- # La invocación debe existir y estar DESPUÉS del guard (dentro del bloque __main__).+ # The invocation must exist and be AFTER the guard (inside the __main__ block).call = "plugin_loader.load_plugins("assert call in sourceassert source.index(call) > guard_idx, "load_plugins no está bajo el guard __main__"- # Y no debe haber una invocación a nivel de módulo (antes del guard).+ # And there must be no invocation at module level (before the guard).assert (source[:guard_idx].find(call) == -1), "load_plugins se invoca a nivel de módulo"diff --git a/docs/plugins/developing-plugins.md b/docs/plugins/developing-plugins.mdindex 60ad688..c91deb9 100644--- a/docs/plugins/developing-plugins.md+++ b/docs/plugins/developing-plugins.md@@ -1,11 +1,11 @@-# Escribir un plugin de kali-mcp+# Writing a kali-mcp plugin-Guía para autores de plugins. Para el detalle del descubrimiento/carga y de las dos rutas-del árbol `plugins/`, consulta [discovery.md](discovery.md).+Guide for plugin authors. For the details of discovery/loading and the two paths of the+`plugins/` tree, see [discovery.md](discovery.md).-## Estructura de un plugin+## Structure of a plugin-Un plugin es un **subdirectorio inmediato** de `plugins/` con, al menos, un `plugin.py`:+A plugin is an **immediate subdirectory** of `plugins/` with, at minimum, a `plugin.py`:```plugins/@@ -17,19 +17,19 @@ plugins/README.md # recomendado```-`plugin.py` debe exponer:+`plugin.py` must expose:-- `PLUGIN_API = 1` — versión del contrato que el plugin implementa. El cargador exige- **igualdad exacta** con `plugin_api.SUPPORTED_PLUGIN_API`; si no casan, el plugin se- rechaza en fase `api`.-- `PLUGIN_NAME = "mi-plugin"` — nombre del plugin (para logs y `server_info`).-- `register(ctx)` — función que recibe un `PluginContext` y declara tools, skill y- volúmenes a través de él.+- `PLUGIN_API = 1` — version of the contract that the plugin implements. The loader+ requires **exact equality** with `plugin_api.SUPPORTED_PLUGIN_API`; if they do not match,+ the plugin is rejected in phase `api`.+- `PLUGIN_NAME = "mi-plugin"` — name of the plugin (for logs and `server_info`).+- `register(ctx)` — function that receives a `PluginContext` and declares tools, skill, and+ volumes through it.## `register(ctx)`-Es el **único punto** por el que el plugin toca el servidor. Recibe un `PluginContext` ya-configurado para el directorio del plugin. Ejemplo mínimo:+It is the **only point** through which the plugin touches the server. It receives a+`PluginContext` already configured for the plugin's directory. Minimal example:```pythonfrom __future__ import annotations@@ -48,89 +48,92 @@ def register(ctx):ctx.needs_volume("kali-artifacts")```-El plugin de ejemplo `plugins/example-hello.disabled/` demuestra el contrato completo y-sirve de plantilla.--## API de `PluginContext`--Firmas fijas, versionadas con `PLUGIN_API = 1`:--- `ctx.tool(*args, **kwargs)` — **decorador de tool con detección de colisión**. Resuelve el- nombre objetivo (kwarg `name=` o `fn.__name__`) y consulta las tools ya registradas. Si el- nombre ya existe, **no** delega: anota la colisión (el plugin queda `degraded`) y devuelve- la función intacta. Si no existe, delega literalmente en `mcp.tool(*a, **k)` y anota el- nombre. Si no puede obtener la lista fiable de nombres, el registro **falla** (no delega a- ciegas).-- `ctx.skill(path)` — declara la **única** skill del plugin (ruta relativa al directorio del- plugin). Valida con `realpath` que la ruta resuelta queda **bajo** el directorio del- plugin; si escapa, se ignora con un warning no fatal. Una segunda llamada es un error de- contrato (máximo una skill): se ignora.-- `ctx.needs_volume(name)` — **solo anota** que el plugin necesita un volumen. **No monta ni- habilita nada**; es declarativo para `server_info`.-- `ctx.plugin_dir()` — ruta absoluta del directorio del plugin (siempre devuelve ruta,- exista o no).-- `ctx.vendor_dir()` — ruta absoluta de `<plugin_dir>/vendor` (siempre devuelve ruta, exista- o no). **Contrato**: devuelve la ruta a `vendor/`; tú decides si existe y si la insertas en- `sys.path`. No crea el directorio ni verifica su contenido.--## Regla de PREFIJAR módulos (sombra en `sys.modules`)--El cargador importa cada `plugin.py` bajo un nombre namespaced (`vuln_plugin_<dir>`) e-inserta el directorio del plugin en `sys.path` **solo** mientras ejecuta su cuerpo, para que-`import <hermano>` resuelva contra el propio directorio del plugin.--Aun así, los módulos hermanos que importes (y cualquier dependencia de `vendor/`) entran en-`sys.modules` por su **nombre tal cual**. Si dos plugins (o un plugin y el core) usan el-mismo nombre de módulo, el segundo **sombrea** al primero en `sys.modules`. Para evitarlo,-**prefija** los nombres de tus módulos y paquetes vendorizados con algo propio del plugin-(p. ej. `miplugin_utils` en vez de `utils`). No asumas que tu `utils` es el que se importa.--## La skill = nombre del directorio--La skill del plugin se copia al perfil de Hermes bajo un directorio **con el nombre del-plugin** (el nombre de su directorio). Es el bucle de skills del `command` de `ooda-agent`-en `docker-compose.yml` quien hace la copia desde el bind-mount `/opt/plugins`. Nombra el-directorio del plugin con cuidado: es también el nombre de su skill en Hermes.--## Cómo entregar `vendor/` y `skill/`--- **`vendor/`**: empaqueta aquí las dependencias de terceros del plugin. Si necesitas que- Python las encuentre, inserta `ctx.vendor_dir()` en `sys.path` **dentro de `register`** y- recuerda la regla de prefijos. `vendor_dir()` no añade nada por sí solo.-- **`skill/`**: deja aquí el `SKILL.md` (y recursos) de la skill. Declárala con- `ctx.skill(path="skill")`. Se copia a Hermes como se describe arriba; recuerda que esa capa- es **viva** (bind-mount) y solo necesita reinicio de `ooda-agent`, mientras que las tools- viajan en la imagen **congelada** de la Kali y necesitan rebuild (ver+The example plugin `plugins/example-hello.disabled/` demonstrates the full contract and+serves as a template.++## `PluginContext` API++Fixed signatures, versioned with `PLUGIN_API = 1`:++- `ctx.tool(*args, **kwargs)` — **tool decorator with collision detection**. It resolves+ the target name (kwarg `name=` or `fn.__name__`) and queries the already-registered+ tools. If the name already exists, it does **not** delegate: it records the collision (the+ plugin ends up `degraded`) and returns the function untouched. If it does not exist, it+ delegates literally to `mcp.tool(*a, **k)` and records the name. If it cannot obtain the+ reliable list of names, the registration **fails** (it does not delegate blindly).+- `ctx.skill(path)` — declares the **single** skill of the plugin (path relative to the+ plugin's directory). It validates with `realpath` that the resolved path stays **under**+ the plugin's directory; if it escapes, it is ignored with a non-fatal warning. A second+ call is a contract error (at most one skill): it is ignored.+- `ctx.needs_volume(name)` — **only annotates** that the plugin needs a volume. It **does+ not mount or enable anything**; it is declarative for `server_info`.+- `ctx.plugin_dir()` — absolute path of the plugin's directory (always returns a path,+ whether it exists or not).+- `ctx.vendor_dir()` — absolute path of `<plugin_dir>/vendor` (always returns a path,+ whether it exists or not). **Contract**: it returns the path to `vendor/`; you decide+ whether it exists and whether to insert it into `sys.path`. It does not create the+ directory or verify its contents.++## Rule for PREFIXING modules (shadow in `sys.modules`)++The loader imports each `plugin.py` under a namespaced name (`vuln_plugin_<dir>`) and+inserts the plugin's directory into `sys.path` **only** while running its body, so that+`import <sibling>` resolves against the plugin's own directory.++Even so, the sibling modules you import (and any `vendor/` dependency) enter `sys.modules`+under their **name as is**. If two plugins (or a plugin and the core) use the same module+name, the second **shadows** the first in `sys.modules`. To avoid this, **prefix** the+names of your vendored modules and packages with something specific to the plugin (e.g.+`miplugin_utils` instead of `utils`). Do not assume that your `utils` is the one that gets+imported.++## The skill = directory name++The plugin's skill is copied into the Hermes profile under a directory **with the plugin's+name** (its directory name). It is the skills loop of the `ooda-agent` `command` in+`docker-compose.yml` that does the copy from the `/opt/plugins` bind-mount. Name the+plugin's directory carefully: it is also the name of its skill in Hermes.++## How to ship `vendor/` and `skill/`++- **`vendor/`**: package the plugin's third-party dependencies here. If you need Python to+ find them, insert `ctx.vendor_dir()` into `sys.path` **inside `register`** and remember+ the prefix rule. `vendor_dir()` does not add anything on its own.+- **`skill/`**: leave the skill's `SKILL.md` (and resources) here. Declare it with+ `ctx.skill(path="skill")`. It is copied to Hermes as described above; remember that this+ layer is **live** (bind-mount) and only needs a restart of `ooda-agent`, whereas the tools+ travel in the Kali's **frozen** image and need a rebuild (see[discovery.md](discovery.md)).-## Postura de seguridad (NIT-7)+## Security posture (NIT-7)-El código de un plugin se ejecuta con **confianza plena**: corre en el **mismo proceso** del-servidor kali-mcp, con sus mismos privilegios, **sin sandbox** y **sin aislamiento** entre-el plugin y el servidor. Un plugin puede hacer lo que haga el core.+A plugin's code runs with **full trust**: it runs in the **same process** as the kali-mcp+server, with its same privileges, **without a sandbox** and **without isolation** between+the plugin and the server. A plugin can do whatever the core does.-Además, el perfil de Hermes **ya no hace whitelist** de las tools de la Kali (se retiró-`mcp_servers.kali.tools.include` de `agent-ooda/profile/config.yaml`): el **servidor MCP es-la fuente de verdad** y lo que el servidor expone es lo que Hermes ve. Por tanto, una tool-aportada por un plugin de terceros entra en la superficie de Hermes **sin pasar por un-gate**. Instala únicamente plugins de **origen conocido y revisado**.+In addition, the Hermes profile **no longer whitelists** the Kali's tools+(`mcp_servers.kali.tools.include` was removed from `agent-ooda/profile/config.yaml`): the+**MCP server is the source of truth** and what the server exposes is what Hermes sees.+Therefore, a tool contributed by a third-party plugin enters Hermes's surface **without+passing through a gate**. Only install plugins of **known and reviewed origin**.-Si quisieras volver a revisar tool por tool, la vía es **reañadir manualmente** una-`include:` con la whitelist exacta de nombres (tal como los expone el servidor) bajo-`mcp_servers.kali.tools` en el `config.yaml`. No está puesta por defecto.+If you wanted to review tool by tool again, the way is to **manually re-add** an+`include:` with the exact whitelist of names (as the server exposes them) under+`mcp_servers.kali.tools` in the `config.yaml`. It is not set by default.-## `.disabled` como constante única (NIT-6)+## `.disabled` as a single constant (NIT-6)-El sufijo que apaga un plugin es `.disabled`, definido **una sola vez** en el código Python-como `plugin_api.DISABLED_SUFFIX`. Lo comparten el cargador (capa de tools) y el bucle de-skills del compose (capa de Hermes), y un test de paridad fija que no diverjan. Para apagar-un plugin, renombra su directorio añadiendo `.disabled`; para encenderlo, quítalo.+The suffix that turns off a plugin is `.disabled`, defined **only once** in the Python code+as `plugin_api.DISABLED_SUFFIX`. It is shared by the loader (tools layer) and the compose+skills loop (Hermes layer), and a parity test pins that they do not diverge. To turn off a+plugin, rename its directory by adding `.disabled`; to turn it on, remove it.-## Cómo testear con un `ctx` doble+## How to test with a double `ctx`-Los tests del core **no** importan el SDK `mcp` ni el servidor: usan un **doble** de `mcp`-que imita la parte de la API interna de FastMCP que `PluginContext` toca —`mcp.tool(*a, **k)`-(decorador) y `mcp._tool_manager.list_tools()` (nombres existentes)—. Sigue el mismo patrón-para tu plugin: construye un `PluginContext` con ese doble y llama a tu `register(ctx)`,-luego afirma sobre `ctx.tools`, `ctx.skill_path`, `ctx.volumes` y `ctx.collisions`.-Consulta `docker/kali/tests/test_plugin_api.py` y `test_example_hello.py` como ejemplos.+The core tests do **not** import the `mcp` SDK nor the server: they use a **double** of+`mcp` that mimics the part of FastMCP's internal API that `PluginContext` touches —+`mcp.tool(*a, **k)` (decorator) and `mcp._tool_manager.list_tools()` (existing names). Follow+the same pattern for your plugin: build a `PluginContext` with that double and call your+`register(ctx)`, then assert on `ctx.tools`, `ctx.skill_path`, `ctx.volumes`, and+`ctx.collisions`. See `docker/kali/tests/test_plugin_api.py` and `test_example_hello.py` as+examples.diff --git a/docs/plugins/discovery.md b/docs/plugins/discovery.mdindex cc07b44..ab81379 100644--- a/docs/plugins/discovery.md+++ b/docs/plugins/discovery.md@@ -1,107 +1,110 @@-# Descubrimiento y carga de plugins+# Plugin discovery and loading-Este documento describe **cómo** el servidor kali-mcp descubre y carga los plugins, y las-**dos rutas** por las que el árbol `plugins/` entra en el stack. Para escribir un plugin,-consulta [developing-plugins.md](developing-plugins.md).+This document describes **how** the kali-mcp server discovers and loads plugins, and the+**two paths** by which the `plugins/` tree enters the stack. To write a plugin, see+[developing-plugins.md](developing-plugins.md).-## Cuándo se cargan+## When they are loaded-La carga ocurre **una sola vez, en el arranque del servidor**, dentro del guard-`if __name__ == "__main__":` de `docker/kali/kali_mcp_server.py`, ANTES de abrir ningún-plano (datos ni control). Nunca se invoca a nivel de módulo: así `load_plugins` no corre en-cada `import` del servidor ni en los tests (que no tienen el SDK `mcp`). La llamada es:+Loading happens **only once, at server startup**, inside the+`if __name__ == "__main__":` guard of `docker/kali/kali_mcp_server.py`, BEFORE opening any+plane (data or control). It is never invoked at module level: that way `load_plugins` does+not run on every `import` of the server nor in the tests (which do not have the `mcp` SDK).+The call is:```pythonplugin_loader.load_plugins(mcp, os.environ.get("PLUGINS_DIR", "plugins"))```-Es decir, la raíz de plugins por defecto es `plugins` **relativa al WORKDIR**-(`/opt/kali-mcp/plugins` dentro de la imagen), configurable con la variable de entorno-`PLUGINS_DIR`.--## Orden de descubrimiento--El cargador enumera los **subdirectorios inmediatos** de la raíz de plugins en **orden-alfabético determinista** (`sorted(os.listdir(...))`). Un directorio es candidato solo si:--- no empieza por `.` (ocultos ignorados);-- no termina en `.disabled` (ver abajo);-- es un directorio;-- contiene un fichero `plugin.py`.--El orden alfabético es estable entre arranques: dos plugins que registren tools en un orden-reproducible verán siempre la misma secuencia.--## El sufijo `.disabled`--Un directorio cuyo nombre termina en `.disabled` se **ignora por completo**. El sufijo es-una **constante única** en el código Python: `plugin_api.DISABLED_SUFFIX = ".disabled"`-(NIT-6). Esa MISMA cadena la comparte el bucle de skills de plugins del `command` de-`ooda-agent` en `docker-compose.yml`, que salta los directorios `*.disabled` antes de-copiar su skill. El test `docker/kali/tests/test_disabled_parity.py` fija que ambas capas-usan el mismo sufijo, de modo que no pueden divergir (un plugin nunca queda "apagado en una-capa y vivo en la otra").--Para activar un plugin entregado deshabilitado, se quita el sufijo del nombre del-directorio; para volver a apagarlo, se reañade. (El impacto de un rename sobre cada ruta se-detalla en «Las dos rutas» más abajo.)--## Errores no fatales (aislamiento)--Cada plugin se procesa dentro de su propio `try/except`: **un plugin roto no tumba a los-demás ni al arranque del servidor**. El cargador aplica un micro-algoritmo por fases y, en-cada fallo, registra hasta dónde llegó sin propagar la excepción:--- `name` — el nombre del directorio no casa el regex permitido.-- `import` — el cuerpo de `plugin.py` (o un `import` de un módulo hermano) lanzó.-- `api` — el `PLUGIN_API` del plugin no es compatible (se exige igualdad exacta con- `SUPPORTED_PLUGIN_API`).-- `register-missing` — el plugin no expone un `register(ctx)` invocable.-- `register` — `register(ctx)` lanzó durante su ejecución.--El traceback completo va a stdout/stderr; el reporte solo guarda `str(exc)` (una línea).--## Reversión en fallo de `register` (NIT-8)--Si `register(ctx)` lanza **después** de haber registrado una o más tools, el cargador-**revierte** esas tools ya montadas (`mcp._tool_manager.remove_tool(name)`, best-effort)-para no dejar tools huérfanas visibles de un plugin que falló a medias. El plugin se reporta-como `failed` en fase `register`.--## Introspección síncrona y esquema `server_info['plugins']`--`server_info` **no** lleva una lista estática de plugins: lee el singleton de módulo-`plugin_loader.LAST_REPORT`, que `load_plugins` publica al terminar su pasada (HIGH-1). La-introspección es **síncrona**: el reporte ya está calculado en el arranque, así que-`server_info` solo lo clasifica. Si nunca se cargaron plugins (p. ej. en un `import` suelto-del módulo), `LAST_REPORT` arranca vacío y el bloque es coherente y vacío — comportamiento-idéntico al de hoy.--El bloque `plugins` de `server_info` tiene un **esquema cerrado** derivado del reporte: por-cada plugin descubierto se expone su nombre, su `status` (`loaded` / `degraded` / `failed`),-la fase alcanzada, las tools que registró, la skill declarada, los volúmenes anotados y las-colisiones detectadas.--## Las dos rutas del árbol `plugins/` (NIT-5)--El mismo árbol versionado `plugins/` del repo entra en el stack por **dos rutas-DISTINTAS**, que **no son la misma y no deben unificarse**:--1. **Congelada en la imagen de Kali — `/opt/kali-mcp/plugins`.**- El `Dockerfile` hace `COPY plugins/ ./plugins/` (sobre el WORKDIR `/opt/kali-mcp`). Es la- ruta que lee `load_plugins` para descubrir y cargar las **tools** del plugin en el- servidor kali-mcp. Al copiarse en **build**, queda **congelada**: activar o desactivar un- plugin (añadirlo, quitarlo o renombrar su `.disabled`) exige **reconstruir la imagen de- Kali** para que el cambio tenga efecto en las tools.--2. **Viva por bind-mount en Hermes — `/opt/plugins`.**- `docker-compose.yml` monta `./plugins:/opt/plugins:ro` en el contenedor `ooda-agent`. El- `command` de ese servicio recorre esa ruta y copia la `skill/` de cada plugin a la carpeta- de skills del perfil de Hermes. Al ser un bind-mount **vivo**, basta un **reinicio de- `ooda-agent`** (sin rebuild) para que la **skill** de un plugin se recoja o deje de- recogerse.--Consecuencia práctica: la capa de **tools** (Kali, congelada) y la capa de **skills**-(Hermes, viva) se activan por mecanismos diferentes. No unifiques las rutas ni asumas que un-solo cambio basta para ambas: una tool nueva necesita rebuild de la Kali, y una skill nueva-necesita reinicio de `ooda-agent`.+That is, the default plugins root is `plugins` **relative to the WORKDIR**+(`/opt/kali-mcp/plugins` inside the image), configurable with the `PLUGINS_DIR` environment+variable.++## Discovery order++The loader enumerates the **immediate subdirectories** of the plugins root in+**deterministic alphabetical order** (`sorted(os.listdir(...))`). A directory is a+candidate only if:++- it does not start with `.` (hidden ones are ignored);+- it does not end in `.disabled` (see below);+- it is a directory;+- it contains a `plugin.py` file.++The alphabetical order is stable across startups: two plugins that register tools in a+reproducible order will always see the same sequence.++## The `.disabled` suffix++A directory whose name ends in `.disabled` is **ignored entirely**. The suffix is a+**single constant** in the Python code: `plugin_api.DISABLED_SUFFIX = ".disabled"`+(NIT-6). That SAME string is shared by the plugin skills loop in the `ooda-agent` `command`+in `docker-compose.yml`, which skips `*.disabled` directories before copying their skill.+The `docker/kali/tests/test_disabled_parity.py` test pins that both layers use the same+suffix, so they cannot diverge (a plugin never ends up "off in one layer and alive in the+other").++To activate a plugin shipped disabled, remove the suffix from the directory name; to turn+it off again, add it back. (The impact of a rename on each path is detailed in "The two+paths" below.)++## Non-fatal errors (isolation)++Each plugin is processed inside its own `try/except`: **a broken plugin does not take down+the others or the server startup**. The loader applies a phased micro-algorithm and, on+each failure, records how far it got without propagating the exception:++- `name` — the directory name does not match the allowed regex.+- `import` — the body of `plugin.py` (or an `import` of a sibling module) raised.+- `api` — the plugin's `PLUGIN_API` is not compatible (exact equality with+ `SUPPORTED_PLUGIN_API` is required).+- `register-missing` — the plugin does not expose a callable `register(ctx)`.+- `register` — `register(ctx)` raised during its execution.++The full traceback goes to stdout/stderr; the report only stores `str(exc)` (a single+line).++## Rollback on `register` failure (NIT-8)++If `register(ctx)` raises **after** having registered one or more tools, the loader+**rolls back** those already-mounted tools (`mcp._tool_manager.remove_tool(name)`,+best-effort) so as not to leave orphan tools visible from a plugin that failed halfway. The+plugin is reported as `failed` in phase `register`.++## Synchronous introspection and the `server_info['plugins']` schema++`server_info` does **not** carry a static list of plugins: it reads the module singleton+`plugin_loader.LAST_REPORT`, which `load_plugins` publishes when its pass finishes (HIGH-1).+The introspection is **synchronous**: the report is already computed at startup, so+`server_info` only classifies it. If plugins were never loaded (e.g. in a bare `import` of+the module), `LAST_REPORT` starts empty and the block is coherent and empty — behavior+identical to today's.++The `plugins` block of `server_info` has a **closed schema** derived from the report: for+each discovered plugin it exposes its name, its `status` (`loaded` / `degraded` / `failed`),+the phase reached, the tools it registered, the declared skill, the annotated volumes, and+the detected collisions.++## The two paths of the `plugins/` tree (NIT-5)++The same versioned `plugins/` tree from the repo enters the stack through **two DIFFERENT+paths**, which **are not the same and must not be unified**:++1. **Frozen in the Kali image — `/opt/kali-mcp/plugins`.**+ The `Dockerfile` runs `COPY plugins/ ./plugins/` (onto the WORKDIR `/opt/kali-mcp`). It+ is the path that `load_plugins` reads to discover and load the plugin's **tools** in the+ kali-mcp server. Being copied at **build** time, it is **frozen**: enabling or disabling+ a plugin (adding it, removing it, or renaming its `.disabled`) requires **rebuilding the+ Kali image** for the change to take effect on the tools.++2. **Live by bind-mount in Hermes — `/opt/plugins`.**+ `docker-compose.yml` mounts `./plugins:/opt/plugins:ro` into the `ooda-agent` container.+ That service's `command` walks that path and copies each plugin's `skill/` into the+ Hermes profile's skills folder. Being a **live** bind-mount, a **restart of+ `ooda-agent`** (without a rebuild) is enough for a plugin's **skill** to be picked up or+ dropped.++Practical consequence: the **tools** layer (Kali, frozen) and the **skills** layer (Hermes,+live) are activated by different mechanisms. Do not unify the paths or assume that a single+change is enough for both: a new tool needs a rebuild of the Kali, and a new skill needs a+restart of `ooda-agent`.diff --git a/plugins/README.md b/plugins/README.mdindex 33bc074..be046f4 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -1,47 +1,46 @@# plugins/-Árbol versionado de plugins del servidor kali-mcp. Este directorio **siempre debe-existir** en el repo: el `Dockerfile` hace `COPY plugins/ ./plugins/` y, sin un árbol-versionado, el build fallaría. Por eso este `README.md` lo mantiene presente aunque no-haya ningún plugin activo.+Versioned tree of kali-mcp server plugins. This directory **must always exist** in the+repo: the `Dockerfile` runs `COPY plugins/ ./plugins/`, and without a versioned tree the+build would fail. That is why this `README.md` keeps it present even when there is no+active plugin.-## Qué es un plugin+## What a plugin is-Un plugin es un subdirectorio inmediato de `plugins/` con, al menos, un `plugin.py` que-expone:+A plugin is an immediate subdirectory of `plugins/` with, at minimum, a `plugin.py` that+exposes:-- `PLUGIN_API = 1` — versión del contrato que el plugin implementa.-- `PLUGIN_NAME = "<nombre>"` — nombre del plugin.-- `register(ctx)` — función que recibe un `PluginContext` y declara tools, skill y- volúmenes a través de él.+- `PLUGIN_API = 1` — version of the contract that the plugin implements.+- `PLUGIN_NAME = "<name>"` — name of the plugin.+- `register(ctx)` — function that receives a `PluginContext` and declares tools, skill, and+ volumes through it.-El cargador descubre los subdirectorios en orden alfabético y, por cada uno con-`plugin.py`, ejecuta su `register(ctx)`. Consulta `docs/plugins/` para el detalle del-contrato y del descubrimiento.+The loader discovers the subdirectories in alphabetical order and, for each one with a+`plugin.py`, runs its `register(ctx)`. See `docs/plugins/` for the details of the contract+and discovery.-## Postura de confianza+## Trust posture-El código de un plugin se ejecuta **con la misma confianza que el core**: corre en el-mismo proceso del servidor, con sus mismos privilegios, sin sandbox. Añade aquí solo-plugins de origen conocido y revisado. No hay aislamiento entre un plugin y el servidor.+A plugin's code runs **with the same trust as the core**: it runs in the same server+process, with its same privileges, without a sandbox. Only add plugins of known and+reviewed origin here. There is no isolation between a plugin and the server.-## Habilitar / deshabilitar un plugin+## Enable / disable a plugin-Un directorio cuyo nombre termina en `.disabled` se **ignora** por completo (ni el-cargador ni el resto del sistema lo montan). Para activar un plugin entregado-deshabilitado, **renombra el directorio quitando el sufijo `.disabled`**:+A directory whose name ends in `.disabled` is **ignored** entirely (neither the loader nor+the rest of the system mounts it). To activate a plugin shipped disabled, **rename the+directory by removing the `.disabled` suffix**:```shmv plugins/example-hello.disabled plugins/example-hello```-Para deshabilitarlo de nuevo, vuelve a añadir el sufijo. Tras activar o desactivar un-plugin hay que reconstruir la imagen de Kali (el árbol `plugins/` se copia en build);-consulta el `README.md` del propio plugin de ejemplo para el recordatorio completo.+To disable it again, add the suffix back. After enabling or disabling a plugin you must+rebuild the Kali image (the `plugins/` tree is copied at build time); see the example+plugin's own `README.md` for the full reminder.-## Ejemplo entregado+## Shipped example-`example-hello.disabled/` es un plugin de ejemplo entregado **deshabilitado**. Demuestra-el contrato completo (una tool inocua, una skill y la declaración de un volumen) sin-cambiar el comportamiento por defecto del servidor. Léelo como plantilla para escribir-plugins propios.+`example-hello.disabled/` is an example plugin shipped **disabled**. It demonstrates the+full contract (a harmless tool, a skill, and a volume declaration) without changing the+server's default behavior. Read it as a template for writing your own plugins.diff --git a/plugins/example-hello.disabled/README.md b/plugins/example-hello.disabled/README.mdindex c900032..c156516 100644--- a/plugins/example-hello.disabled/README.md+++ b/plugins/example-hello.disabled/README.md@@ -1,30 +1,30 @@-# example-hello (plugin de ejemplo, entregado DESHABILITADO)+# example-hello (example plugin, shipped DISABLED)-Plugin de ejemplo que demuestra el contrato de plugins de kali-mcp de principio a fin:+Example plugin that demonstrates the kali-mcp plugin contract end to end:-- Registra la tool **`hello`**, inocua: devuelve `{"status": "done", "greeting":- "hello, <name>"}` y no toca red, filesystem ni target.-- Declara una **skill** (`skill/SKILL.md`).-- Declara (solo anota) que necesita el volumen **`kali-artifacts`**.+- Registers the **`hello`** tool, which is harmless: it returns `{"status": "done", "greeting":+ "hello, <name>"}` and does not touch the network, filesystem, or target.+- Declares a **skill** (`skill/SKILL.md`).+- Declares (only annotates) that it needs the **`kali-artifacts`** volume.-Se entrega dentro de un directorio terminado en `.disabled`, por lo que **por defecto no-se carga**: ni el cargador de plugins ni el bucle de skills lo montan. El comportamiento-del servidor es idéntico a no tener este plugin.+It ships inside a directory ending in `.disabled`, so **by default it is not loaded**:+neither the plugin loader nor the skills loop mounts it. The server behavior is identical+to not having this plugin.-## Cómo activarlo+## How to enable it-Renombra el directorio quitando el sufijo `.disabled`:+Rename the directory by removing the `.disabled` suffix:```shmv plugins/example-hello.disabled plugins/example-hello```-Para deshabilitarlo de nuevo, vuelve a añadir el sufijo.+To disable it again, add the suffix back.-## Importante tras activar/desactivar+## Important after enabling/disabling-El árbol `plugins/` se copia dentro de la imagen de Kali en **tiempo de build**, de modo-que para que un cambio de activación surta efecto hay que **reconstruir la imagen de-Kali**. El contenedor del agente (ooda-agent) monta el árbol y recarga las skills al-**reiniciarse**. El detalle de este flujo (bind-mount `./plugins:/opt/plugins:ro` y el-bucle de skills) se documenta junto a la integración de runtime.+The `plugins/` tree is copied into the Kali image at **build time**, so for an enable+change to take effect you must **rebuild the Kali image**. The agent container (ooda-agent)+mounts the tree and reloads the skills when it **restarts**. The details of this flow (the+`./plugins:/opt/plugins:ro` bind-mount and the skills loop) are documented alongside the+runtime integration.diff --git a/plugins/example-hello.disabled/plugin.py b/plugins/example-hello.disabled/plugin.pyindex 4114c68..fc60c50 100644--- a/plugins/example-hello.disabled/plugin.py+++ b/plugins/example-hello.disabled/plugin.py@@ -1,39 +1,40 @@-"""Plugin de EJEMPLO entregado DESHABILITADO (directorio ``*.disabled``).+"""EXAMPLE plugin shipped DISABLED (``*.disabled`` directory).-Demuestra el contrato completo de ``PluginContext`` sin cambiar el comportamiento del-servidor: al vivir en un directorio ``.disabled`` ni el cargador ni el bucle de skills lo-montan, así que el default es idéntico a hoy. Para activarlo, renombra el directorio-quitando el sufijo ``.disabled`` (ver ``README.md`` de este plugin).+It demonstrates the full ``PluginContext`` contract without changing the server's behavior:+by living in a ``.disabled`` directory, neither the loader nor the skills loop mounts it, so+the default is identical to today. To activate it, rename the directory by removing the+``.disabled`` suffix (see this plugin's ``README.md``).-Registra una tool INOCUA (``hello``) que no toca red, filesystem ni target: solo devuelve-un saludo. Además declara una skill y un volumen para ejercitar el contrato entero.+It registers a HARMLESS tool (``hello``) that does not touch the network, filesystem, or+target: it only returns a greeting. It also declares a skill and a volume to exercise the+entire contract."""from __future__ import annotations-# Versión del contrato de plugin que este ejemplo implementa (debe casar con-# ``plugin_api.SUPPORTED_PLUGIN_API`` del core).+# Version of the plugin contract that this example implements (must match the core's+# ``plugin_api.SUPPORTED_PLUGIN_API``).PLUGIN_API = 1-# Nombre del plugin, usado por el cargador y por ``server_info``.+# Name of the plugin, used by the loader and by ``server_info``.PLUGIN_NAME = "example-hello"def register(ctx):- """Declara la tool, la skill y el volumen del plugin a través del ``ctx``.+ """Declares the plugin's tool, skill, and volume through ``ctx``.- ``ctx`` es un ``PluginContext``: ``ctx.tool`` es un decorador con detección de- colisión; ``ctx.skill`` declara la (única) skill; ``ctx.needs_volume`` anota un- volumen (solo declarativo).+ ``ctx`` is a ``PluginContext``: ``ctx.tool`` is a decorator with collision detection;+ ``ctx.skill`` declares the (single) skill; ``ctx.needs_volume`` annotates a volume (only+ declarative)."""@ctx.tool()def hello(name: str = "world") -> dict:- """Tool de ejemplo INOCUA: devuelve un saludo, sin efectos secundarios."""+ """HARMLESS example tool: returns a greeting, with no side effects."""return {"status": "done", "greeting": f"hello, {name}"}- # Declara la skill de ejemplo (directorio ``skill/`` relativo a este plugin).+ # Declares the example skill (``skill/`` directory relative to this plugin).ctx.skill(path="skill")- # Declara (solo anota) que el plugin usaría el volumen de artefactos de Kali.+ # Declares (only annotates) that the plugin would use the Kali artifacts volume.ctx.needs_volume("kali-artifacts")diff --git a/plugins/example-hello.disabled/skill/SKILL.md b/plugins/example-hello.disabled/skill/SKILL.mdindex f1da2bc..575abc8 100644--- a/plugins/example-hello.disabled/skill/SKILL.md+++ b/plugins/example-hello.disabled/skill/SKILL.md@@ -1,8 +1,8 @@# Skill: example-hello-Skill de ejemplo del plugin `example-hello`. Es trivial y neutral: existe solo para-demostrar que un plugin puede entregar una skill junto a su `plugin.py`.+Example skill of the `example-hello` plugin. It is trivial and neutral: it exists only to+demonstrate that a plugin can ship a skill alongside its `plugin.py`.-La tool `hello` que acompaña a esta skill devuelve un saludo inocuo y no realiza ninguna-acción sobre la red, el sistema de ficheros ni el objetivo. Úsala como punto de partida-para escribir skills propias en tus plugins.+The `hello` tool that accompanies this skill returns a harmless greeting and performs no+action on the network, the filesystem, or the target. Use it as a starting point for+writing your own skills in your plugins.