π The fast, Pythonic way to build MCP servers and clients.
Treat upstream HTTP errors from OpenAPI tools as HTTP status errors (#5308)
Asem ahmedcf9d864ffde2
diff --git a/fastmcp_slim/fastmcp/server/providers/openapi/components.py b/fastmcp_slim/fastmcp/server/providers/openapi/components.pyindex bd25d5bc7..95b0b4d32 100644--- a/fastmcp_slim/fastmcp/server/providers/openapi/components.py+++ b/fastmcp_slim/fastmcp/server/providers/openapi/components.py@@ -60,7 +60,12 @@ _DEFAULT_MIME_TYPE = "application/json"def _raise_for_status(response: httpx2.Response) -> None:- """Raise an OpenAPI-formatted error without relying on client exception types."""+ """Raise an OpenAPI-formatted error without relying on client exception types.++ The error is an `httpx2.HTTPStatusError` whatever library the client+ belongs to, so the server can recognize an upstream error response by its+ status code.+ """if 200 <= response.status_code < 300:return@@ -71,7 +76,9 @@ def _raise_for_status(response: httpx2.Response) -> None:except (json.JSONDecodeError, ValueError):if response.text:error_message += f" - {response.text}"- raise ValueError(error_message)+ raise httpx2.HTTPStatusError(+ error_message, request=response.request, response=response+ )async def _send_request(diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.pyindex ba4ce6965..9a2a6329a 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -1510,10 +1510,15 @@ class FastMCP(name,)raise- logger.exception(f"Error calling tool {name!r}")+ # An upstream HTTP error response is an answer from the+ # upstream API, not a crash in the tool: skip the traceback.+ status_code = get_http_status_code(e)+ logger.error(+ f"Error calling tool {name!r}", exc_info=status_code is None+ )# Handle actionable errors that should reach the LLM# even when masking is enabled- if get_http_status_code(e) == 429:+ if status_code == 429:raise ToolError("Rate limited by upstream API, please retry later") from ediff --git a/tests/server/providers/openapi/test_http_errors.py b/tests/server/providers/openapi/test_http_errors.pynew file mode 100644index 000000000..e27920407--- /dev/null+++ b/tests/server/providers/openapi/test_http_errors.py@@ -0,0 +1,133 @@+"""Upstream HTTP error responses from OpenAPI components."""++import logging++import httpx2+import pytest+from mcp_types import TextContent++from fastmcp import Client, FastMCP+from fastmcp.exceptions import ResourceError+from fastmcp.server.providers.openapi.routing import MCPType, RouteMap++SPEC = {+ "openapi": "3.1.0",+ "info": {"title": "Items API", "version": "1.0"},+ "servers": [{"url": "https://api.example.test"}],+ "paths": {+ "/items/{item_id}": {+ "get": {+ "operationId": "get_item",+ "parameters": [+ {+ "name": "item_id",+ "in": "path",+ "required": True,+ "schema": {"type": "string"},+ }+ ],+ "responses": {"200": {"description": "OK"}},+ }+ }+ },+}++RESOURCE_SPEC = {+ "openapi": "3.1.0",+ "info": {"title": "Items API", "version": "1.0"},+ "servers": [{"url": "https://api.example.test"}],+ "paths": {+ "/items": {+ "get": {+ "operationId": "list_items",+ "responses": {"200": {"description": "OK"}},+ }+ }+ },+}+++def _upstream(status: int) -> httpx2.AsyncClient:+ def respond(request: httpx2.Request) -> httpx2.Response:+ return httpx2.Response(status, json={"detail": "nope"})++ return httpx2.AsyncClient(+ base_url="https://api.example.test",+ transport=httpx2.MockTransport(respond),+ )+++async def _call_get_item(server: FastMCP) -> str:+ async with Client(server) as client:+ result = await client.call_tool(+ "get_item", {"item_id": "x1"}, raise_on_error=False+ )+ assert result.is_error+ assert isinstance(result.content[0], TextContent)+ return result.content[0].text+++ ("status", "reason"),+ [(401, "Unauthorized"), (404, "Not Found"), (500, "Internal Server Error")],+)+async def test_http_error_is_logged_without_traceback(+ status: int, reason: str, caplog: pytest.LogCaptureFixture+) -> None:+ async with _upstream(status) as http_client:+ server = FastMCP.from_openapi(openapi_spec=SPEC, client=http_client)+ with caplog.at_level(logging.DEBUG, logger="fastmcp.server.server"):+ text = await _call_get_item(server)++ assert text == (+ f"Error calling tool 'get_item': HTTP error {status}: {reason} - "+ "{'detail': 'nope'}"+ )+ records = [+ r for r in caplog.records if r.getMessage() == "Error calling tool 'get_item'"+ ]+ assert len(records) == 1+ assert records[0].levelname == "ERROR"+ assert not records[0].exc_info+++async def test_http_429_returns_rate_limit_message() -> None:+ async with _upstream(429) as http_client:+ server = FastMCP.from_openapi(openapi_spec=SPEC, client=http_client)+ text = await _call_get_item(server)++ assert text == "Rate limited by upstream API, please retry later"+++ ("status", "expected"),+ [+ (404, "Error calling tool 'get_item'"),+ (429, "Rate limited by upstream API, please retry later"),+ ],+)+async def test_masked_http_error_hides_upstream_body(+ status: int, expected: str+) -> None:+ async with _upstream(status) as http_client:+ server = FastMCP.from_openapi(+ openapi_spec=SPEC, client=http_client, mask_error_details=True+ )+ text = await _call_get_item(server)++ assert text == expected+++async def test_resource_http_429_returns_rate_limit_message() -> None:+ async with _upstream(429) as http_client:+ server = FastMCP.from_openapi(+ openapi_spec=RESOURCE_SPEC,+ client=http_client,+ route_maps=[RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE)],+ )+ async with Client(server) as client:+ [resource] = await client.list_resources()+ with pytest.raises(ResourceError) as exc_info:+ await server.read_resource(str(resource.uri))++ assert str(exc_info.value) == "Rate limited by upstream API, please retry later"diff --git a/tests/server/test_input_validation.py b/tests/server/test_input_validation.pyindex abe1fbc90..a13fc59f7 100644--- a/tests/server/test_input_validation.py+++ b/tests/server/test_input_validation.py@@ -9,6 +9,7 @@ strict_input_validation=False, the default).import jsonfrom typing import Annotated, Any+import httpx2import pytestfrom mcp.shared.exceptions import MCPErrorfrom mcp_types import TextContent@@ -604,6 +605,31 @@ class TestExpectedToolFailureLogging:assert records[0].levelname == "ERROR"assert not records[0].exc_info+ async def test_upstream_http_status_error_logs_without_traceback(self, caplog):+ mcp = FastMCP("TestServer")++ @mcp.tool+ def do_thing() -> str:+ request = httpx2.Request("GET", "https://api.example.test/items")+ response = httpx2.Response(404, request=request)+ raise httpx2.HTTPStatusError(+ "not found", request=request, response=response+ )++ with caplog.at_level("DEBUG", logger="fastmcp.server.server"):+ async with Client(mcp) as client:+ with pytest.raises(ToolError, match="not found"):+ await client.call_tool("do_thing", {})++ records = [+ r+ for r in caplog.records+ if r.getMessage() == "Error calling tool 'do_thing'"+ ]+ assert records, "expected an 'Error calling tool' log without traceback"+ assert records[0].levelname == "ERROR"+ assert not records[0].exc_info+async def test_unexpected_exception_still_logs_with_traceback(self, caplog):mcp = FastMCP("TestServer")