# Albedo-owned MCP stdio launcher: no shell, scoped cwd, silent stderr. It # stays the server's parent, in a process group of the server's own, so that # closing its stdin ends the server even when the server ignores EOF: the # server gets GRACE seconds, then SIGTERM, then SIGKILL of its whole group. import os import signal import subprocess import sys import threading GRACE = 2.0 _, cwd, command, *arguments = sys.argv if cwd: os.environ["PWD"] = cwd server = subprocess.Popen( [command, *arguments], executable=command, stdin=subprocess.PIPE, stderr=subprocess.DEVNULL, cwd=cwd or None, start_new_session=True, ) def signal_group(sig): try: os.killpg(server.pid, sig) except (ProcessLookupError, PermissionError): pass def exit_with_server(): status = server.wait() # Whatever the server left running in its group goes with it. signal_group(signal.SIGKILL) os._exit(status if status >= 0 else 128 - status) threading.Thread(target=exit_with_server, daemon=True).start() assert server.stdin is not None try: while chunk := os.read(0, 65536): server.stdin.write(chunk) server.stdin.flush() except (BrokenPipeError, OSError): pass try: server.stdin.close() except BrokenPipeError: pass for sig in (signal.SIGTERM, signal.SIGKILL): try: server.wait(GRACE) break except subprocess.TimeoutExpired: signal_group(sig) server.wait()