π The fast, Pythonic way to build MCP servers and clients.
Report an unbindable OAuth callback port instead of SystemExit (#5692)
Asem ahmed1f9ba3e0c30f
diff --git a/fastmcp_slim/fastmcp/client/auth/oauth.py b/fastmcp_slim/fastmcp/client/auth/oauth.pyindex 81391a9c1..884996fdd 100644--- a/fastmcp_slim/fastmcp/client/auth/oauth.py+++ b/fastmcp_slim/fastmcp/client/auth/oauth.py@@ -423,9 +423,20 @@ class OAuth(OAuthClientProvider):result_ready=result_ready,)+ async def serve() -> None:+ try:+ await server.serve()+ except SystemExit as exc:+ # uvicorn exits the process when it cannot bind its port+ raise OSError(+ "OAuth callback server could not start on "+ f"http://{self._callback_host}:{self.redirect_port}; "+ "is the port already in use?"+ ) from exc+# Run server until response is received with timeout logicasync with anyio.create_task_group() as tg:- tg.start_soon(server.serve)+ tg.start_soon(serve)logger.info(f"π§ OAuth callback server started on http://{self._callback_host}:{self.redirect_port}")diff --git a/tests/client/auth/test_oauth_client.py b/tests/client/auth/test_oauth_client.pyindex b3687c393..4cb3f1b81 100644--- a/tests/client/auth/test_oauth_client.py+++ b/tests/client/auth/test_oauth_client.py@@ -230,6 +230,31 @@ async def test_oauth_callback_handler_propagates_iss_to_authorization_code_resulassert result.iss == "https://issuer.example.com"+async def test_oauth_callback_port_in_use_fails_the_connection(+ streamable_http_server: str,+):+ """A callback port that cannot be bound fails the connection with a clear+ error instead of leaking uvicorn's SystemExit out of the client."""+ with socket.socket() as busy:+ busy.bind(("127.0.0.1", 0))+ busy.listen()+ oauth = OAuth(+ mcp_url=streamable_http_server,+ callback_host="127.0.0.1",+ callback_port=busy.getsockname()[1],+ )+ client = Client(+ transport=StreamableHttpTransport(streamable_http_server), auth=oauth+ )++ with (+ patch.object(oauth_module.webbrowser, "open"),+ pytest.raises(RuntimeError, match="callback server could not start"),+ ):+ async with client:+ pass++class TestOAuthClientUrlHandling:"""Tests for OAuth client URL handling (issue #2573)."""