Skip to content

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

fix(openapi): preserve timeouts so the server maps them to the actionable message (#5847)

ε“ˆεŸΊη±³1fdac8764a06
diff --git a/fastmcp_slim/fastmcp/server/providers/openapi/components.py b/fastmcp_slim/fastmcp/server/providers/openapi/components.py
index 22a19e69a..83ead909b 100644
--- a/fastmcp_slim/fastmcp/server/providers/openapi/components.py
+++ b/fastmcp_slim/fastmcp/server/providers/openapi/components.py
@@ -106,9 +106,17 @@ async def _send_request(
client: httpx2.AsyncClient,
request: httpx2.Request,
) -> httpx2.Response:
- """Send a request while preserving transitional legacy-client errors."""
+ """Send a request, preserving native httpx2 transport errors.
+
+ Native `httpx2` transport errors are re-raised unchanged so the server's
+ actionable error mapping (for example, timeouts) can recognize them.
+ Legacy-httpx clients, still accepted through the deprecation bridge, are
+ normalized to `ValueError` with the original error details.
+ """
try:
return await client.send(request)
+ except httpx2.RequestError:
+ raise
except Exception as exc:
if is_timeout_error(exc):
raise ValueError(f"HTTP request timed out ({type(exc).__name__})") from exc
@@ -265,50 +273,44 @@ class OpenAPITool(Tool):
f"{self._route.path}: {type(e).__name__}: {e}"
) from e
- # Send the request and process the response.
+ # Send the request and process the response. Transport errors from
+ # httpx2 are left intact for the server's actionable error mapping.
+ logger.debug(
+ f"run - sending request; headers: {_redact_headers(request.headers)}"
+ )
+
+ response = await _send_request(self._client, request)
+ _raise_for_status(response)
+
+ # Try to parse as JSON first
try:
- logger.debug(
- f"run - sending request; headers: {_redact_headers(request.headers)}"
- )
+ result = response.json()
- response = await _send_request(self._client, request)
- _raise_for_status(response)
-
- # Try to parse as JSON first
- try:
- result = response.json()
-
- # Handle structured content based on output schema
- wrap_result = False
- if self.output_schema is not None:
- if self.output_schema.get("x-fastmcp-wrap-result"):
- structured_output = {"result": result}
- else:
- structured_output = result
- elif not isinstance(result, dict):
+ # Handle structured content based on output schema
+ wrap_result = False
+ if self.output_schema is not None:
+ if self.output_schema.get("x-fastmcp-wrap-result"):
structured_output = {"result": result}
- wrap_result = True
else:
structured_output = result
+ elif not isinstance(result, dict):
+ structured_output = {"result": result}
+ wrap_result = True
+ else:
+ structured_output = result
- # Structured content must be a dict for the MCP protocol.
- # Wrap non-dict values that slipped through (e.g. a backend
- # returning an array when the schema declared an object).
- if not isinstance(structured_output, dict):
- structured_output = {"result": structured_output}
+ # Structured content must be a dict for the MCP protocol.
+ # Wrap non-dict values that slipped through (e.g. a backend
+ # returning an array when the schema declared an object).
+ if not isinstance(structured_output, dict):
+ structured_output = {"result": structured_output}
- return ToolResult(
- structured_content=structured_output,
- meta={"fastmcp": {"wrap_result": True}} if wrap_result else None,
- )
- except json.JSONDecodeError:
- return ToolResult(content=response.text)
-
- except httpx2.TimeoutException as exc:
- raise ValueError(f"HTTP request timed out ({type(exc).__name__})") from exc
-
- except httpx2.RequestError as exc:
- raise ValueError(f"Request error ({type(exc).__name__}): {exc!s}") from exc
+ return ToolResult(
+ structured_content=structured_output,
+ meta={"fastmcp": {"wrap_result": True}} if wrap_result else None,
+ )
+ except json.JSONDecodeError:
+ return ToolResult(content=response.text)
class OpenAPIResource(Resource):
@@ -345,64 +347,53 @@ class OpenAPIResource(Resource):
async def read(self) -> ResourceResult:
"""Fetch the resource data by making an HTTP request."""
- try:
- base_url = str(self._client.base_url) or "http://localhost"
- directed_request = self._director.build(
- self._route, self._arguments, base_url
+ base_url = str(self._client.base_url) or "http://localhost"
+ directed_request = self._director.build(self._route, self._arguments, base_url)
+ # Build through the configured client so its defaults are applied.
+ request = self._client.build_request(
+ method=directed_request.method,
+ url=str(directed_request.url.copy_with(query=None)),
+ params=list(directed_request.url.params.multi_items()),
+ headers=list(directed_request.headers.raw),
+ # read() materializes streaming bodies (multipart files=)
+ # that .content would refuse with RequestNotRead; idempotent
+ # for plain byte bodies.
+ content=directed_request.read(),
+ )
+ mcp_headers = get_http_headers()
+ if mcp_headers:
+ for key, value in mcp_headers.items():
+ if key not in request.headers:
+ request.headers[key] = value
+
+ # Transport errors from httpx2 are left intact for the server's
+ # actionable error mapping.
+ response = await _send_request(self._client, request)
+ _raise_for_status(response)
+
+ content_type = response.headers.get("content-type", "").lower()
+ media_type = content_type.split(";")[0].strip()
+
+ # RFC 6839: a "+json" suffix marks a JSON media type
+ if media_type == "application/json" or media_type.endswith("+json"):
+ result = response.json()
+ return ResourceResult(
+ contents=[
+ ResourceContent(content=json.dumps(result), mime_type=media_type)
+ ]
)
- # Build through the configured client so its defaults are applied.
- request = self._client.build_request(
- method=directed_request.method,
- url=str(directed_request.url.copy_with(query=None)),
- params=list(directed_request.url.params.multi_items()),
- headers=list(directed_request.headers.raw),
- # read() materializes streaming bodies (multipart files=)
- # that .content would refuse with RequestNotRead; idempotent
- # for plain byte bodies.
- content=directed_request.read(),
+ elif any(ct in content_type for ct in ["text/", "application/xml"]):
+ return ResourceResult(
+ contents=[
+ ResourceContent(content=response.text, mime_type=self.mime_type)
+ ]
+ )
+ else:
+ return ResourceResult(
+ contents=[
+ ResourceContent(content=response.content, mime_type=self.mime_type)
+ ]
)
- mcp_headers = get_http_headers()
- if mcp_headers:
- for key, value in mcp_headers.items():
- if key not in request.headers:
- request.headers[key] = value
-
- response = await _send_request(self._client, request)
- _raise_for_status(response)
-
- content_type = response.headers.get("content-type", "").lower()
- media_type = content_type.split(";")[0].strip()
-
- # RFC 6839: a "+json" suffix marks a JSON media type
- if media_type == "application/json" or media_type.endswith("+json"):
- result = response.json()
- return ResourceResult(
- contents=[
- ResourceContent(
- content=json.dumps(result), mime_type=media_type
- )
- ]
- )
- elif any(ct in content_type for ct in ["text/", "application/xml"]):
- return ResourceResult(
- contents=[
- ResourceContent(content=response.text, mime_type=self.mime_type)
- ]
- )
- else:
- return ResourceResult(
- contents=[
- ResourceContent(
- content=response.content, mime_type=self.mime_type
- )
- ]
- )
-
- except httpx2.TimeoutException as exc:
- raise ValueError(f"HTTP request timed out ({type(exc).__name__})") from exc
-
- except httpx2.RequestError as exc:
- raise ValueError(f"Request error ({type(exc).__name__}): {exc!s}") from exc
def _path_argument_name(route: HTTPRoute, parameter_name: str) -> str:
diff --git a/tests/server/providers/openapi/test_comprehensive.py b/tests/server/providers/openapi/test_comprehensive.py
index ace2a03a5..d4efa280b 100644
--- a/tests/server/providers/openapi/test_comprehensive.py
+++ b/tests/server/providers/openapi/test_comprehensive.py
@@ -746,7 +746,7 @@ class TestOpenAPIComprehensive:
async def test_timeout_error_produces_useful_message(
self, comprehensive_openapi_spec
):
- """ReadTimeout should surface a clear error, not an empty string."""
+ """ReadTimeout should surface the actionable timeout message."""
mock_client = Mock(spec=httpx2.AsyncClient)
mock_client.base_url = "https://api.example.com"
mock_client.headers = None
@@ -765,8 +765,7 @@ class TestOpenAPIComprehensive:
await mcp_client.call_tool("get_user", {"id": 1})
error_message = str(exc_info.value)
- assert "timed out" in error_message
- assert "ReadTimeout" in error_message
+ assert "Upstream request timed out, please retry" in error_message
class TestOpenAPIPostEdgeCases:
diff --git a/tests/server/providers/openapi/test_transport_errors.py b/tests/server/providers/openapi/test_transport_errors.py
new file mode 100644
index 000000000..32303fa46
--- /dev/null
+++ b/tests/server/providers/openapi/test_transport_errors.py
@@ -0,0 +1,118 @@
+"""Transport error propagation from OpenAPI components."""
+
+from collections.abc import Callable
+
+import httpx2
+import pytest
+from mcp_types import TextContent
+
+from fastmcp import Client, FastMCP, FastMCPDeprecationWarning
+from fastmcp.exceptions import ResourceError, ToolError
+from fastmcp.server.providers.openapi.routing import MCPType, RouteMap
+
+SPEC = {
+ "openapi": "3.1.0",
+ "info": {"title": "Slow API", "version": "1.0"},
+ "servers": [{"url": "https://api.example.test"}],
+ "paths": {
+ "/slow": {
+ "get": {
+ "operationId": "slow",
+ "responses": {"200": {"description": "OK"}},
+ }
+ }
+ },
+}
+
+
+def _upstream(
+ handler: Callable[[httpx2.Request], httpx2.Response],
+) -> httpx2.AsyncClient:
+ return httpx2.AsyncClient(
+ base_url="https://api.example.test",
+ transport=httpx2.MockTransport(handler),
+ )
+
+
+async def _call_slow(server: FastMCP) -> str:
+ async with Client(server) as client:
+ result = await client.call_tool("slow", {}, raise_on_error=False)
+ assert result.is_error
+ assert isinstance(result.content[0], TextContent)
+ return result.content[0].text
+
+
+async def test_masked_tool_timeout_returns_actionable_message() -> None:
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ raise httpx2.ReadTimeout("simulated", request=request)
+
+ async with _upstream(handler) as http_client:
+ server = FastMCP.from_openapi(
+ openapi_spec=SPEC, client=http_client, mask_error_details=True
+ )
+ text = await _call_slow(server)
+
+ assert text == "Upstream request timed out, please retry"
+
+
+async def test_masked_resource_timeout_returns_actionable_message() -> None:
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ raise httpx2.ReadTimeout("simulated", request=request)
+
+ async with _upstream(handler) as http_client:
+ server = FastMCP.from_openapi(
+ openapi_spec=SPEC,
+ client=http_client,
+ mask_error_details=True,
+ 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) == "Upstream request timed out, please retry"
+
+
+async def test_masked_ordinary_error_stays_generic() -> None:
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ raise RuntimeError("boom")
+
+ async with _upstream(handler) as http_client:
+ server = FastMCP.from_openapi(
+ openapi_spec=SPEC, client=http_client, mask_error_details=True
+ )
+ text = await _call_slow(server)
+
+ assert text == "Error calling tool 'slow'"
+
+
+async def test_unmasked_ordinary_error_keeps_details() -> None:
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ raise RuntimeError("boom")
+
+ async with _upstream(handler) as http_client:
+ server = FastMCP.from_openapi(openapi_spec=SPEC, client=http_client)
+ text = await _call_slow(server)
+
+ assert text == "Error calling tool 'slow': boom"
+
+
+async def test_legacy_request_error_remains_normalized() -> None:
+ httpx = pytest.importorskip("httpx", reason="legacy httpx not installed")
+
+ def handler(request: "httpx.Request") -> "httpx.Response":
+ raise httpx.ConnectError("transport failed", request=request)
+
+ transport = httpx.MockTransport(handler)
+ async with httpx.AsyncClient(
+ transport=transport, base_url="https://api.example.test"
+ ) as client:
+ with pytest.warns(FastMCPDeprecationWarning):
+ server = FastMCP.from_openapi(SPEC, client=client)
+ with pytest.raises(ToolError) as exc_info:
+ await server.call_tool("slow", {})
+
+ assert str(exc_info.value) == (
+ "Error calling tool 'slow': Request error (ConnectError): transport failed"
+ )