The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(mcp): one parent-death supervisor per process, not one per stdio server
John Paul Soliva2d783a15eb0b
diff --git a/tests/tools/test_mcp_death_supervisor.py b/tests/tools/test_mcp_death_supervisor.pynew file mode 100644index 00000000000..ef08cdebec9--- /dev/null+++ b/tests/tools/test_mcp_death_supervisor.py@@ -0,0 +1,589 @@+"""Contract tests for the shared parent-death supervisor for stdio MCP servers.++The end-to-end tests here spawn real processes and really SIGKILL a real parent,+because the whole point of this module is behaviour that only exists when a+process dies without running any Python cleanup. A mocked parent death proves+nothing about the guarantee.+"""++import asyncio+import contextlib+import io+import os+import signal+import subprocess+import sys+import time+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from tools import mcp_death_supervisor, mcp_tool++pytestmark = pytest.mark.skipif(+ os.name != "posix", reason="the supervisor is POSIX-only (process groups)"+)++SUPERVISOR = os.path.join(os.path.dirname(mcp_tool.__file__), "mcp_death_supervisor.py")++# Long enough that nothing here can pass because the victim exited on its own.+_VICTIM = [sys.executable, "-c", "import time; time.sleep(300)"]+++def _alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except (ProcessLookupError, OSError):+ return False+ return True+++def _wait_gone(pid: int, timeout: float = 15.0) -> bool:+ """Wait for a process this test does NOT own to disappear."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if not _alive(pid):+ return True+ time.sleep(0.05)+ return False+++def _wait_exited(proc: subprocess.Popen, timeout: float = 15.0) -> bool:+ """Wait for a direct child of this test to exit.++ ``os.kill(pid, 0)`` cannot be used for our own children: a killed child+ stays a zombie until someone reaps it, and signalling a zombie succeeds.+ """+ try:+ proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ return False+ return True+++def _kill(pid: int) -> None:+ try:+ os.kill(pid, signal.SIGKILL)+ except (ProcessLookupError, OSError):+ pass+++# ---------------------------------------------------------------------------+# Target safety: this process signals whole process GROUPS, so a bad target is+# unusually expensive. killpg(0, ...) would signal the supervisor's own group.+# ---------------------------------------------------------------------------++[email protected]("pgid", [0, 1, -1, -5])+def test_refuses_process_groups_that_are_never_a_valid_target(pgid):+ assert mcp_death_supervisor._is_safe_target(+ pgid, own_pgid=4242, parent_pgid=777+ ) is False+++def test_refuses_its_own_group_and_the_parents_group():+ assert mcp_death_supervisor._is_safe_target(+ 4242, own_pgid=4242, parent_pgid=777+ ) is False+ assert mcp_death_supervisor._is_safe_target(+ 777, own_pgid=4242, parent_pgid=777+ ) is False+++def test_accepts_an_unrelated_group():+ assert mcp_death_supervisor._is_safe_target(+ 999, own_pgid=4242, parent_pgid=777+ ) is True+++# ---------------------------------------------------------------------------+# Control protocol+# ---------------------------------------------------------------------------+++def test_registrations_survive_to_eof_and_unregistrations_are_dropped():+ stream = io.StringIO("register 111\nregister 222\nunregister 111\n")++ still_registered = mcp_death_supervisor._serve(+ stream, own_pgid=4242, parent_pgid=777+ )++ assert still_registered == {222}+++def test_garbage_lines_do_not_cost_us_the_other_registrations():+ # A corrupted byte on the control pipe must not take down reaping for every+ # other server -- that would turn a cosmetic bug into leaked processes.+ stream = io.StringIO(+ "register 111\n"+ "\n"+ "register\n"+ "register notanumber\n"+ "register 222 333\n"+ "explode 444\n"+ "register 555\n"+ )++ still_registered = mcp_death_supervisor._serve(+ stream, own_pgid=4242, parent_pgid=777+ )++ assert still_registered == {111, 555}+++def test_a_writer_that_never_sends_a_newline_cannot_grow_us_without_bound():+ """Found for real: iterating the stream let /dev/zero reach 15 GB.++ The supervisor is the last line of defense against leaked MCP servers, so+ it must not be the process that dies under memory pressure -- and a reader+ that buffers until a newline arrives is exactly that risk.+ """+ huge = "register " + ("0" * 10_000_000) + "\nregister 222\n"++ still_registered = mcp_death_supervisor._serve(+ io.StringIO(huge), own_pgid=4242, parent_pgid=777+ )++ # The overlong line is skipped, and the stream resyncs on the next one.+ assert still_registered == {222}+++def test_a_line_truncated_by_the_cap_is_never_acted_on():+ # Truncation must not turn one pgid into a different, valid-looking one:+ # "register 999999" clipped to "register 9" would reap the wrong group.+ stream = io.StringIO("register " + "9" * (mcp_death_supervisor._MAX_LINE_CHARS))++ assert mcp_death_supervisor._serve(+ stream, own_pgid=4242, parent_pgid=777+ ) == set()+++def test_unsafe_targets_are_rejected_at_registration_time():+ stream = io.StringIO("register 0\nregister 777\nregister 999\n")++ still_registered = mcp_death_supervisor._serve(+ stream, own_pgid=4242, parent_pgid=777+ )++ assert still_registered == {999}+++def test_refuses_to_run_inside_the_parents_own_process_group():+ # Started without start_new_session, a killpg of the parent's group would+ # take the supervisor out before it could reap. It must not pretend to work.+ proc = subprocess.run(+ [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ stdin=subprocess.DEVNULL,+ capture_output=True,+ text=True,+ timeout=30,+ )++ assert proc.returncode == 2+ assert "process group" in proc.stderr+++# ---------------------------------------------------------------------------+# End to end: real processes, real death+# ---------------------------------------------------------------------------+++def test_reaps_a_registered_group_when_the_control_pipe_reaches_eof():+ victim = subprocess.Popen(_VICTIM, start_new_session=True)+ supervisor = subprocess.Popen(+ [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ stdin=subprocess.PIPE,+ text=True,+ start_new_session=True,+ )+ try:+ supervisor.stdin.write(f"register {os.getpgid(victim.pid)}\n")+ supervisor.stdin.flush()+ assert victim.poll() is None, "victim should outlive registration"++ # EOF is the death signal, whatever closed the pipe.+ supervisor.stdin.close()++ assert _wait_exited(victim), "registered group survived parent death"+ finally:+ _kill(victim.pid)+ _kill(supervisor.pid)+ victim.wait(timeout=10)+ supervisor.wait(timeout=10)+++def test_leaves_an_unregistered_group_alone_at_eof():+ # The other failure direction, and the more damaging one: a clean Hermes+ # shutdown unregisters as it tears each server down, so EOF must not become+ # a kill-everything event for servers that were handed back.+ survivor = subprocess.Popen(_VICTIM, start_new_session=True)+ supervisor = subprocess.Popen(+ [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ stdin=subprocess.PIPE,+ text=True,+ start_new_session=True,+ )+ try:+ pgid = os.getpgid(survivor.pid)+ supervisor.stdin.write(f"register {pgid}\nunregister {pgid}\n")+ supervisor.stdin.flush()+ supervisor.stdin.close()++ supervisor.wait(timeout=15)+ assert survivor.poll() is None, "a cleanly unregistered server was killed"+ finally:+ _kill(survivor.pid)+ _kill(supervisor.pid)+ survivor.wait(timeout=10)+ supervisor.wait(timeout=10)+++# A stand-in for Hermes: registers a real child, then blocks forever holding the+# only write end of the control pipe. SIGKILLing it is the scenario the whole+# module exists for -- no cleanup code of ours gets to run.+_FAKE_PARENT = """+import os, subprocess, sys, time++supervisor = sys.argv[1]+victim = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(300)"], start_new_session=True+)+sup = subprocess.Popen(+ [sys.executable, supervisor, "--parent-pgid", str(os.getpgid(0))],+ stdin=subprocess.PIPE, text=True, start_new_session=True,+)+sup.stdin.write("register %d\\n" % os.getpgid(victim.pid))+sup.stdin.flush()+print("%d %d" % (victim.pid, sup.pid), flush=True)+time.sleep(300)+"""+++# Reparented-to-init processes are by definition outside this test's subtree,+# so cleaning them up trips conftest's live-system kill guard. Real signal+# delivery to a real orphan is the entire point of these two tests.[email protected]_system_guard_bypass+def test_reaps_the_server_when_the_registering_parent_is_sigkilled(tmp_path):+ script = tmp_path / "fake_parent.py"+ script.write_text(_FAKE_PARENT)++ parent = subprocess.Popen(+ [sys.executable, str(script), SUPERVISOR],+ stdout=subprocess.PIPE,+ text=True,+ )+ victim_pid = supervisor_pid = None+ try:+ victim_pid, supervisor_pid = (+ int(x) for x in parent.stdout.readline().split()+ )+ assert _alive(victim_pid)++ # No graceful anything: the parent never runs another line of Python.+ parent.kill()+ parent.wait(timeout=10)++ assert _wait_gone(victim_pid), (+ "stdio MCP server survived kill -9 of its Hermes parent"+ )+ finally:+ for pid in (victim_pid, supervisor_pid):+ if pid is not None:+ _kill(pid)+ _kill(parent.pid)++[email protected]_system_guard_bypass+def test_reaps_a_grandchild_left_in_the_registered_group(tmp_path):+ # Real shape of the bug: mcp-remote exits but leaves the `node` it spawned+ # behind. The grandchild reparents to init but keeps the pgid, so killpg+ # still reaches it -- which is why we track groups and not pids.+ script = tmp_path / "leaky_server.py"+ script.write_text(+ "import subprocess, sys\n"+ "child = subprocess.Popen([sys.executable, '-c',"+ " 'import time; time.sleep(300)'])\n"+ "print(child.pid, flush=True)\n"+ )++ # start_new_session mirrors how the MCP SDK spawns stdio servers.+ server = subprocess.Popen(+ [sys.executable, str(script)],+ stdout=subprocess.PIPE,+ text=True,+ start_new_session=True,+ )+ grandchild_pid = int(server.stdout.readline())+ server.wait(timeout=10) # the direct child exits; the grandchild does not++ supervisor = subprocess.Popen(+ [sys.executable, SUPERVISOR, "--parent-pgid", str(os.getpgid(0))],+ stdin=subprocess.PIPE,+ text=True,+ start_new_session=True,+ )+ try:+ assert _alive(grandchild_pid), "grandchild should outlive its parent"+ # server.pid is its own pgid leader, captured at spawn time exactly as+ # mcp_tool records it -- still usable after the leader itself exited.+ supervisor.stdin.write(f"register {server.pid}\n")+ supervisor.stdin.flush()+ supervisor.stdin.close()++ assert _wait_gone(grandchild_pid), "orphaned grandchild was not reaped"+ finally:+ _kill(grandchild_pid)+ _kill(supervisor.pid)+ supervisor.wait(timeout=10)+++# ---------------------------------------------------------------------------+# Client side: what mcp_tool tells the supervisor+# ---------------------------------------------------------------------------+++class _FakeSupervisor:+ """Stands in for the supervisor process, recording the control stream."""++ def __init__(self, exited=False):+ self.stdin = io.StringIO()+ self.pid = 4242+ self._exited = exited++ def poll(self):+ return 1 if self._exited else None++ def lines(self):+ return self.stdin.getvalue().splitlines()++[email protected](autouse=True)+def _reset_client_state():+ yield+ mcp_tool._death_supervisor = None+ mcp_tool._supervised_pgids.clear()+++def test_register_starts_the_supervisor_once_and_reuses_it(monkeypatch):+ spawned = []++ def _spawn():+ fake = _FakeSupervisor()+ spawned.append(fake)+ return fake++ monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", _spawn)++ mcp_tool._update_death_supervisor("register", [111])+ mcp_tool._update_death_supervisor("register", [222])++ assert len(spawned) == 1, "each register spawned its own supervisor"+ assert spawned[0].lines() == ["register 111", "register 222"]+++def test_unregister_is_forwarded(monkeypatch):+ fake = _FakeSupervisor()+ monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: fake)++ mcp_tool._update_death_supervisor("register", [111])+ mcp_tool._update_death_supervisor("unregister", [111])++ assert fake.lines() == ["register 111", "unregister 111"]+ assert mcp_tool._supervised_pgids == set()+++def test_unregister_alone_does_not_start_a_supervisor(monkeypatch):+ spawned = []+ monkeypatch.setattr(+ mcp_tool,+ "_spawn_death_supervisor",+ lambda: spawned.append(1) or _FakeSupervisor(),+ )++ mcp_tool._update_death_supervisor("unregister", [111])++ assert spawned == []+++def test_a_dead_supervisor_is_replaced_and_live_coverage_replayed(monkeypatch):+ dead = _FakeSupervisor(exited=True)+ replacement = _FakeSupervisor()+ queue = [dead, replacement]+ monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: queue.pop(0))++ mcp_tool._update_death_supervisor("register", [111])+ mcp_tool._update_death_supervisor("register", [222])++ # Losing the supervisor must not silently drop the server registered with+ # it -- the replacement has to be told about 111 as well as 222.+ assert set(replacement.lines()) == {"register 111", "register 222"}+++def test_replay_does_not_resurrect_an_unregistered_group(monkeypatch):+ dead = _FakeSupervisor(exited=True)+ replacement = _FakeSupervisor()+ queue = [dead, replacement]+ monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: queue.pop(0))++ mcp_tool._update_death_supervisor("register", [111])+ mcp_tool._update_death_supervisor("register", [222])+ mcp_tool._update_death_supervisor("unregister", [111])++ assert mcp_tool._supervised_pgids == {222}+ assert "register 111" not in replacement.lines()[-1:]+++def test_a_broken_pipe_never_propagates_into_a_live_mcp_session(monkeypatch):+ class _BrokenPipe(_FakeSupervisor):+ def __init__(self):+ super().__init__()++ class _Stdin:+ def write(self, _payload):+ raise BrokenPipeError("supervisor exited after poll()")++ def flush(self):+ pass++ self.stdin = _Stdin()++ monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", _BrokenPipe)++ mcp_tool._update_death_supervisor("register", [111]) # must not raise++ # Dropped, so the next registration respawns instead of writing into a+ # pipe that is known to be dead.+ assert mcp_tool._death_supervisor is None+++def test_a_supervisor_that_cannot_start_is_not_fatal(monkeypatch):+ monkeypatch.setattr(mcp_tool, "_spawn_death_supervisor", lambda: None)++ mcp_tool._update_death_supervisor("register", [111]) # must not raise++ assert mcp_tool._death_supervisor is None+++def _stdio_connection(child_pid, fake_supervisor):+ """Drive the real MCPServerTask._run_stdio with a known spawned child.++ Only the MCP transport itself is mocked. Everything the supervisor wiring+ depends on -- child discovery, _filter_mcp_children, the real os.getpgid+ lookup -- runs for real against ``child_pid``, so the pgid asserted on is+ the pgid of an actual process rather than a fixture value.+ """+ session = MagicMock()+ session.initialize = AsyncMock()+ session.list_tools = AsyncMock(return_value=SimpleNamespace(tools=[]))++ stdio_cm = MagicMock()+ stdio_cm.__aenter__ = AsyncMock(return_value=(object(), object()))+ stdio_cm.__aexit__ = AsyncMock(return_value=False)+ session_cm = MagicMock()+ session_cm.__aenter__ = AsyncMock(return_value=session)+ session_cm.__aexit__ = AsyncMock(return_value=False)++ with (+ patch("tools.mcp_tool.stdio_client", return_value=stdio_cm),+ patch("tools.mcp_tool.ClientSession", return_value=session_cm),+ # First call is the pids_before baseline; the second reports our child+ # as the newly spawned server.+ patch(+ "tools.mcp_tool._snapshot_child_pids",+ side_effect=[set(), {child_pid}],+ ),+ patch("tools.mcp_tool._write_stderr_log_header"),+ patch("tools.mcp_tool._get_mcp_stderr_log", return_value=None),+ patch(+ "tools.mcp_tool._spawn_death_supervisor",+ return_value=fake_supervisor,+ ),+ ):+ yield mcp_tool.MCPServerTask("supervisor-wiring")++[email protected](not mcp_tool._MCP_AVAILABLE, reason="MCP SDK not installed")+def test_connecting_a_stdio_server_registers_its_real_process_group():+ fake = _FakeSupervisor()+ child = subprocess.Popen(_VICTIM, start_new_session=True)+ try:+ with _stdio_connection(child.pid, fake) as server:+ asyncio.run(server.start({"command": "echo", "args": ["hi"]}))++ assert f"register {os.getpgid(child.pid)}" in fake.lines(), (+ "connecting a stdio server did not hand its process group to the "+ f"supervisor; control stream was {fake.lines()}"+ )+ finally:+ _kill(child.pid)+ child.wait(timeout=10)++[email protected](not mcp_tool._MCP_AVAILABLE, reason="MCP SDK not installed")+def test_a_server_that_exited_is_released_on_teardown():+ fake = _FakeSupervisor()+ child = subprocess.Popen(_VICTIM, start_new_session=True)+ pgid = None+ try:+ with _stdio_connection(child.pid, fake) as server:++ async def _connect_then_lose_the_child():+ await server.start({"command": "echo", "args": ["hi"]})+ nonlocal pgid+ pgid = os.getpgid(child.pid)+ # The server exits while connected. Reap it here so the+ # teardown path sees a genuinely dead pid, not a zombie.+ child.kill()+ child.wait(timeout=10)+ await server.shutdown()++ asyncio.run(_connect_then_lose_the_child())++ assert f"register {pgid}" in fake.lines()+ assert f"unregister {pgid}" in fake.lines(), (+ "a stdio server with nothing left alive stayed registered, so the "+ f"supervisor would keep a stale group; stream was {fake.lines()}"+ )+ finally:+ _kill(child.pid)++[email protected](not mcp_tool._MCP_AVAILABLE, reason="MCP SDK not installed")+def test_a_server_that_survived_teardown_stays_registered():+ # The case the whole module exists for: teardown did not manage to kill it.+ # Releasing it here would hand the orphan back to nobody.+ fake = _FakeSupervisor()+ child = subprocess.Popen(_VICTIM, start_new_session=True)+ try:+ with _stdio_connection(child.pid, fake) as server:++ async def _connect_then_shutdown():+ await server.start({"command": "echo", "args": ["hi"]})+ await server.shutdown()++ asyncio.run(_connect_then_shutdown())++ pgid = os.getpgid(child.pid)+ assert f"register {pgid}" in fake.lines()+ assert f"unregister {pgid}" not in fake.lines(), (+ "a server that outlived teardown was released from the supervisor, "+ "so an ungraceful exit would leave it running forever"+ )+ finally:+ _kill(child.pid)+ child.wait(timeout=10)+++def test_no_pgids_is_a_no_op(monkeypatch):+ spawned = []+ monkeypatch.setattr(+ mcp_tool,+ "_spawn_death_supervisor",+ lambda: spawned.append(1) or _FakeSupervisor(),+ )++ mcp_tool._update_death_supervisor("register", [])++ assert spawned == []diff --git a/tests/tools/test_mcp_stdio_watchdog.py b/tests/tools/test_mcp_stdio_watchdog.pydeleted file mode 100644index 411695eea54..00000000000--- a/tests/tools/test_mcp_stdio_watchdog.py+++ /dev/null@@ -1,40 +0,0 @@-"""Contract tests for the direct POSIX stdio MCP child watchdog."""--import os-import sys--import pytest--from tools import mcp_stdio_watchdog, mcp_tool---def test_is_orphaned_is_false_while_direct_parent_is_unchanged():- original_ppid = 1234-- assert mcp_stdio_watchdog._is_orphaned(- original_ppid,- getppid=lambda: original_ppid,- ) is False--[email protected](os.name != "posix", reason="watchdog wrapping is POSIX-only")-def test_wrap_command_uses_stable_parent_pid_and_preserves_command_tail():- parent_pid = os.getpid()- command = "/opt/hermes/bin/mcp-server"- command_args = ["--label", "value with spaces", "--", "literal-tail"]-- wrapped_command, wrapped_args = mcp_tool._wrap_command_with_watchdog(- command,- command_args,- )-- assert wrapped_command == sys.executable- assert wrapped_args == [- os.path.join(os.path.dirname(mcp_tool.__file__), "mcp_stdio_watchdog.py"),- "--ppid",- str(parent_pid),- "--",- command,- *command_args,- ]- assert "--create-time" not in wrapped_argsdiff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex ada55426d2c..ecc72a69045 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -3446,9 +3446,9 @@ def _kill_process_tree(proc: "subprocess.Popen") -> None:descendants on both platforms.Fires SIGTERM then SIGKILL back-to-back with no grace period between- them (unlike ``tools/mcp_stdio_watchdog.py``'s ``_terminate_process_group``,- which waits between signals because it's reacting to a live daemon being- orphaned). By the time this is called, the caller has already burned its+ them (unlike ``tools/mcp_death_supervisor.py``'s ``_reap``, which waits+ between signals because it's reacting to a live daemon being orphaned).+ By the time this is called, the caller has already burned itsfull timeout budget waiting for a graceful exit — there's nothing to gainfrom waiting again here, only more delay on an already-timed-out call.@@ -3487,7 +3487,7 @@ def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:# on Windows), but resolve them defensively via getattr anyway so an# accidental future refactor that drops that guard degrades to a plain# kill() instead of AttributeError — same discipline as- # tools/mcp_stdio_watchdog.py's _terminate_process_group.+ # tools/mcp_death_supervisor.py's _reap.killpg = getattr(os, "killpg", None)if killpg is None: # windows-footgun: ok - non-POSIX fallbacktry:diff --git a/tools/mcp_death_supervisor.py b/tools/mcp_death_supervisor.pynew file mode 100644index 00000000000..22ede0ca739--- /dev/null+++ b/tools/mcp_death_supervisor.py@@ -0,0 +1,186 @@+#!/usr/bin/env python3+"""One parent-death supervisor per Hermes process, shared by all stdio MCP servers.++Why this exists+---------------+When Hermes dies without running its cleanup path (SIGKILL, OOM killer, a hard+crash), stdio MCP servers it spawned are reparented to init and keep running+forever. macOS has no ``PR_SET_PDEATHSIG``, so something has to outlive Hermes+and reap them.++The predecessor (``mcp_stdio_watchdog.py``) solved this with one CPython+*per MCP server*, wrapping each server command and polling ``getppid()`` every+two seconds. That costs ~10 MB of resident memory per server and detects death+up to one poll interval late. This module replaces the whole fleet of pollers+with a single supervisor per Hermes process:++* **Death detection is a blocking read on a pipe.** Hermes holds the only write+ end. When Hermes dies -- by any means, including SIGKILL -- the write end+ closes and the read returns EOF. Exact, instant, and free.+* **Servers are spawned unwrapped.** The MCP SDK already spawns stdio children+ with ``start_new_session=True``, so each one is its own process-group leader+ and ``killpg`` still reaches its descendants. Removing the wrapper also+ removes the signal-forwarding layer the wrapper needed to avoid inverting the+ bug it fixed.++Protocol (line-based, on stdin)+-------------------------------+ register <pgid>\n start reaping this process group on parent death+ unregister <pgid>\n stop reaping it (its server shut down cleanly)++On EOF the supervisor SIGTERMs every still-registered process group, waits a+short grace period, SIGKILLs the survivors, and exits. A registered group that+Hermes never unregistered *is* the orphan set, so a clean Hermes shutdown --+which unregisters as it tears each server down -- ends with nothing to kill.++Unparseable lines are ignored rather than fatal: a corrupted byte on the control+pipe must not cost us the reaping guarantee for every other server.+"""++from __future__ import annotations++import argparse+import os+import signal+import sys+import time++# Matches the grace period the per-server watchdog used before it escalated.+_TERM_GRACE_S = 3.0+# How often we re-check for survivors during that grace period.+_REAP_POLL_S = 0.1+# A command is "unregister <pgid>" -- around 20 characters. The cap only has to+# be generous enough for a legitimate line; see _serve for why it exists.+_MAX_LINE_CHARS = 256+++def _is_safe_target(pgid: int, *, own_pgid: int, parent_pgid: int) -> bool:+ """Return True if ``pgid`` is a process group we may signal.++ Defensive only -- Hermes already filters non-MCP children before it+ registers anything (see ``_filter_mcp_children`` in ``tools/mcp_tool.py``).+ But this process signals whole process *groups*, so a bad value here is+ unusually expensive: ``killpg(0, ...)`` signals our own group, and pgid 1+ is init. A caller bug should cost us one unreaped server, never the+ Hermes process tree or the session.+ """+ if pgid <= 1:+ return False+ if pgid == own_pgid or pgid == parent_pgid:+ return False+ return True+++def _reap(pgids: set[int]) -> None:+ """SIGTERM every group, then SIGKILL whatever is still alive.++ Every process-group call below is POSIX-only by construction: this whole+ module only ever runs as a child of ``_update_death_supervisor``, which+ returns early unless ``os.name == "posix"``, so the supervisor is never+ spawned on Windows in the first place.+ """+ if not pgids:+ return++ alive = set()+ for pgid in pgids:+ try:+ os.killpg(pgid, signal.SIGTERM) # windows-footgun: ok — POSIX-only process+ alive.add(pgid)+ except (ProcessLookupError, PermissionError, OSError):+ # Already gone, or not ours to signal. Either way, nothing to reap.+ pass++ deadline = time.monotonic() + _TERM_GRACE_S+ while alive and time.monotonic() < deadline:+ time.sleep(_REAP_POLL_S)+ for pgid in list(alive):+ try:+ # Signal 0 probes liveness: succeeds iff some member survives.+ os.killpg(pgid, 0) # windows-footgun: ok — POSIX-only process+ except (ProcessLookupError, PermissionError, OSError):+ alive.discard(pgid)++ for pgid in alive:+ try:+ os.killpg(pgid, signal.SIGKILL) # windows-footgun: ok — POSIX-only+ except (ProcessLookupError, PermissionError, OSError):+ pass+++def _serve(stream, *, own_pgid: int, parent_pgid: int) -> set[int]:+ """Read control lines until EOF; return the groups still registered.++ Reads are length-capped rather than newline-terminated. Iterating the+ stream instead lets a writer that never sends a newline grow this process+ without bound -- feeding it ``/dev/zero`` reached 15 GB before it was+ stopped. Nothing in Hermes can produce that today, but this process is the+ last line of defense against leaked servers, so it must not be the thing+ that dies under memory pressure. A line truncated by the cap fails to parse+ and is skipped; the remainder resyncs at the next newline.+ """+ registered: set[int] = set()+ while True:+ line = stream.readline(_MAX_LINE_CHARS)+ if not line:+ break # EOF: the parent is gone.+ if not line.endswith("\n"):+ # Truncated by the cap, or an unterminated tail at EOF. Either way+ # it is not a command we are willing to act on.+ continue+ parts = line.split()+ if len(parts) != 2:+ continue+ verb, raw = parts+ try:+ pgid = int(raw)+ except ValueError:+ continue+ if verb == "register":+ if _is_safe_target(pgid, own_pgid=own_pgid, parent_pgid=parent_pgid):+ registered.add(pgid)+ elif verb == "unregister":+ registered.discard(pgid)+ return registered+++def main(argv=None) -> int:+ parser = argparse.ArgumentParser(+ description="Reap registered process groups when the parent dies."+ )+ parser.add_argument(+ "--parent-pgid",+ type=int,+ required=True,+ help="Process group of the spawning Hermes process; never signalled.",+ )+ args = parser.parse_args(argv)++ # The parent may be torn down with killpg on its own group. We are spawned+ # with start_new_session=True precisely so that sweep cannot take us with+ # it before we have reaped -- assert that here rather than trust the caller.+ own_pgid = os.getpgid(0)+ if own_pgid == args.parent_pgid:+ print(+ "mcp_death_supervisor: refusing to run inside the parent's process "+ "group (a killpg of the parent would kill us before we can reap)",+ file=sys.stderr,+ )+ return 2++ # A dying parent's SIGINT/SIGHUP must not preempt the reap; the pipe's EOF+ # is our only shutdown signal. SIGHUP is POSIX-only, which is fine here --+ # this process is never spawned on Windows (see _reap's docstring).+ for sig in (signal.SIGINT, signal.SIGHUP): # windows-footgun: ok — POSIX-only process+ try:+ signal.signal(sig, signal.SIG_IGN)+ except (ValueError, OSError):+ pass++ registered = _serve(sys.stdin, own_pgid=own_pgid, parent_pgid=args.parent_pgid)+ _reap(registered)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/mcp_stdio_watchdog.py b/tools/mcp_stdio_watchdog.pydeleted file mode 100644index a39f36d6feb..00000000000--- a/tools/mcp_stdio_watchdog.py+++ /dev/null@@ -1,157 +0,0 @@-#!/usr/bin/env python3-"""Parent-death watchdog supervisor for stdio MCP subprocesses.--Problem this fixes (#TBD): a stdio MCP server (e.g. ``npx -y mcp-remote-<url>``) is spawned as a direct child of the Hermes process. Hermes's own-teardown path (``MCPServerTask.shutdown()`` / ``_kill_orphaned_mcp_children``-at final exit) reaps it cleanly on a *graceful* exit. But if the spawning-Hermes process dies hard — ``kill -9``, an OS-level crash, a force-quit of-the TUI/desktop app — that teardown code never runs, and the child (plus any-of its own descendants, e.g. mcp-remote's spawned ``node`` process) is-orphaned. macOS has no direct equivalent of Linux's-``prctl(PR_SET_PDEATHSIG)`` to make the kernel auto-kill a child when its-parent dies, so nothing reaps these until the next Hermes startup's opt-in-``_kill_orphaned_mcp_children()`` sweep — which only runs if something calls-it. Repeated ungraceful session restarts can pile up N orphaned processes,-all racing to hold the same upstream SSE session, producing errors like-"Invalid request parameters" / "Received request before initialization was-complete" on the *legitimate* new connection.--Fix: don't spawn the MCP server command directly. Spawn this supervisor-instead, which:- 1. execs the real command as its own child (own process group via- ``start_new_session``, so it doesn't inherit the supervisor's- controlling terminal weirdly and so we can killpg it cleanly);- 2. transparently passes stdin/stdout/stderr through — the MCP stdio- protocol talks directly over those pipes, so the supervisor must be a- no-op relay, not a bytes-in-the-middle proxy;- 3. runs a background thread that polls the direct POSIX parent identity:- compare current ``getppid()`` against the parent PID recorded when the- wrapper was created;- 4. the instant the original parent is gone, terminates the real child's- process group (SIGTERM, grace period, then SIGKILL) and exits.--This is intentionally a thin, standard-library-only script so it starts fast-and can't itself become a resource leak.--Usage (see ``tools/mcp_tool.py::_run_stdio``)::-- python3 -m tools.mcp_stdio_watchdog \\- --ppid <original_parent_pid> -- <real_command> <arg1> <arg2> ...-"""--from __future__ import annotations--import argparse-import os-import signal-import subprocess-import sys-import threading-import time--_POLL_INTERVAL_S = 2.0-_TERM_GRACE_S = 3.0---def _is_orphaned(original_ppid: int, getppid=os.getppid) -> bool:- """Return whether this process no longer has its original POSIX parent."""- return getppid() != original_ppid---def _terminate_process_group(proc: subprocess.Popen) -> None:- """Best-effort SIGTERM-then-SIGKILL of the child's process group.-- This module only ever runs on POSIX (the wrap site in tools/mcp_tool.py- gates on ``os.name == "posix"``), but guard the POSIX-only primitives- anyway so an accidental Windows import/execute degrades to a plain- child kill instead of AttributeError.- """- killpg = getattr(os, "killpg", None)- if killpg is None: # windows-footgun: ok — non-POSIX fallback- try:- proc.terminate()- proc.wait(timeout=_TERM_GRACE_S)- except (OSError, subprocess.TimeoutExpired):- proc.kill()- return- try:- pgid = os.getpgid(proc.pid)- except (ProcessLookupError, OSError):- return- sigkill = getattr(signal, "SIGKILL", signal.SIGTERM)- for sig in (signal.SIGTERM, sigkill):- try:- killpg(pgid, sig)- except (ProcessLookupError, PermissionError, OSError):- return- try:- proc.wait(timeout=_TERM_GRACE_S)- return- except subprocess.TimeoutExpired:- continue---def _watchdog_loop(proc: subprocess.Popen, original_ppid: int) -> None:- while proc.poll() is None:- if _is_orphaned(original_ppid):- _terminate_process_group(proc)- return- time.sleep(_POLL_INTERVAL_S)---def main(argv: list[str] | None = None) -> int:- parser = argparse.ArgumentParser(- description="Parent-death watchdog for a stdio MCP subprocess.",- )- parser.add_argument("--ppid", type=int, required=True)- parser.add_argument("command", nargs=argparse.REMAINDER)- args = parser.parse_args(argv)-- real_argv = list(args.command)- if real_argv and real_argv[0] == "--":- real_argv = real_argv[1:]- if not real_argv:- print("mcp_stdio_watchdog: no command given after '--'", file=sys.stderr)- return 2-- # New process group so we can killpg() the whole tree the real command- # may spawn (e.g. mcp-remote's own child `node` process), without- # touching our own group or the (already-gone) original parent's.- proc = subprocess.Popen(- real_argv,- stdin=sys.stdin,- stdout=sys.stdout,- stderr=sys.stderr,- start_new_session=True,- )-- # Because the real server lives in its OWN process group (above), the- # parent's graceful-shutdown killpg of *our* group no longer reaches it.- # Forward SIGTERM/SIGINT to the child's group so graceful teardown- # (`_kill_orphaned_mcp_children`, shutdown sweeps) still kills a wedged- # server that ignores stdin EOF — otherwise the watchdog wrap would- # invert the bug it fixes.- def _forward_shutdown(signum, frame): # noqa: ARG001- _terminate_process_group(proc)- sys.exit(128 + signum)-- signal.signal(signal.SIGTERM, _forward_shutdown)- signal.signal(signal.SIGINT, _forward_shutdown)-- watchdog = threading.Thread(- target=_watchdog_loop,- args=(proc, args.ppid),- daemon=True,- )- watchdog.start()-- try:- return proc.wait()- except KeyboardInterrupt:- _terminate_process_group(proc)- return 130---if __name__ == "__main__":- sys.exit(main())diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex 01e7d9b3db0..130014ec579 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -1073,32 +1073,100 @@ def _resolve_stdio_command(command: str, env: dict) -> tuple[str, dict]:return resolved_command, resolved_env-def _wrap_command_with_watchdog(command: str, args: list) -> tuple[str, list]:- """Wrap a stdio MCP server command in the parent-death watchdog supervisor.+# ---------------------------------------------------------------------------+# Shared parent-death supervisor+# ---------------------------------------------------------------------------+# If this Hermes process dies without running its cleanup path (kill -9, OOM,+# crash, force-quit), stdio MCP children reparent to init and run forever.+# macOS has no PR_SET_PDEATHSIG, so something has to outlive us and reap them.+#+# We keep ONE supervisor process for all stdio servers and tell it which process+# groups to reap over a pipe. It detects our death as EOF on that pipe -- exact+# and instant -- rather than by polling getppid(). This replaced a design that+# wrapped every server command in its own poller, which cost ~10 MB resident per+# server (measured 9.8 MB physical footprint on macOS/arm64) and needed a signal+# forwarding layer, because wrapping put the real server in a different session+# from the pgid we tracked for killpg. See tools/mcp_death_supervisor.py.+#+# POSIX-only (relies on process groups), matching the platform scope of the+# killpg-based orphan cleanup below.+_death_supervisor = None # Optional[subprocess.Popen]+_death_supervisor_lock = threading.Lock()+# Process groups the supervisor is currently reaping on our behalf. Replayed+# verbatim if the supervisor has to be respawned, so a respawn never silently+# drops coverage for servers that are still running.+_supervised_pgids: set = set()+++def _spawn_death_supervisor():+ """Start the shared supervisor, or return None if it cannot be started."""+ import subprocess++ supervisor = os.path.join(+ os.path.dirname(os.path.abspath(__file__)), "mcp_death_supervisor.py"+ )+ try:+ # start_new_session=True is load-bearing, not hygiene: shutdown paths+ # killpg this process's own group, which would kill the supervisor+ # before it could reap anything.+ return subprocess.Popen(+ [sys.executable, supervisor, "--parent-pgid", str(os.getpgid(0))],+ stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL,+ stderr=_get_mcp_stderr_log(),+ start_new_session=True,+ close_fds=True,+ text=True,+ )+ except Exception:+ # Never let supervisor bookkeeping failure block a real MCP connection.+ # The graceful shutdown paths still reap normally; we only lose the+ # ungraceful-exit safety net.+ logger.debug("Could not start the MCP parent-death supervisor", exc_info=True)+ return None+- On POSIX, the watchdog records this process's PID and later detects parent- death directly through ``getppid()``. Returns the (command, args) unchanged- on non-POSIX platforms or if the PID cannot be read.+def _update_death_supervisor(verb: str, pgids) -> None:+ """Register or unregister process groups with the shared supervisor.++ ``verb`` is ``"register"`` or ``"unregister"``. Failures are swallowed:+ losing the ungraceful-exit safety net must never fail a live MCP session."""if os.name != "posix":- # Relies on process groups (os.getpgid/os.killpg); no POSIX- # equivalent wired up here yet, matching the existing killpg-based- # orphan cleanup's platform scope (Windows falls back to plain- # os.kill there too).- return command, args- try:- my_pid = os.getpid()- except Exception:- # Never let watchdog bookkeeping failure block a real MCP connection.- return command, args- watchdog_args = [- os.path.join(os.path.dirname(os.path.abspath(__file__)), "mcp_stdio_watchdog.py"),- "--ppid", str(my_pid),- "--",- command,- *args,- ]- return sys.executable, watchdog_args+ return+ wanted = {int(pgid) for pgid in pgids}+ if not wanted:+ return++ global _death_supervisor+ with _death_supervisor_lock:+ if verb == "register":+ _supervised_pgids.update(wanted)+ else:+ _supervised_pgids.difference_update(wanted)++ proc = _death_supervisor+ if proc is None or proc.poll() is not None:+ if verb == "unregister" and proc is None:+ # Nothing was ever registered, so there is nothing to tell.+ return+ proc = _spawn_death_supervisor()+ _death_supervisor = proc+ if proc is None:+ return+ # A fresh supervisor knows nothing. Replay live coverage, which+ # already reflects this call's mutation.+ payload = "".join(f"register {pgid}\n" for pgid in _supervised_pgids)+ else:+ payload = "".join(f"{verb} {pgid}\n" for pgid in wanted)++ try:+ proc.stdin.write(payload)+ proc.stdin.flush()+ except (BrokenPipeError, ValueError, OSError):+ # It exited between poll() and write(). Drop it so the next call+ # respawns and replays, rather than writing into a dead pipe.+ _death_supervisor = None# ---------------------------------------------------------------------------@@ -3243,9 +3311,10 @@ class MCPServerTask:# it with a wall-clock timeout so a stalled SSL handshake can't freeze# MCP discovery / gateway startup (#29184). The check is fail-open, so# on timeout we log and proceed rather than blocking indefinitely.- # NOTE: must run against the REAL command/args — the watchdog wrap- # below rewrites argv to `python -m tools.mcp_stdio_watchdog …`,- # which would silently turn the preflight into a no-op.+ # NOTE: must run against the REAL command/args. Anything that rewrites+ # argv to point at a wrapper or a resolved binary has to happen AFTER+ # this call, or the preflight silently inspects the wrapper instead of+ # the package and becomes a no-op.from tools.osv_check import check_package_for_malwaretry:malware_error = await asyncio.wait_for(@@ -3264,18 +3333,6 @@ class MCPServerTask:f"MCP server '{self.name}': {malware_error}")- # Wrap the real command in a parent-death watchdog supervisor so an- # ungraceful exit of this Hermes process (kill -9, crash, force-quit)- # can't leave the stdio MCP child (and its own descendants, e.g.- # mcp-remote's spawned `node`) running forever. On a clean exit,- # MCPServerTask.shutdown() / _kill_orphaned_mcp_children() still do- # the reaping as before -- this only covers the case where that code- # never gets to run. POSIX-only (relies on process groups); no-op- # elsewhere, matching existing killpg-based cleanup's platform scope.- # Applied AFTER the OSV preflight so the check inspects the real- # package, not the watchdog wrapper.- command, args = _wrap_command_with_watchdog(command, args)-server_params = StdioServerParameters(command=command,args=args,@@ -3365,6 +3422,14 @@ class MCPServerTask:_pid,exc_info=True,)+ # Hand the pgroups to the shared parent-death supervisor so+ # an ungraceful exit of this process (kill -9, crash,+ # force-quit) can't leave this server -- or its own+ # descendants, e.g. mcp-remote's spawned `node` -- running+ # forever. The graceful paths (MCPServerTask.shutdown,+ # _kill_orphaned_mcp_children) still reap as before; this+ # only covers the case where they never get to run.+ _update_death_supervisor("register", new_pgids.values())# Track the spawned children on the connection object for# fast-fail of in-flight calls when the subprocess dies# (#81995).@@ -3417,6 +3482,11 @@ class MCPServerTask:if new_pids:from gateway.status import _pid_exists_killpg = getattr(os, "killpg", None)+ # Groups with nothing left alive; the supervisor is told to+ # forget them after the lock is released. Groups that ARE still+ # alive stay registered on purpose, so the supervisor still+ # reaps them if this process dies before the orphan sweep runs.+ released_pgids: list = []with _lock:for _pid in new_pids:_stdio_pids.pop(_pid, None)@@ -3442,7 +3512,10 @@ class MCPServerTask:else:# Nothing left to reap — drop the pgid entry so# PID-reuse can't surface stale pgroup state later.- _stdio_pgids.pop(pid, None)+ dropped = _stdio_pgids.pop(pid, None)+ if dropped is not None:+ released_pgids.append(dropped)+ _update_death_supervisor("unregister", released_pgids)# Content types a real MCP Streamable-HTTP endpoint may return on the# initial POST/GET. Anything else on a 2xx response means the URL is not@@ -8896,6 +8969,10 @@ def _kill_orphaned_mcp_children(pid, server_name,)+ # These groups are reaped. Release them last, so a crash partway through+ # the SIGTERM/SIGKILL dance still leaves the supervisor holding them.+ _update_death_supervisor("unregister", pgids.values())+def _stop_mcp_loop_if_idle() -> bool:"""Stop the MCP loop only when no registered server still owns it.