Something went wrong. Try again.
mirror of github.com/PrefectHQ/fastmcp
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041"""Serve server.py over streamable HTTP in a subprocess for the length of a `with` block."""
import osimport socketimport subprocessimport sysimport timefrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom pathlib import Path
SERVER = Path(__file__).with_name("server.py")
def free_port() -> int: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1]
@contextmanagerdef http_server(python: list[str]) -> Iterator[str]: port = free_port() proc = subprocess.Popen([*python, str(SERVER), "http", str(port)], env=os.environ) try: deadline = time.monotonic() + 30 while time.monotonic() < deadline: if proc.poll() is not None: sys.exit(f"server exited with {proc.returncode}") try: socket.create_connection(("127.0.0.1", port), timeout=0.2).close() break except OSError: time.sleep(0.1) else: sys.exit("server did not start listening within 30s") yield f"http://127.0.0.1:{port}/mcp" finally: proc.terminate() proc.wait(timeout=10)