Autonomous OODA-loop pentesting agent. Hermes brain, Kali + Playwright tools over MCP, ATT&CK as the Orient language.
Python ai-agentsautonomous-agentskali-linuxllm-agentsoffensive-securityooda-looppentestingplaywrightsecurity
feat: plugin core — PluginContext and discovery loader
irraz0bf9d071c115
diff --git a/docker/kali/plugin_api.py b/docker/kali/plugin_api.pynew file mode 100644index 0000000..9f2172d--- /dev/null+++ b/docker/kali/plugin_api.py@@ -0,0 +1,178 @@+"""Contrato público del mecanismo de plugins de kali-mcp (STDLIB PURA, SIN ``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`` /+``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).+"""++from __future__ import annotations++import os+import re+from dataclasses import dataclass, field+from 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.+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.+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.+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.+PLUGIN_API = 1++# Prefijo común de los logs del subsistema de plugins (loader y contexto).+_LOG_PREFIX = "[kali-mcp][plugins]"+++@dataclass+class PluginRecord:+ """Resultado por plugin descubierto, para el reporte y ``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.+ """++ name: str+ status: str # "loaded" | "degraded" | "failed"+ phase: str+ tools: list[str] = field(default_factory=list)+ skill: str | None = None+ volumes: list[str] = field(default_factory=list)+ collisions: list[str] = field(default_factory=list)+ error: str | None = None+++@dataclass+class PluginLoadReport:+ """Reporte agregado de una pasada de ``load_plugins`` (lo lee ``server_info``)."""++ plugins: list[PluginRecord] = field(default_factory=list)++ def add(self, record: PluginRecord) -> None:+ self.plugins.append(record)+++class PluginContext:+ """Handle que el plugin recibe en ``register(ctx)``. Firmas fijas: ``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.+ """++ PLUGIN_API = PLUGIN_API++ def __init__(self, mcp: Any, plugin_dir: str) -> None:+ self._mcp = mcp+ self._plugin_dir = os.path.abspath(plugin_dir)+ self.PLUGIN_API = PLUGIN_API+ # Anotaciones recogidas por el loader tras ``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``.+ self.skill_path: str | None = None++ def _existing_tool_names(self) -> set[str]:+ """Nombres de tool ya registradas vía la API interna de FastMCP.++ 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).+ """+ tool_manager = self._mcp._tool_manager+ tools = 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.++ 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).+ """++ 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).+ self.collisions.append(name)+ print(+ f"{_LOG_PREFIX} collision: tool '{name}' ya existe; "+ "el plugin NO la registra",+ flush=True,+ )+ return fn+ decorated = self._mcp.tool(*args, **kwargs)(fn)+ self.tools.append(name)+ return decorated++ return _decorator++ def skill(self, path: str) -> None:+ """Declara la ÚNICA skill del plugin (ruta relativa al dir del plugin).++ 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.+ """+ if self.skill_path is not None:+ print(+ f"{_LOG_PREFIX} contract error: solo se admite UNA skill por plugin; "+ f"se ignora la skill adicional '{path}'",+ flush=True,+ )+ return+ resolved = os.path.realpath(os.path.join(self._plugin_dir, path))+ root = os.path.realpath(self._plugin_dir)+ if resolved != root and not resolved.startswith(root + os.sep):+ print(+ f"{_LOG_PREFIX} warning: la skill '{path}' escapa del directorio del "+ "plugin; se ignora",+ flush=True,+ )+ return+ self.skill_path = resolved++ def needs_volume(self, name: str) -> None:+ """Declara (solo anota) que el plugin necesita un volumen. NO monta nada."""+ self.volumes.append(name)++ def plugin_dir(self) -> str:+ """Ruta absoluta del directorio del plugin. SIEMPRE devuelve ruta, exista o no."""+ return self._plugin_dir++ def vendor_dir(self) -> str:+ """Ruta absoluta de ``<plugin_dir>/vendor``. SIEMPRE devuelve ruta, exista o no."""+ return os.path.join(self._plugin_dir, "vendor")diff --git a/docker/kali/plugin_loader.py b/docker/kali/plugin_loader.pynew file mode 100644index 0000000..ca0f5eb--- /dev/null+++ b/docker/kali/plugin_loader.py@@ -0,0 +1,177 @@+"""Cargador por DESCUBRIMIENTO de plugins de kali-mcp (STDLIB PURA, SIN ``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.++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.++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).+"""++from __future__ import annotations++import importlib.util+import os+import sys+import traceback++from plugin_api import (+ DISABLED_SUFFIX,+ PLUGIN_DIR_NAME_RE,+ SUPPORTED_PLUGIN_API,+ PluginContext,+ PluginLoadReport,+ PluginRecord,+)++# Prefijo de logs del subsistema de carga (tracebacks completos a 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).+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.++ 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.+ """+ candidates: list[tuple[str, str]] = []+ for name in sorted(os.listdir(plugins_root)):+ if name.startswith("."):+ continue+ if name.endswith(DISABLED_SUFFIX):+ continue+ plugin_dir = os.path.join(plugins_root, name)+ if not os.path.isdir(plugin_dir):+ continue+ if not os.path.isfile(os.path.join(plugin_dir, "plugin.py")):+ continue+ candidates.append((name, plugin_dir))+ return candidates+++def _load_one(mcp, name: str, plugin_dir: str) -> PluginRecord:+ """Carga un plugin AISLADO aplicando el micro-algoritmo MEDIUM-3/NIT-8.++ 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.+ """+ # (fase name) El nombre de dir debe casar el regex ANTES de tocar sys.path/import.+ if not PLUGIN_DIR_NAME_RE.match(name):+ print(+ f"{_LOG_PREFIX} plugin '{name}' rechazado: nombre de directorio inválido",+ flush=True,+ )+ return PluginRecord(+ name=name,+ status="failed",+ phase="name",+ error="invalid plugin directory name",+ )++ plugin_py = os.path.join(plugin_dir, "plugin.py")+ 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).+ 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í.+ try:+ spec = importlib.util.spec_from_file_location(mod_name, plugin_py)+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ except Exception as exc: # noqa: BLE001 - aislado: un plugin roto no tumba al resto+ traceback.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).+ plugin_api_version = getattr(module, "PLUGIN_API", None)+ if plugin_api_version != SUPPORTED_PLUGIN_API:+ msg = (+ f"PLUGIN_API {plugin_api_version!r} incompatible; "+ f"soportado {SUPPORTED_PLUGIN_API}"+ )+ 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.+ register = getattr(module, "register", None)+ if not callable(register):+ msg = "falta un callable register(ctx)"+ print(f"{_LOG_PREFIX} plugin '{name}' rechazado: {msg}", flush=True)+ return PluginRecord(+ name=name, status="failed", phase="register-missing", error=msg+ )++ # (e) fase 'register': ejecutar register(ctx). Si lanza, NIT-8: revertir tools.+ try:+ register(ctx)+ except Exception as exc: # noqa: BLE001 - aislado+ traceback.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+ traceback.print_exc()+ return PluginRecord(+ name=name, status="failed", phase="register", error=str(exc)+ )++ # (f) recoger lo anotado; colisiones -> degraded (cargó, pero no todo entró).+ if ctx.collisions:+ status, phase = "degraded", "register"+ else:+ status, phase = "loaded", "loaded"+ return PluginRecord(+ name=name,+ status=status,+ phase=phase,+ tools=list(ctx.tools),+ skill=ctx.skill_path,+ volumes=list(ctx.volumes),+ collisions=list(ctx.collisions),+ )+ finally:+ # (g) restaurar sys.path tras cada plugin (quitar SOLO la entrada insertada).+ try:+ sys.path.remove(plugin_dir)+ except ValueError:+ pass+++def load_plugins(mcp, plugins_root: str) -> PluginLoadReport:+ """Descubre y carga los plugins bajo ``plugins_root``. Devuelve y publica el reporte.++ 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).+ """+ global LAST_REPORT+ report = PluginLoadReport()++ if not plugins_root or not os.path.isdir(plugins_root):+ LAST_REPORT = report+ return report++ for name, plugin_dir in _iter_plugin_dirs(plugins_root):+ record = _load_one(mcp, name, plugin_dir)+ report.add(record)++ LAST_REPORT = report+ return reportdiff --git a/docker/kali/tests/fixtures/plugins/README.md b/docker/kali/tests/fixtures/plugins/README.mdnew file mode 100644index 0000000..2f4cc79--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/README.md@@ -0,0 +1,18 @@+# Fixtures de plugins para `test_plugin_loader`++Árbol de plugins de ejemplo que `test_plugin_loader.py` apunta como `plugins_root`. Cada+subdirectorio ejercita un camino del cargador:++- `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).++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`.diff --git a/docker/kali/tests/fixtures/plugins/aaa_first/plugin.py b/docker/kali/tests/fixtures/plugins/aaa_first/plugin.pynew file mode 100644index 0000000..4bea07f--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/aaa_first/plugin.py@@ -0,0 +1,12 @@+"""Plugin válido mínimo (fixture). Registra una tool y declara su skill."""++PLUGIN_API = 1+++def register(ctx):+ @ctx.tool(name="aaa_tool")+ def aaa_tool():+ return "aaa"++ ctx.skill("skill.md")+ ctx.needs_volume("aaa-vol")diff --git a/docker/kali/tests/fixtures/plugins/aaa_first/skill.md b/docker/kali/tests/fixtures/plugins/aaa_first/skill.mdnew file mode 100644index 0000000..06d5106--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/aaa_first/skill.md@@ -0,0 +1 @@+# aaa skill (fixture)diff --git a/docker/kali/tests/fixtures/plugins/bad_api/plugin.py b/docker/kali/tests/fixtures/plugins/bad_api/plugin.pynew file mode 100644index 0000000..a5ad641--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/bad_api/plugin.py@@ -0,0 +1,7 @@+"""Fixture fase 'api': PLUGIN_API incompatible (distinto de SUPPORTED_PLUGIN_API)."""++PLUGIN_API = 999+++def register(ctx): # pragma: no cover - nunca se alcanza+ passdiff --git a/docker/kali/tests/fixtures/plugins/broken_import/plugin.py b/docker/kali/tests/fixtures/plugins/broken_import/plugin.pynew file mode 100644index 0000000..d89e452--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/broken_import/plugin.py@@ -0,0 +1,9 @@+"""Fixture fase 'import': importa un módulo inexistente -> exec_module lanza."""++import this_module_does_not_exist_anywhere # noqa: F401++PLUGIN_API = 1+++def register(ctx): # pragma: no cover - nunca se alcanza+ passdiff --git a/docker/kali/tests/fixtures/plugins/example.disabled/plugin.py b/docker/kali/tests/fixtures/plugins/example.disabled/plugin.pynew file mode 100644index 0000000..9c4472d--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/example.disabled/plugin.py@@ -0,0 +1,9 @@+"""Fixture: dir terminado en .disabled -> el loader lo IGNORA (no debe cargarse)."""++PLUGIN_API = 1+++def register(ctx): # pragma: no cover - nunca se alcanza: el dir está deshabilitado+ @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.pynew file mode 100644index 0000000..4eb9a5e--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/no_api/plugin.py@@ -0,0 +1,5 @@+"""Fixture fase 'api': no declara PLUGIN_API."""+++def register(ctx): # pragma: no cover - nunca se alcanza+ passdiff --git a/docker/kali/tests/fixtures/plugins/no_register/plugin.py b/docker/kali/tests/fixtures/plugins/no_register/plugin.pynew file mode 100644index 0000000..927eb60--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/no_register/plugin.py@@ -0,0 +1,5 @@+"""Fixture fase 'register-missing': no expone un callable register."""++PLUGIN_API = 1++register = "no soy callable"diff --git a/docker/kali/tests/fixtures/plugins/not_a_plugin/README.md b/docker/kali/tests/fixtures/plugins/not_a_plugin/README.mdnew file mode 100644index 0000000..a4b9f99--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/not_a_plugin/README.md@@ -0,0 +1 @@+Dir SIN plugin.py: el loader lo omite (no es candidato).diff --git a/docker/kali/tests/fixtures/plugins/raises_register/plugin.py b/docker/kali/tests/fixtures/plugins/raises_register/plugin.pynew file mode 100644index 0000000..e3afc12--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/raises_register/plugin.py@@ -0,0 +1,14 @@+"""Fixture fase 'register' + NIT-8: registra una tool y luego LANZA.++El loader debe revertir la tool ya montada vía ``_tool_manager.remove_tool``.+"""++PLUGIN_API = 1+++def register(ctx):+ @ctx.tool(name="partial_tool")+ def partial_tool():+ return "partial"++ raise RuntimeError("boom en register")diff --git a/docker/kali/tests/fixtures/plugins/sibling_import/helper.py b/docker/kali/tests/fixtures/plugins/sibling_import/helper.pynew file mode 100644index 0000000..21b013a--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/sibling_import/helper.py@@ -0,0 +1,4 @@+"""Módulo HERMANO del fixture ``sibling_import`` (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.pynew file mode 100644index 0000000..0d0b55c--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/sibling_import/plugin.py@@ -0,0 +1,15 @@+"""Fixture MEDIUM-3: plugin.py que importa un HERMANO (``helper``) del mismo 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.+"""++import helper # noqa: F401 - hermano del mismo dir del plugin++PLUGIN_API = 1+++def register(ctx):+ @ctx.tool(name=helper.TOOL_NAME)+ def sibling_tool():+ return helper.VALUEdiff --git a/docker/kali/tests/fixtures/plugins/zzz_last/plugin.py b/docker/kali/tests/fixtures/plugins/zzz_last/plugin.pynew file mode 100644index 0000000..6bf1a15--- /dev/null+++ b/docker/kali/tests/fixtures/plugins/zzz_last/plugin.py@@ -0,0 +1,9 @@+"""Segundo plugin válido (fixture) para comprobar orden alfabético determinista."""++PLUGIN_API = 1+++def register(ctx):+ @ctx.tool(name="zzz_tool")+ def zzz_tool():+ return "zzz"diff --git a/docker/kali/tests/test_plugin_api.py b/docker/kali/tests/test_plugin_api.pynew file mode 100644index 0000000..590a8f3--- /dev/null+++ b/docker/kali/tests/test_plugin_api.py@@ -0,0 +1,188 @@+"""Tests de ``PluginContext`` (STDLIB PURA, con un doble de ``mcp`` — SIN el 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.+"""++from __future__ import annotations++import os+import sys+from pathlib import Path++import pytest++_PARENT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(_PARENT))++import plugin_api # noqa: E402+++class _FakeTool:+ def __init__(self, name: str) -> None:+ self.name = name+++class _FakeToolManager:+ """Doble del ``_tool_manager`` de FastMCP: lista y elimina tools por nombre."""++ def __init__(self, names=None) -> None:+ self._names = list(names or [])++ def list_tools(self):+ return [_FakeTool(n) for n in self._names]++ def remove_tool(self, name: str) -> None:+ self._names.remove(name)+++class _FakeMcp:+ """Doble de FastMCP: ``tool(*a, **k)`` registra el nombre al aplicarse al fn."""++ def __init__(self, existing=None) -> None:+ self._tool_manager = _FakeToolManager(existing)++ def tool(self, *args, **kwargs):+ def _decorator(fn):+ name = kwargs.get("name") or fn.__name__+ self._tool_manager._names.append(name)+ return fn++ return _decorator+++class _McpWithoutListTools:+ """Doble SIN ``_tool_manager.list_tools`` para probar el fallback MEDIUM-2."""++ class _TM:+ pass++ def __init__(self) -> None:+ self._tool_manager = self._TM()++ def tool(self, *args, **kwargs): # pragma: no cover - no debe llegar a delegar+ def _decorator(fn):+ return fn++ return _decorator+++def test_tool_delega_y_registra_el_nombre():+ mcp = _FakeMcp()+ ctx = plugin_api.PluginContext(mcp, "/opt/plugins/p")++ @ctx.tool()+ def my_scan(): # noqa: D401+ return "ok"++ assert ctx.tools == ["my_scan"]+ assert ctx.collisions == []+ # La tool quedó efectivamente registrada en el doble.+ assert "my_scan" in {t.name for t in mcp._tool_manager.list_tools()}+++def test_tool_colision_con_nativa_no_delega():+ mcp = _FakeMcp(existing=["server_info"])+ ctx = plugin_api.PluginContext(mcp, "/opt/plugins/p")++ @ctx.tool(name="server_info")+ def clash():+ return "nope"++ assert ctx.tools == []+ assert ctx.collisions == ["server_info"]+++def test_tool_colision_con_otro_plugin_no_delega():+ # Dos contextos sobre el MISMO mcp: el primero registra 'shared', el segundo colisiona.+ mcp = _FakeMcp()+ ctx_a = plugin_api.PluginContext(mcp, "/opt/plugins/a")+ ctx_b = plugin_api.PluginContext(mcp, "/opt/plugins/b")++ @ctx_a.tool(name="shared")+ def first():+ return 1++ @ctx_b.tool(name="shared")+ def second():+ return 2++ assert ctx_a.tools == ["shared"]+ assert ctx_b.tools == []+ assert ctx_b.collisions == ["shared"]+++def test_tool_fallback_medium2_falla_sin_list_tools():+ mcp = _McpWithoutListTools()+ ctx = plugin_api.PluginContext(mcp, "/opt/plugins/p")++ with pytest.raises(AttributeError):++ @ctx.tool()+ def broken():+ return "x"+++def test_skill_valida_realpath_bajo_plugin_dir(tmp_path):+ plugin_dir = tmp_path / "p"+ plugin_dir.mkdir()+ (plugin_dir / "skill.md").write_text("hola", encoding="utf-8")+ ctx = plugin_api.PluginContext(_FakeMcp(), str(plugin_dir))++ ctx.skill("skill.md")+ assert ctx.skill_path == os.path.realpath(str(plugin_dir / "skill.md"))+++def test_skill_que_escapa_no_se_anota(tmp_path):+ plugin_dir = tmp_path / "p"+ plugin_dir.mkdir()+ ctx = plugin_api.PluginContext(_FakeMcp(), str(plugin_dir))++ ctx.skill("../outside.md")+ assert ctx.skill_path is None+++def test_skill_segunda_llamada_es_error_de_contrato(tmp_path):+ plugin_dir = tmp_path / "p"+ plugin_dir.mkdir()+ (plugin_dir / "a.md").write_text("a", encoding="utf-8")+ (plugin_dir / "b.md").write_text("b", encoding="utf-8")+ ctx = plugin_api.PluginContext(_FakeMcp(), str(plugin_dir))++ ctx.skill("a.md")+ ctx.skill("b.md")+ # Se queda con la primera; la segunda se ignora.+ assert ctx.skill_path == os.path.realpath(str(plugin_dir / "a.md"))+++def test_needs_volume_anota():+ ctx = plugin_api.PluginContext(_FakeMcp(), "/opt/plugins/p")+ ctx.needs_volume("my-vol")+ ctx.needs_volume("other")+ assert ctx.volumes == ["my-vol", "other"]+++def test_plugin_dir_y_vendor_dir_siempre_absolutos():+ ctx = plugin_api.PluginContext(_FakeMcp(), "/opt/plugins/p")+ assert os.path.isabs(ctx.plugin_dir())+ assert os.path.isabs(ctx.vendor_dir())+ assert ctx.plugin_dir() == "/opt/plugins/p"+ assert ctx.vendor_dir() == "/opt/plugins/p/vendor"+++def test_vendor_dir_absoluto_aunque_no_exista(tmp_path):+ # vendor/ no existe pero vendor_dir() devuelve ruta absoluta igualmente (nunca None).+ plugin_dir = tmp_path / "p"+ plugin_dir.mkdir()+ ctx = plugin_api.PluginContext(_FakeMcp(), str(plugin_dir))+ assert ctx.vendor_dir() == str(plugin_dir / "vendor")+ assert not os.path.exists(ctx.vendor_dir())+++def test_constantes_de_contrato():+ assert plugin_api.SUPPORTED_PLUGIN_API == 1+ assert plugin_api.DISABLED_SUFFIX == ".disabled"+ assert plugin_api.PLUGIN_DIR_NAME_RE.match("ok-plugin_1.2")+ assert not plugin_api.PLUGIN_DIR_NAME_RE.match("bad name!")diff --git a/docker/kali/tests/test_plugin_loader.py b/docker/kali/tests/test_plugin_loader.pynew file mode 100644index 0000000..c9da99e--- /dev/null+++ b/docker/kali/tests/test_plugin_loader.py@@ -0,0 +1,159 @@+"""Tests de ``load_plugins`` (STDLIB PURA, con un doble de ``mcp`` — SIN el 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).+"""++from __future__ import annotations++import sys+from pathlib import Path++_PARENT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(_PARENT))++import plugin_loader # noqa: E402++_FIXTURES = Path(__file__).resolve().parent / "fixtures" / "plugins"+++class _FakeTool:+ def __init__(self, name: str) -> None:+ self.name = name+++class _FakeToolManager:+ def __init__(self) -> None:+ self._names: list[str] = []+ self.removed: list[str] = []++ def list_tools(self):+ return [_FakeTool(n) for n in self._names]++ def remove_tool(self, name: str) -> None:+ self.removed.append(name)+ self._names.remove(name)+++class _FakeMcp:+ def __init__(self) -> None:+ self._tool_manager = _FakeToolManager()++ def tool(self, *args, **kwargs):+ def _decorator(fn):+ name = kwargs.get("name") or fn.__name__+ self._tool_manager._names.append(name)+ return fn++ return _decorator+++def _by_name(report):+ return {r.name: r for r in report.plugins}+++def test_raiz_inexistente_reporte_vacio_y_last_report(tmp_path):+ mcp = _FakeMcp()+ 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).+ assert plugin_loader.LAST_REPORT is report+++def test_raiz_que_no_es_dir_reporte_vacio(tmp_path):+ f = tmp_path / "a-file"+ f.write_text("x", encoding="utf-8")+ report = plugin_loader.load_plugins(_FakeMcp(), str(f))+ assert report.plugins == []+++def test_orden_determinista_y_omisiones():+ mcp = _FakeMcp()+ report = plugin_loader.load_plugins(mcp, str(_FIXTURES))+ names = [r.name for r in report.plugins]++ # Orden alfabético estricto entre los candidatos presentes.+ assert names == sorted(names)+ # Dir .disabled ignorado y dir sin plugin.py omitido.+ assert "example.disabled" not in names+ assert "not_a_plugin" not in names+ # 'aaa_first' va antes que 'zzz_last'.+ assert names.index("aaa_first") < names.index("zzz_last")+++def test_plugin_valido_cargado_con_tool_skill_volumen():+ report = plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))+ rec = _by_name(report)["aaa_first"]+ assert rec.status == "loaded"+ assert rec.phase == "loaded"+ assert rec.tools == ["aaa_tool"]+ assert rec.skill is not None and rec.skill.endswith("skill.md")+ assert rec.volumes == ["aaa-vol"]+++def test_import_de_hermano_resuelve_medium3():+ report = plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))+ rec = _by_name(report)["sibling_import"]+ assert rec.status == "loaded"+ assert rec.tools == ["sibling_tool"]+++def test_import_roto_cae_en_fase_import():+ report = plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))+ 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).+ assert rec.error and "\n" not in rec.error+++def test_api_ausente_e_incompatible_caen_en_fase_api():+ report = plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))+ recs = _by_name(report)+ assert recs["no_api"].status == "failed"+ assert recs["no_api"].phase == "api"+ assert recs["bad_api"].status == "failed"+ assert recs["bad_api"].phase == "api"+++def test_sin_register_cae_en_register_missing():+ report = plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))+ rec = _by_name(report)["no_register"]+ assert rec.status == "failed"+ assert rec.phase == "register-missing"+++def test_register_que_lanza_revierte_tools_nit8():+ mcp = _FakeMcp()+ report = plugin_loader.load_plugins(mcp, str(_FIXTURES))+ 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.+ assert "partial_tool" in mcp._tool_manager.removed+ assert "partial_tool" not in mcp._tool_manager._names+++def test_sys_path_restaurado_tras_la_pasada():+ before = list(sys.path)+ plugin_loader.load_plugins(_FakeMcp(), str(_FIXTURES))+ assert sys.path == before+++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).+ 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")+ report = plugin_loader.load_plugins(_FakeMcp(), str(tmp_path))+ rec = _by_name(report)["bad name!"]+ assert rec.status == "failed"+ assert rec.phase == "name"+++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