The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(e2e): mcp_plugins harness: real mcp 2.x fixture server (stdio + streamable HTTP) recording its inbound wire
teknium1239a71047dd6
diff --git a/tests/e2e/core/mcp_plugins/__init__.py b/tests/e2e/core/mcp_plugins/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/tests/e2e/core/mcp_plugins/_helpers.py b/tests/e2e/core/mcp_plugins/_helpers.pynew file mode 100644index 00000000000..2dc51a1c4c3--- /dev/null+++ b/tests/e2e/core/mcp_plugins/_helpers.py@@ -0,0 +1,256 @@+"""Shared harness for the MCP + plugin conformance suite.++Every test drives a REAL Hermes process (``hermes chat -q`` or the ``tui_gateway``+stdio host) against the recording fake LLM provider and one or more REAL MCP+servers built with the installed ``mcp`` SDK (``mcp_fixture_server.py``), over+stdio or streamable HTTP. Fakes sit only at boundaries we do not own (the LLM+vendor, the MCP server); assertions read what the MCP server received, what the+next provider request carried, or what the Hermes process printed/persisted.+"""++from __future__ import annotations++import contextlib+import json+import os+import signal+import subprocess+import sys+import time+import uuid+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable, Iterator++import yaml++from tests.e2e.core.parity._helpers import hermes_argv, kill_tagged, tagged_pids, wait_until+from tests.fakes.fake_llm_provider import FakeLLMServer, Text, ToolCall, write_hermes_home++REPO_ROOT = Path(__file__).resolve().parents[4]+FIXTURE_SERVER = Path(__file__).with_name("mcp_fixture_server.py")+FINAL = "MCPE2E-TURN-COMPLETE"+TURN_TIMEOUT = 240.0++_SECRET_ENV_SUFFIXES = ("_API_KEY", "_TOKEN", "_SECRET", "_ACCESS_KEY")+_PASSTHROUGH_ENV = frozenset({"PATH", "LANG", "LANGUAGE", "USER", "LOGNAME", "SHELL", "TMPDIR", "TZ"})++__all__ = ["FINAL", "E2EHome", "HttpMcpServer", "build_home", "stdio_server", "http_server_cfg",+ "script", "run_chat_q", "inbound", "calls_received", "tool_results", "tool_name",+ "kill_tagged", "tagged_pids", "wait_until"]+++def tool_name(server: str, tool: str) -> str:+ return f"mcp__{server}__{tool}"+++@dataclass+class E2EHome:+ root: Path+ home: Path+ hermes_home: Path+ project: Path+ tag: str+ extra_env: dict[str, str] = field(default_factory=dict)++ def env(self, extra: dict[str, str] | None = None) -> dict[str, str]:+ """Hermetic child env: fake HOME (so no ``~/.hermes`` of the real user is reachable)."""+ import pwd # the suite is Linux-gated++ real_root = Path(pwd.getpwuid(os.getuid()).pw_dir, ".hermes").resolve()+ fixture = self.hermes_home.resolve()+ assert fixture != real_root and fixture.parent != real_root / "profiles", fixture+ assert fixture == (self.home / ".hermes").resolve(), fixture+ env = {k: v for k, v in os.environ.items()+ if (k in _PASSTHROUGH_ENV or k.startswith("LC_")) and not k.endswith(_SECRET_ENV_SUFFIXES)}+ env.update({+ "HOME": str(self.home), "HERMES_HOME": str(self.hermes_home), "PYTHONPATH": str(REPO_ROOT),+ "PYTHONUNBUFFERED": "1", "NO_COLOR": "1", "TERM": "dumb",+ "PARITY_TREE_TAG": self.tag, # orphan-scan tag inherited by the whole tree+ "HERMES_STATE_DB_GUARD_BYPASS": "1", # child HOME is tmp_path by construction+ })+ env.update(self.extra_env)+ env.update(extra or {})+ return env++ @property+ def config_path(self) -> Path:+ return self.hermes_home / "config.yaml"++ def update_config(self, mutate: Callable[[dict], None]) -> None:+ cfg = yaml.safe_load(self.config_path.read_text(encoding="utf-8"))+ mutate(cfg)+ self.config_path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+++def build_home(root: Path, base_url: str, *, mcp_servers: dict[str, dict] | None = None,+ extra: dict[str, Any] | None = None) -> E2EHome:+ home = root / "home"+ hermes_home = home / ".hermes"+ project = root / "project"+ for d in (hermes_home, project):+ d.mkdir(parents=True, exist_ok=True)+ eh = E2EHome(root=root, home=home, hermes_home=hermes_home, project=project, tag=uuid.uuid4().hex)+ write_hermes_home(hermes_home, base_url)+ cfg = yaml.safe_load(eh.config_path.read_text(encoding="utf-8"))+ cfg["mcp_servers"] = dict(mcp_servers or {})+ # Discovery must be complete before the first agent build (interactive surfaces+ # wait only ~1.5 s by default, by design); the join returns as soon as it finishes.+ cfg["mcp_discovery_timeout"] = 120+ cfg["mcp_single_query_discovery_timeout"] = 120+ cfg.setdefault("display", {})["compact"] = True+ cfg["updates"] = {"check": False}+ cfg.update(extra or {})+ eh.config_path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")+ return eh+++def stdio_server(name: str, log: Path, tag: str, **env: str) -> dict[str, Any]:+ """``mcp_servers`` entry for a stdio fixture server logging its inbound wire to ``log``."""+ return {+ "command": sys.executable,+ "args": [str(FIXTURE_SERVER)],+ "env": {"MCPE2E_LOG": str(log), "MCPE2E_NAME": name, "PARITY_TREE_TAG": tag,+ "PYTHONPATH": str(REPO_ROOT), **env},+ "connect_timeout": 60,+ "timeout": 60,+ }+++def http_server_cfg(url: str, **extra: Any) -> dict[str, Any]:+ return {"url": url, "connect_timeout": 30, "timeout": 30, **extra}+++class HttpMcpServer:+ """A streamable-HTTP fixture server subprocess that can be crashed and restarted on its port."""++ def __init__(self, root: Path, tag: str, **env: str) -> None:+ self.root = root+ self.tag = tag+ self.log = root / "http_inbound.jsonl"+ self.port_file = root / "http_port"+ self.env = env+ self.port = 0+ self.proc: subprocess.Popen | None = None+ self.stderr_path = root / "http_server.stderr"++ @property+ def url(self) -> str:+ return f"http://127.0.0.1:{self.port}/mcp"++ def start(self) -> "HttpMcpServer":+ with contextlib.suppress(FileNotFoundError):+ self.port_file.unlink()+ env = {k: v for k, v in os.environ.items() if k in _PASSTHROUGH_ENV}+ env.update({"PYTHONPATH": str(REPO_ROOT), "MCPE2E_TRANSPORT": "http", "MCPE2E_LOG": str(self.log),+ "MCPE2E_PORT_FILE": str(self.port_file), "MCPE2E_PORT": str(self.port),+ "PARITY_TREE_TAG": self.tag, **self.env})+ with open(self.stderr_path, "ab") as err:+ self.proc = subprocess.Popen([sys.executable, str(FIXTURE_SERVER)], env=env,+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=err)+ text = wait_until(lambda: self.port_file.exists() and self.port_file.read_text().strip(), 60,+ f"HTTP MCP server bind ({self.stderr_path})")+ self.port = int(text.split()[0])+ return self++ def wait_exit(self, timeout: float = 30.0) -> int:+ assert self.proc is not None+ return self.proc.wait(timeout=timeout)++ def stop(self) -> None:+ if self.proc is not None and self.proc.poll() is None:+ self.proc.send_signal(signal.SIGTERM)+ try:+ self.proc.wait(timeout=10)+ except subprocess.TimeoutExpired:+ self.proc.kill()+ self.proc.wait(timeout=10)+++# Scripted provider -----------------------------------------------------------------------------+++def _names(body: dict[str, Any]) -> set[str]:+ return {(t.get("function") or {}).get("name") for t in body.get("tools") or []}+++def _tool_msgs_this_turn(body: dict[str, Any]) -> list[dict]:+ msgs = body.get("messages") or []+ last_user = max((i for i, m in enumerate(msgs) if m.get("role") == "user"), default=-1)+ return [m for m in msgs[last_user + 1:] if m.get("role") == "tool"]+++def script(*calls: tuple[str, dict[str, Any] | str]) -> Callable[[dict[str, Any]], Any]:+ """Stateless per-turn script: issue ``calls[k]`` while k tool results exist this turn, then answer.++ Stateless (keyed on the request's own history) so a retried request cannot desynchronise it,+ and it restarts on every new user message (multi-turn sessions)."""++ def respond(record: dict[str, Any]):+ body = record["body"]+ done = len(_tool_msgs_this_turn(body))+ if done >= len(calls):+ return Text(FINAL)+ name, args = calls[done]+ if name in _names(body) or "tool_call" not in _names(body):+ return ToolCall(name, args)+ # Tool Search active: MCP tools sit behind the deferred-catalog bridge.+ return ToolCall("tool_call", {"calls": [{"name": name, "arguments": args}]})++ return respond+++def run_chat_q(eh: E2EHome, prompt: str, *, timeout: float = TURN_TIMEOUT,+ env: dict[str, str] | None = None) -> subprocess.CompletedProcess:+ return subprocess.run(hermes_argv("chat", "-q", prompt, "-Q"), cwd=eh.project, env=eh.env(env),+ capture_output=True, text=True, timeout=timeout, stdin=subprocess.DEVNULL)+++# Observation ------------------------------------------------------------------------------------+++def inbound(log: Path) -> list[dict[str, Any]]:+ if not log.exists():+ return []+ return [json.loads(line)["msg"] for line in log.read_text(encoding="utf-8").splitlines() if line.strip()]+++def calls_received(log: Path, tool: str) -> list[dict[str, Any]]:+ """``tools/call`` request params the server received for ``tool`` (bare MCP tool name)."""+ return [m.get("params") or {} for m in inbound(log)+ if isinstance(m, dict) and m.get("method") == "tools/call"+ and (m.get("params") or {}).get("name") == tool]+++def _text(content: Any) -> str:+ if isinstance(content, str):+ return content+ if isinstance(content, list):+ return "\n".join(p.get("text", "") for p in content if isinstance(p, dict))+ return ""+++def tool_results(srv: FakeLLMServer) -> list[str]:+ """Tool-result contents in the LAST main request (what the model saw)."""+ mains = srv.main_requests()+ if not mains:+ return []+ return [_text(m.get("content")) for m in mains[-1].get("messages") or [] if m.get("role") == "tool"]+++def provider(responder: Callable[[dict[str, Any]], Any]) -> Iterator[FakeLLMServer]:+ srv = FakeLLMServer(responder)+ srv.start()+ try:+ yield srv+ finally:+ srv.stop()+++def wait_for(pred: Callable[[], Any], timeout: float, what: str) -> Any:+ return wait_until(pred, timeout, what)+++def now() -> float:+ return time.monotonic()diff --git a/tests/e2e/core/mcp_plugins/mcp_fixture_server.py b/tests/e2e/core/mcp_plugins/mcp_fixture_server.pynew file mode 100644index 00000000000..6bafe5f0fd2--- /dev/null+++ b/tests/e2e/core/mcp_plugins/mcp_fixture_server.py@@ -0,0 +1,243 @@+"""Real MCP server (installed ``mcp`` 2.x SDK) for the MCP + plugin conformance suite.++Runs over stdio (default) or streamable HTTP (``MCPE2E_TRANSPORT=http``) and records+every JSON-RPC message it RECEIVES, byte-exact as parsed JSON, to ``MCPE2E_LOG``+(one object per line). Tests assert on what the server actually got on the wire+(arguments, ``_meta``), never on what Hermes believes it sent.++Environment knobs (all optional):++* ``MCPE2E_LOG`` — JSONL path for inbound messages (stdio: teed from fd 0; HTTP: ASGI body).+* ``MCPE2E_NAME`` — server name advertised in ``initialize`` (default ``e2e``).+* ``MCPE2E_CANARY`` — returned by every tool so a test can prove a REAL round trip.+* ``MCPE2E_ECHO_ENV`` — name of an env var whose value ``env_echo`` returns (``${VAR}`` checks).+* ``MCPE2E_RESOURCE_ONLY=1`` — advertise one resource and NO tools.+* ``MCPE2E_TRANSPORT=http`` + ``MCPE2E_PORT_FILE`` — serve streamable HTTP on+ ``MCPE2E_PORT`` (0 = ephemeral) and write the bound port to the file.+* ``MCPE2E_401_CALLS=<path>`` — HTTP only: while the file holds a positive integer N,+ the next ``tools/call`` is answered ``401`` and N is decremented (the fault survives+ a server restart because the budget lives on disk).+"""++from __future__ import annotations++import base64+import json+import os+import sys+import threading++_LOG_LOCK = threading.Lock()+++def _log(msg: object) -> None:+ path = os.environ.get("MCPE2E_LOG")+ if not path:+ return+ items = msg if isinstance(msg, list) else [msg]+ with _LOG_LOCK, open(path, "a", encoding="utf-8") as fh:+ for item in items:+ fh.write(json.dumps({"pid": os.getpid(), "msg": item}) + "\n")+++def _log_raw_line(line: bytes) -> None:+ line = line.strip()+ if not line:+ return+ try:+ _log(json.loads(line))+ except ValueError:+ _log({"unparsed": line.decode("utf-8", "replace")})+++def _tee_stdin() -> None:+ """Swap fd 0 for a pipe fed by a pump thread that logs each newline-delimited frame."""+ read_end, write_end = os.pipe()+ upstream = os.dup(0)+ os.dup2(read_end, 0)+ os.close(read_end)++ def pump() -> None:+ pending = b""+ with os.fdopen(upstream, "rb", buffering=0) as src, os.fdopen(write_end, "wb", buffering=0) as dst:+ while True:+ chunk = src.read(65536)+ if not chunk:+ break+ pending += chunk+ *lines, pending = pending.split(b"\n")+ for line in lines:+ _log_raw_line(line)+ dst.write(chunk)+ _log_raw_line(pending)++ threading.Thread(target=pump, name="mcpe2e-tee", daemon=True).start()+++# 1x1 PNG (valid magic bytes; the image cache accepts it).+_PNG = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="+)+# Formats the image cache cannot store: (mime, raw bytes or None for "send the data string verbatim").+IMAGE_FORMATS: dict[str, tuple[str, bytes | str]] = {+ "png": ("image/png", _PNG),+ "svg": ("image/svg+xml", b'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>'),+ "avif": ("image/avif", b"\x00\x00\x00\x1cftypavif\x00\x00\x00\x00avifmif1miaf"),+ "tiff": ("image/tiff", b"II*\x00\x08\x00\x00\x00\x00\x00"),+ "heic": ("image/heic", b"\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"),+ "badb64": ("image/png", "@@not-base64@@"),+}+++def build_server():+ from mcp.server import MCPServer+ from mcp_types import ImageContent, TextContent, ToolAnnotations++ canary = os.environ.get("MCPE2E_CANARY", "NO-CANARY")+ server = MCPServer(os.environ.get("MCPE2E_NAME", "e2e"))++ if os.environ.get("MCPE2E_RESOURCE_ONLY") == "1":+ @server.resource("e2e://doc", name="doc", description="the only thing this server offers")+ def doc() -> str:+ return f"DOC:{canary}"+ return server++ @server.tool(annotations=ToolAnnotations(read_only_hint=True, destructive_hint=False))+ def ro_probe(nonce: str = "") -> str:+ """Read-only probe (annotated readOnlyHint=true)."""+ return f"RO:{canary}:{nonce}"++ @server.tool(annotations=ToolAnnotations(read_only_hint=False, destructive_hint=True))+ def rw_probe(nonce: str = "") -> str:+ """Destructive probe (annotated destructiveHint=true)."""+ return f"RW:{canary}:{nonce}"++ @server.tool()+ def noargs_probe() -> str:+ """Takes no parameters at all."""+ return f"NOARGS:{canary}"++ @server.tool()+ def optional_obj_probe(operation: str = "list", parameters: dict | None = None) -> str:+ """No required params; ``parameters`` is an optional JSON object."""+ return f"OPT:{canary}:{operation}:{json.dumps(parameters, sort_keys=True)}"++ @server.tool()+ def image_probe(fmt: str = "png") -> list:+ """Return a status line plus one image block in the requested format."""+ mime, payload = IMAGE_FORMATS[fmt]+ data = payload if isinstance(payload, str) else base64.b64encode(payload).decode()+ return [TextContent(type="text", text=f"IMG-STATUS:{canary}:{fmt}"),+ ImageContent(type="image", mime_type=mime, data=data)]++ @server.tool()+ def env_echo() -> str:+ """Return the value of the env var named by MCPE2E_ECHO_ENV."""+ name = os.environ.get("MCPE2E_ECHO_ENV", "")+ return f"ENV:{canary}:{os.environ.get(name, '<unset>')}"++ @server.tool()+ def crash_probe() -> str:+ """Kill this server process while the call is in flight (no response is ever sent)."""+ _log({"crash_probe_pid": os.getpid()})+ os._exit(7)++ return server+++def _take_401(path: str) -> bool:+ try:+ with open(path, encoding="utf-8") as fh:+ left = int(fh.read().strip() or 0)+ except (OSError, ValueError):+ return False+ if left <= 0:+ return False+ with open(path, "w", encoding="utf-8") as fh:+ fh.write(str(left - 1))+ return True+++def _recording_app(inner):+ """ASGI wrapper: log each POSTed JSON-RPC body; optionally answer tools/call with 401."""+ fault_file = os.environ.get("MCPE2E_401_CALLS")++ async def app(scope, receive, send):+ if scope["type"] != "http" or scope.get("method") != "POST":+ await inner(scope, receive, send)+ return+ chunks = []+ while True:+ event = await receive()+ chunks.append(event.get("body", b""))+ if not event.get("more_body"):+ break+ body = b"".join(chunks)+ try:+ parsed = json.loads(body or b"null")+ except ValueError:+ parsed = {"unparsed": body.decode("utf-8", "replace")}+ _log(parsed)+ is_call = isinstance(parsed, dict) and parsed.get("method") == "tools/call"+ if is_call and fault_file and _take_401(fault_file):+ _log({"injected_401_for": parsed.get("id")})+ await send({"type": "http.response.start", "status": 401,+ "headers": [(b"content-type", b"application/json")]})+ await send({"type": "http.response.body", "body": b'{"error":"unauthorized"}'})+ return+ replayed = False++ async def replay():+ nonlocal replayed+ if not replayed:+ replayed = True+ return {"type": "http.request", "body": body, "more_body": False}+ return await receive()++ await inner(scope, replay, send)++ return app+++def _serve_http(server) -> None:+ import socket++ import uvicorn++ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind(("127.0.0.1", int(os.environ.get("MCPE2E_PORT", "0") or 0)))+ port = sock.getsockname()[1]+ app = _recording_app(server.streamable_http_app())+ config = uvicorn.Config(app, log_level="warning", lifespan="on")+ userver = uvicorn.Server(config)+ port_file = os.environ.get("MCPE2E_PORT_FILE")++ async def run():+ import asyncio++ task = asyncio.create_task(userver.serve(sockets=[sock]))+ while not userver.started:+ await asyncio.sleep(0.01)+ if port_file:+ tmp = port_file + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ fh.write(f"{port} {os.getpid()}")+ os.replace(tmp, port_file)+ await task++ import asyncio++ asyncio.run(run())+++def main() -> None:+ if os.environ.get("MCPE2E_TRANSPORT") == "http":+ _serve_http(build_server())+ return+ _tee_stdin()+ build_server().run(transport="stdio")+++if __name__ == "__main__":+ sys.exit(main())