Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Clean up run_server_async when startup exits early (#5469)

Yuefeng Shi5baeacfe20ec
diff --git a/fastmcp_slim/fastmcp/utilities/tests.py b/fastmcp_slim/fastmcp/utilities/tests.py
index f6817bc51..abbe0c190 100644
--- a/fastmcp_slim/fastmcp/utilities/tests.py
+++ b/fastmcp_slim/fastmcp/utilities/tests.py
@@ -151,6 +151,31 @@ def run_server_in_process(
raise RuntimeError("Server process failed to terminate even after kill")
+async def _wait_for_server_started(
+ server: FastMCP, server_task: asyncio.Task[None]
+) -> None:
+ """Wait for startup or surface lifespan / transport failures immediately."""
+ started_wait = asyncio.create_task(server._started.wait())
+ try:
+ done, _ = await asyncio.wait(
+ {started_wait, server_task},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if server_task in done:
+ started_wait.cancel()
+ with suppress(asyncio.CancelledError):
+ await started_wait
+ exc = server_task.exception()
+ if exc is not None:
+ raise exc
+ raise RuntimeError("Server exited before signalling startup completion")
+ finally:
+ if not started_wait.done():
+ started_wait.cancel()
+ with suppress(asyncio.CancelledError):
+ await started_wait
+
+
async def _wait_for_port(host: str, port: int, timeout: float = 5.0) -> None:
"""Poll until a TCP connection to `host:port` is accepted, or raise on timeout."""
deadline = time.monotonic() + timeout
@@ -225,7 +250,6 @@ async def run_server_async(
if port is None:
port = find_available_port()
- # Start server as a background task
server_task = asyncio.create_task(
server.run_http_async(
host=host,
@@ -236,23 +260,15 @@ async def run_server_async(
)
)
- # Wait for server lifespan to be ready, unless the server task ends first:
- # a server that fails to start will never set `_started`.
- started = asyncio.create_task(server._started.wait())
- await asyncio.wait({started, server_task}, return_when=asyncio.FIRST_COMPLETED)
- if not started.done():
- started.cancel()
- await server_task
- raise RuntimeError("Server exited before it finished starting")
+ try:
+ await _wait_for_server_started(server, server_task)
- # The lifespan completing does not guarantee uvicorn has bound the port yet, so
- # poll until the socket accepts a connection rather than guessing at a sleep.
- await _wait_for_port(host, port)
+ # The lifespan completing does not guarantee uvicorn has bound the port yet, so
+ # poll until the socket accepts a connection rather than guessing at a sleep.
+ await _wait_for_port(host, port)
- try:
yield f"http://{host}:{port}{path}"
finally:
- # Cleanup: cancel the task with timeout to avoid hanging on Windows
server_task.cancel()
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
await asyncio.wait_for(server_task, timeout=2.0)
diff --git a/tests/utilities/test_run_server_async_startup.py b/tests/utilities/test_run_server_async_startup.py
new file mode 100644
index 000000000..66cafba3e
--- /dev/null
+++ b/tests/utilities/test_run_server_async_startup.py
@@ -0,0 +1,91 @@
+"""Regression tests for run_server_async startup failure handling."""
+
+import asyncio
+from contextlib import asynccontextmanager, suppress
+from typing import Any
+
+import pytest
+
+import fastmcp.utilities.tests as helpers
+from fastmcp import FastMCP
+from fastmcp.utilities.tests import run_server_async
+
+
+@asynccontextmanager
+async def failing_lifespan(_server):
+ raise RuntimeError("database unavailable")
+ yield # pragma: no cover
+
+
+async def test_run_server_async_raises_when_lifespan_fails():
+ mcp = FastMCP("demo", lifespan=failing_lifespan)
+
+ with pytest.raises(RuntimeError, match="database unavailable"):
+ async with run_server_async(mcp):
+ pass
+
+
+async def test_cancelled_startup_cleans_server(monkeypatch):
+ mcp = FastMCP("startup-cancellation")
+ entered = asyncio.Event()
+ stopped = asyncio.Event()
+ server_task = None
+
+ async def run(**kwargs: Any) -> None:
+ nonlocal server_task
+ server_task = asyncio.current_task()
+ entered.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ stopped.set()
+
+ monkeypatch.setattr(mcp, "run_http_async", run)
+
+ async def enter() -> None:
+ async with run_server_async(mcp):
+ pass
+
+ task = asyncio.create_task(enter())
+ await entered.wait()
+ task.cancel()
+ try:
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert stopped.is_set()
+ finally:
+ if server_task is not None and not server_task.done():
+ server_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await server_task
+
+
+async def test_port_wait_failure_cleans_server(monkeypatch):
+ mcp = FastMCP("port-failure")
+ stopped = asyncio.Event()
+ server_task = None
+
+ async def run(**kwargs: Any) -> None:
+ nonlocal server_task
+ server_task = asyncio.current_task()
+ mcp._started.set()
+ try:
+ await asyncio.Event().wait()
+ finally:
+ stopped.set()
+
+ async def fail_port(*args: Any, **kwargs: Any) -> None:
+ raise RuntimeError("port unavailable")
+
+ monkeypatch.setattr(mcp, "run_http_async", run)
+ monkeypatch.setattr(helpers, "_wait_for_port", fail_port)
+ try:
+ with pytest.raises(RuntimeError, match="port unavailable"):
+ async with run_server_async(mcp):
+ pass
+ assert stopped.is_set()
+ finally:
+ if server_task is not None and not server_task.done():
+ server_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await server_task