Skip to content

Commit b3920b0

Browse files
authored
fix(server): exit when MCP parent process disappears (#217)
Start a parent-death watchdog before server setup so conda-meta-mcp terminates itself if the launching MCP host/proxy process exits without graceful shutdown. This prevents stale stdio or streamable-http server processes from surviving client shutdown and holding ports such as 4042. This is a defensive workaround for upstream lifecycle gaps where MCP hosts or proxy runners may forcefully terminate the stdio parent without cleaning up descendants. Related upstream issues: - modelcontextprotocol/python-sdk#526 - modelcontextprotocol/python-sdk#2231 - PrefectHQ/fastmcp#353 - anthropics/claude-code#1935 - modelcontextprotocol/typescript-sdk#2023 - modelcontextprotocol/typescript-sdk#2002 - microsoft/vscode#316266
1 parent 1a21244 commit b3920b0

2 files changed

Lines changed: 195 additions & 0 deletions

File tree

‎conda_meta_mcp/server.py‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
import asyncio
44
import contextlib
5+
import ctypes
56
import importlib
67
import os
78
import sys
9+
import threading
10+
import time
811
from typing import TYPE_CHECKING
912

1013
from fastmcp import FastMCP
@@ -13,10 +16,90 @@
1316
import argparse
1417

1518
SERVICE_NAME = "Conda ECO System Meta Data MCP"
19+
_PARENT_WATCHDOG_ENV = "CONDA_META_MCP_PARENT_WATCHDOG"
20+
_PARENT_PID_ENV = "CONDA_META_MCP_PARENT_PID"
1621

1722
_periodic_cleanup_task: asyncio.Task | None = None
1823

1924

25+
def _env_enabled(name: str, *, default: bool) -> bool:
26+
value = os.getenv(name)
27+
if value is None:
28+
return default
29+
return value.strip().lower() not in {"", "0", "false", "no", "off"}
30+
31+
32+
def _parent_pid() -> int:
33+
configured_pid = os.getenv(_PARENT_PID_ENV)
34+
if configured_pid:
35+
with contextlib.suppress(ValueError):
36+
return int(configured_pid)
37+
return os.getppid()
38+
39+
40+
def _wait_for_process_exit_windows(pid: int) -> bool:
41+
"""Wait for the recorded Windows parent process to exit."""
42+
win_dll = getattr(ctypes, "WinDLL", None)
43+
if win_dll is None: # pragma: no cover - defensive for non-Windows tests
44+
return False
45+
46+
kernel32 = win_dll("kernel32", use_last_error=True)
47+
kernel32.OpenProcess.argtypes = (ctypes.c_uint32, ctypes.c_int, ctypes.c_uint32)
48+
kernel32.OpenProcess.restype = ctypes.c_void_p
49+
kernel32.WaitForSingleObject.argtypes = (ctypes.c_void_p, ctypes.c_uint32)
50+
kernel32.WaitForSingleObject.restype = ctypes.c_uint32
51+
kernel32.CloseHandle.argtypes = (ctypes.c_void_p,)
52+
kernel32.CloseHandle.restype = ctypes.c_int
53+
54+
handle = kernel32.OpenProcess(0x00100000, False, pid) # SYNCHRONIZE
55+
if not handle:
56+
return True
57+
58+
try:
59+
wait_result = kernel32.WaitForSingleObject(handle, 0xFFFFFFFF) # INFINITE
60+
finally:
61+
kernel32.CloseHandle(handle)
62+
63+
return wait_result == 0 # WAIT_OBJECT_0
64+
65+
66+
def _wait_for_parent_exit(pid: int) -> bool:
67+
if os.name == "nt":
68+
return _wait_for_process_exit_windows(pid)
69+
70+
while os.getppid() == pid:
71+
time.sleep(1)
72+
return True
73+
74+
75+
def _exit_process(code: int) -> None:
76+
os._exit(code)
77+
78+
79+
def _parent_watchdog_worker(
80+
pid: int,
81+
wait_for_process_exit=_wait_for_parent_exit,
82+
exit_process=_exit_process,
83+
) -> None:
84+
if wait_for_process_exit(pid):
85+
exit_process(0)
86+
87+
88+
def _start_parent_watchdog() -> threading.Thread | None:
89+
"""Stop orphaned servers when MCP hosts or proxy parents disappear."""
90+
if not _env_enabled(_PARENT_WATCHDOG_ENV, default=True):
91+
return None
92+
93+
thread = threading.Thread(
94+
target=_parent_watchdog_worker,
95+
args=(_parent_pid(),),
96+
name="conda-meta-mcp-parent-watchdog",
97+
daemon=True,
98+
)
99+
thread.start()
100+
return thread
101+
102+
20103
def _build_code_mode_transform():
21104
code_mode = importlib.import_module("fastmcp.experimental.transforms.code_mode")
22105

@@ -51,6 +134,7 @@ def setup_run(subparser: argparse._SubParsersAction):
51134
def run_cmd(args):
52135
log_level = "DEBUG" if args.verbose else "INFO"
53136
os.environ["FASTMCP_LOG_LEVEL"] = log_level
137+
_start_parent_watchdog()
54138
mcp = setup_server(args.code)
55139

56140
run_kwargs = {"transport": args.transport, "show_banner": False}

‎tests/test_server.py‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,115 @@ def __init__(self, discovery_tools, sandbox_provider):
8181
}
8282

8383

84+
def test_parent_watchdog_worker__exits_after_parent_exit():
85+
calls = {}
86+
87+
def wait_for_process_exit(pid):
88+
calls["pid"] = pid
89+
return True
90+
91+
def exit_process(code):
92+
calls["exit_code"] = code
93+
94+
server._parent_watchdog_worker(123, wait_for_process_exit, exit_process)
95+
96+
assert calls == {"pid": 123, "exit_code": 0}
97+
98+
99+
def test_parent_watchdog_worker__does_not_exit_if_parent_wait_unavailable():
100+
calls = {}
101+
102+
def wait_for_process_exit(pid):
103+
calls["pid"] = pid
104+
return False
105+
106+
def exit_process(code):
107+
calls["exit_code"] = code
108+
109+
server._parent_watchdog_worker(123, wait_for_process_exit, exit_process)
110+
111+
assert calls == {"pid": 123}
112+
113+
114+
def test_wait_for_parent_exit__returns_after_parent_changes(monkeypatch):
115+
parent_pids = iter([123, 1])
116+
117+
monkeypatch.setattr(server.os, "name", "posix")
118+
monkeypatch.setattr(server.os, "getppid", lambda: next(parent_pids))
119+
monkeypatch.setattr(server.time, "sleep", lambda seconds: None)
120+
121+
assert server._wait_for_parent_exit(123) is True
122+
123+
124+
def test_start_parent_watchdog__starts(monkeypatch):
125+
calls = {}
126+
127+
class FakeThread:
128+
def __init__(self, *, target, args, name, daemon):
129+
calls["target"] = target
130+
calls["args"] = args
131+
calls["name"] = name
132+
calls["daemon"] = daemon
133+
134+
def start(self):
135+
calls["started"] = True
136+
137+
monkeypatch.setattr(server, "_parent_pid", lambda: 123)
138+
monkeypatch.setattr(server.threading, "Thread", FakeThread)
139+
140+
thread = server._start_parent_watchdog()
141+
142+
assert isinstance(thread, FakeThread)
143+
assert calls == {
144+
"target": server._parent_watchdog_worker,
145+
"args": (123,),
146+
"name": "conda-meta-mcp-parent-watchdog",
147+
"daemon": True,
148+
"started": True,
149+
}
150+
151+
152+
def test_start_parent_watchdog__skips_when_disabled(monkeypatch):
153+
monkeypatch.setenv("CONDA_META_MCP_PARENT_WATCHDOG", "0")
154+
155+
assert server._start_parent_watchdog() is None
156+
157+
158+
def test_run_cmd__starts_parent_watchdog_before_setup(monkeypatch):
159+
calls = {}
160+
order = []
161+
162+
class Dummy:
163+
def run(self, **kw):
164+
calls["kw"] = kw
165+
166+
def fake_start_watchdog():
167+
order.append("watchdog")
168+
169+
def fake_setup_server(code=False):
170+
order.append("setup")
171+
return Dummy()
172+
173+
monkeypatch.setattr(server, "setup_server", fake_setup_server)
174+
monkeypatch.setattr(server, "_start_parent_watchdog", fake_start_watchdog)
175+
176+
server.run_cmd(
177+
types.SimpleNamespace(
178+
verbose=False,
179+
code=False,
180+
transport="streamable-http",
181+
port=4042,
182+
)
183+
)
184+
185+
assert order == ["watchdog", "setup"]
186+
assert calls["kw"] == {
187+
"transport": "streamable-http",
188+
"show_banner": False,
189+
"port": 4042,
190+
}
191+
192+
84193
def test_run_cmd(monkeypatch):
85194
calls = {}
86195

@@ -94,6 +203,7 @@ def fake_setup_server(code=False):
94203
return Dummy()
95204

96205
monkeypatch.setattr(server, "setup_server", fake_setup_server)
206+
monkeypatch.setattr(server, "_start_parent_watchdog", lambda: None)
97207
monkeypatch.delenv("FASTMCP_LOG_LEVEL", raising=False)
98208
server.run_cmd(types.SimpleNamespace(verbose=True, code=False, transport="stdio", port=None))
99209
assert calls["setup_called"]
@@ -110,6 +220,7 @@ def run(self, **kw):
110220
calls["kw"] = kw
111221

112222
monkeypatch.setattr(server, "setup_server", lambda code=False: Dummy())
223+
monkeypatch.setattr(server, "_start_parent_watchdog", lambda: None)
113224
server.run_cmd(
114225
types.SimpleNamespace(
115226
verbose=False,

0 commit comments

Comments
 (0)