Something went wrong. Try again.
forked from okami.mom/albedo
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Launch an MCP stdio server and supervise its process group.
When the launcher reaches EOF, the server gets GRACE seconds to exit beforeSIGTERM, then another GRACE seconds before SIGKILL. The launcher's exit statusmirrors the server's."""
import contextlibimport osimport signalimport subprocessimport sysimport threading
GRACE = 2.0
def signal_group(server: subprocess.Popen[bytes], sig: signal.Signals) -> None: with contextlib.suppress(ProcessLookupError, PermissionError): os.killpg(server.pid, sig)
def exit_with_server(server: subprocess.Popen[bytes]) -> None: status = server.wait() # Whatever the server left running in its group goes with it. signal_group(server, signal.SIGKILL) os._exit(status if status >= 0 else 128 - status)
def main(argv: list[str]) -> None: _, cwd, command, *arguments = 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, ) watcher = threading.Thread(target=exit_with_server, args=(server,), daemon=True) watcher.start()
assert server.stdin is not None with contextlib.suppress(OSError): while chunk := os.read(0, 65536): server.stdin.write(chunk) server.stdin.flush() with contextlib.suppress(BrokenPipeError): server.stdin.close() for sig in (signal.SIGTERM, signal.SIGKILL): try: server.wait(GRACE) break except subprocess.TimeoutExpired: signal_group(server, sig) # The watcher cleans up the group and publishes the server's exit status. watcher.join()
if __name__ == "__main__": main(sys.argv)