Skip to content

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

Improve OpenAPI upstream error details (#6141)

nate nowack41c4053c436c
diff --git a/docs/integrations/openapi.mdx b/docs/integrations/openapi.mdx
index ce9f6565b..cb2c06415 100644
--- a/docs/integrations/openapi.mdx
+++ b/docs/integrations/openapi.mdx
@@ -90,6 +90,12 @@ Use `timeout=None` on the HTTP client to disable timeouts, or an `httpx2.Timeout
If you omit the `client` argument, FastMCP creates an HTTP client with a 30-second timeout using the first server URL in your OpenAPI specification.
+## Upstream HTTP errors
+
+When an OpenAPI request receives a non-success status, FastMCP reports the status and reason to the MCP caller. HTTP 429 retains the rate-limit message, "Rate limited by upstream API, please retry later". If your HTTP client returns a redirect response, the error includes its `Location` header. Redirect following is controlled by the HTTP client configuration.
+
+JSON error bodies are rendered as JSON; HTML pages are omitted, and other response text is limited to 1,000 characters with a truncation marker. These details are shared by generated tools, resources, and resource templates. Configure `mask_error_details=True` on `FastMCP.from_openapi()` when callers should not see upstream error details.
+
## Route Mapping
By default, FastMCP converts **every endpoint** in your OpenAPI specification into an MCP **Tool**. This provides a simple, predictable starting point that ensures all your API's functionality is immediately available to the vast majority of LLM clients which only support MCP tools.
diff --git a/fastmcp_slim/fastmcp/server/providers/openapi/components.py b/fastmcp_slim/fastmcp/server/providers/openapi/components.py
index 529371831..fb44f57a0 100644
--- a/fastmcp_slim/fastmcp/server/providers/openapi/components.py
+++ b/fastmcp_slim/fastmcp/server/providers/openapi/components.py
@@ -57,25 +57,43 @@ logger = get_logger(__name__)
# Default MIME type when no response content type can be inferred
_DEFAULT_MIME_TYPE = "application/json"
+_ERROR_BODY_LIMIT = 1000
+_ERROR_BODY_TRUNCATION = "… (truncated)"
-def _raise_for_status(response: httpx2.Response) -> None:
- """Raise an OpenAPI-formatted error without relying on client exception types.
+def _bounded_error_body(body: str) -> str:
+ """Limit upstream error text included in a tool error."""
+ if len(body) <= _ERROR_BODY_LIMIT:
+ return body
+ return body[:_ERROR_BODY_LIMIT] + _ERROR_BODY_TRUNCATION
- 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.
- """
+
+def _raise_for_status(response: httpx2.Response) -> None:
+ """Raise an OpenAPI-formatted error with concise upstream details."""
if 200 <= response.status_code < 300:
return
error_message = f"HTTP error {response.status_code}: {response.reason_phrase}"
- try:
- error_data = response.json()
- error_message += f" - {error_data}"
- except (json.JSONDecodeError, ValueError):
- if response.text:
- error_message += f" - {response.text}"
+ headers = getattr(response, "headers", {})
+ if 300 <= response.status_code < 400:
+ location = headers.get("location")
+ if location:
+ error_message += f" - Location: {location}"
+
+ content_type = headers.get("content-type", "").split(";", 1)[0].strip().lower()
+ body = getattr(response, "text", "")
+ is_html = content_type in {"text/html", "application/xhtml+xml"}
+ if body and not is_html:
+ try:
+ error_data = response.json()
+ except (json.JSONDecodeError, ValueError):
+ # Some upstreams omit Content-Type, so avoid forwarding obvious HTML.
+ if not body.lstrip().lower().startswith(("<!doctype html", "<html")):
+ error_message += f" - {_bounded_error_body(body)}"
+ else:
+ error_message += (
+ f" - {_bounded_error_body(json.dumps(error_data, ensure_ascii=False))}"
+ )
raise httpx2.HTTPStatusError(
error_message, request=response.request, response=response
)
diff --git a/tests/server/providers/openapi/test_http_error_details_regression.py b/tests/server/providers/openapi/test_http_error_details_regression.py
new file mode 100644
index 000000000..1876ad432
--- /dev/null
+++ b/tests/server/providers/openapi/test_http_error_details_regression.py
@@ -0,0 +1,86 @@
+"""Regression tests for concise, useful OpenAPI upstream error details."""
+
+import httpx2
+import pytest
+
+from fastmcp.server.providers.openapi.components import _raise_for_status
+
+
+def _error(response: httpx2.Response) -> str:
+ response.request = httpx2.Request("GET", "https://api.example.test/items")
+ with pytest.raises(httpx2.HTTPStatusError) as exc_info:
+ _raise_for_status(response)
+ return str(exc_info.value)
+
+
+ ("response", "expected", "unexpected"),
+ [
+ (
+ httpx2.Response(
+ 301,
+ headers={
+ "location": "https://api.example.test/v2/items",
+ "content-type": "text/html",
+ },
+ text="<html>moved</html>",
+ ),
+ "Location: https://api.example.test/v2/items",
+ "<html>",
+ ),
+ (
+ httpx2.Response(
+ 502,
+ headers={"content-type": "text/html"},
+ text="<!DOCTYPE html><html>" + "x" * 2000 + "</html>",
+ ),
+ "HTTP error 502: Bad Gateway",
+ "<!DOCTYPE html>",
+ ),
+ (
+ httpx2.Response(409, json={"detail": "conflict"}),
+ '"detail": "conflict"',
+ "{'detail':",
+ ),
+ (
+ httpx2.Response(502, text="<html>proxy failure</html>"),
+ "HTTP error 502: Bad Gateway",
+ "proxy failure",
+ ),
+ ],
+)
+def test_error_message_preserves_details_without_html_noise(
+ response: httpx2.Response, expected: str, unexpected: str
+) -> None:
+ message = _error(response)
+ assert expected in message
+ assert unexpected not in message
+
+
+ ("body", "content_type", "expected"),
+ [
+ ('[1, "two"]', "application/problem+json", '[1, "two"]'),
+ ('"denied"', "application/json", '"denied"'),
+ ("true", "application/json", "true"),
+ ("not-json", "application/json", "not-json"),
+ ("", "text/plain", "HTTP error 400: Bad Request"),
+ ],
+)
+def test_json_and_malformed_error_bodies_are_readable(
+ body: str, content_type: str, expected: str
+) -> None:
+ response = httpx2.Response(
+ 400, headers={"content-type": content_type}, content=body.encode()
+ )
+ assert expected in _error(response)
+
+
+def test_plain_text_error_body_is_bounded_with_truncation_marker() -> None:
+ message = _error(httpx2.Response(500, text="x" * 1050))
+ assert "x" * 1000 + "… (truncated)" in message
+ assert "x" * 1001 not in message
+
+
+def test_redirect_without_location_has_no_extra_detail() -> None:
+ assert _error(httpx2.Response(302, text="")) == "HTTP error 302: Found"
diff --git a/tests/server/providers/openapi/test_http_errors.py b/tests/server/providers/openapi/test_http_errors.py
index e27920407..ab075285c 100644
--- a/tests/server/providers/openapi/test_http_errors.py
+++ b/tests/server/providers/openapi/test_http_errors.py
@@ -4,6 +4,7 @@ import logging
import httpx2
import pytest
+from mcp.shared.exceptions import MCPError
from mcp_types import TextContent
from fastmcp import Client, FastMCP
@@ -81,7 +82,7 @@ async def test_http_error_is_logged_without_traceback(
assert text == (
f"Error calling tool 'get_item': HTTP error {status}: {reason} - "
- "{'detail': 'nope'}"
+ '{"detail": "nope"}'
)
records = [
r for r in caplog.records if r.getMessage() == "Error calling tool 'get_item'"
@@ -131,3 +132,28 @@ async def test_resource_http_429_returns_rate_limit_message() -> None:
await server.read_resource(str(resource.uri))
assert str(exc_info.value) == "Rate limited by upstream API, please retry later"
+
+
[email protected]("component", ["resource", "resource_template"])
+async def test_http_error_details_are_preserved_for_resources(component: str) -> None:
+ if component == "resource":
+ spec = RESOURCE_SPEC
+ route_maps = [RouteMap(methods=["GET"], mcp_type=MCPType.RESOURCE)]
+ else:
+ spec = SPEC
+ route_maps = [RouteMap(pattern=r"\{", mcp_type=MCPType.RESOURCE_TEMPLATE)]
+
+ async with _upstream(409) as http_client:
+ server = FastMCP.from_openapi(
+ openapi_spec=spec, client=http_client, route_maps=route_maps
+ )
+ async with Client(server) as client:
+ if component == "resource":
+ [resource] = await client.list_resources()
+ uri = str(resource.uri)
+ else:
+ uri = "resource://get_item/x1"
+ with pytest.raises(MCPError) as exc_info:
+ await client.read_resource(uri)
+
+ assert '"detail": "nope"' in str(exc_info.value)