π The fast, Pythonic way to build MCP servers and clients.
Raise startup failures from run_server_async instead of hanging (#5340)
Asem ahmedf0ed4fb6da40
diff --git a/fastmcp_slim/fastmcp/utilities/tests.py b/fastmcp_slim/fastmcp/utilities/tests.pyindex e787bc3c9..f6817bc51 100644--- a/fastmcp_slim/fastmcp/utilities/tests.py+++ b/fastmcp_slim/fastmcp/utilities/tests.py@@ -236,8 +236,14 @@ async def run_server_async())- # Wait for server lifespan to be ready- await server._started.wait()+ # 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")# 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.diff --git a/tests/utilities/test_tests.py b/tests/utilities/test_tests.pyindex d5fc24c21..10b284ba9 100644--- a/tests/utilities/test_tests.py+++ b/tests/utilities/test_tests.py@@ -1,10 +1,16 @@+from collections.abc import AsyncIterator+from contextlib import asynccontextmanagerfrom unittest.mock import AsyncMock, MagicMock, patchimport pytestimport fastmcp-from fastmcp import FastMCP-from fastmcp.utilities.tests import HeadlessOAuth, temporary_settings+from fastmcp import Client, FastMCP+from fastmcp.utilities.tests import (+ HeadlessOAuth,+ run_server_async,+ temporary_settings,+)class TestTemporarySettings:@@ -43,6 +49,27 @@ class TestTransportSetting:mock_stdio.assert_called_once()+class TestRunServerAsync:+ async def test_yields_url_of_running_server(self):+ mcp = FastMCP("test")++ async with run_server_async(mcp) as url:+ async with Client(url) as client:+ assert await client.list_tools() == []++ async def test_startup_failure_raises(self):+ @asynccontextmanager+ async def failing_lifespan(server: FastMCP) -> AsyncIterator[None]:+ raise RuntimeError("database unavailable")+ yield++ mcp = FastMCP("test", lifespan=failing_lifespan)++ with pytest.raises(RuntimeError, match="database unavailable"):+ async with run_server_async(mcp):+ pass++class TestHeadlessOAuthCallbackHandler:"""Regression tests for #4056: blank query values must survive parse_qs.