π The fast, Pythonic way to build MCP servers and clients.
Omit the output schema when an OpenAPI success response has no body (#5913)
Asem ahmede95877e76422
diff --git a/fastmcp_slim/fastmcp/server/providers/openapi/components.py b/fastmcp_slim/fastmcp/server/providers/openapi/components.pyindex 95b0b4d32..529371831 100644--- a/fastmcp_slim/fastmcp/server/providers/openapi/components.py+++ b/fastmcp_slim/fastmcp/server/providers/openapi/components.py@@ -247,6 +247,7 @@ class OpenAPITool(Tool):result = response.json()# Handle structured content based on output schema+ wrap_result = Falseif self.output_schema is not None:if self.output_schema.get("x-fastmcp-wrap-result"):structured_output = {"result": result}@@ -254,6 +255,7 @@ class OpenAPITool(Tool):structured_output = resultelif not isinstance(result, dict):structured_output = {"result": result}+ wrap_result = Trueelse:structured_output = result@@ -263,7 +265,10 @@ class OpenAPITool(Tool):if not isinstance(structured_output, dict):structured_output = {"result": structured_output}- return ToolResult(structured_content=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)diff --git a/fastmcp_slim/fastmcp/utilities/openapi/parser.py b/fastmcp_slim/fastmcp/utilities/openapi/parser.pyindex e329d198f..5df5690ad 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/parser.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/parser.py@@ -452,10 +452,39 @@ class OpenAPIParser(# If no success codes found, return None (tool will have no output schema)return None+ def _extract_bodiless_success_responses(+ self, operation_responses: dict[str, Any], primary_status_code: str+ ) -> dict[str, ResponseInfo]:+ """Extract the success responses, besides the primary one, that declare no body.++ Such a response (e.g. a 204 next to a 201) means the operation may answer+ without a body, so the tool cannot promise structured output.+ """+ bodiless_responses: dict[str, ResponseInfo] = {}+ for status_code, resp_or_ref in operation_responses.items():+ if status_code == primary_status_code or not str(status_code).startswith(+ "2"+ ):+ continue+ try:+ response = self._resolve_ref(resp_or_ref)+ except ValueError as e:+ logger.debug(f"Skipping unresolved response {status_code}: {e}")+ continue+ if isinstance(response, self.response_cls) and not response.content:+ bodiless_responses[str(status_code)] = ResponseInfo(+ description=response.description+ )+ return bodiless_responses+def _extract_responses(self, operation_responses: dict[str, Any] | None) -> dict[str, ResponseInfo]:- """Extract and resolve response information. Only includes the primary success response for MCP tools."""+ """Extract and resolve response information.++ Only includes the primary success response for MCP tools, plus any other+ success response that has no body.+ """extracted_responses: dict[str, ResponseInfo] = {}if not operation_responses:@@ -548,6 +577,9 @@ class OpenAPIParser(exc_info=False,)+ extracted_responses.update(+ self._extract_bodiless_success_responses(operation_responses, status_code)+ )return extracted_responsesdef _extract_schema_dependencies(diff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.pyindex 517dd9402..49981d4f5 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py@@ -794,7 +794,9 @@ def extract_output_schema_from_responses(This function finds the first successful response (200, 201, 202, 204) with aJSON-compatible content type and extracts its schema. If the schema is not an- object type, it wraps it to comply with MCP requirements.+ object type, it wraps it to comply with MCP requirements. When any successful+ response has no content, there is no output schema, since the operation may+ answer without a body.Args:responses: Dictionary of ResponseInfo objects keyed by status code@@ -807,6 +809,14 @@ def extract_output_schema_from_responses(if not responses:return None+ # MCP requires structured content from a tool that advertises an output+ # schema, which a bodiless success response (e.g. 204) cannot provide.+ if any(+ status_code.startswith("2") and not resp_info.content_schema+ for status_code, resp_info in responses.items()+ ):+ return None+# Priority order for success status codessuccess_codes = ["200", "201", "202", "204"]diff --git a/tests/server/providers/openapi/test_bodiless_success_responses.py b/tests/server/providers/openapi/test_bodiless_success_responses.pynew file mode 100644index 000000000..2e74fad1e--- /dev/null+++ b/tests/server/providers/openapi/test_bodiless_success_responses.py@@ -0,0 +1,236 @@+"""Operations that may answer with a success response that has no body."""++from typing import Any++import httpx2+import pytest++from fastmcp import Client, FastMCP++INVITATION = {"id": 7, "invitee": "octocat"}++JSON_INVITATION = {+ "description": "Invitation created",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "id": {"type": "integer"},+ "invitee": {"type": "string"},+ },+ }+ }+ },+}+NO_CONTENT = {"description": "The user already has access"}+++def spec_with_responses(responses: dict[str, Any]) -> dict[str, Any]:+ return {+ "openapi": "3.0.3",+ "info": {"title": "Collaborators", "version": "1.0"},+ "paths": {+ "/collaborators/{username}": {+ "put": {+ "operationId": "add_collaborator",+ "parameters": [+ {+ "name": "username",+ "in": "path",+ "required": True,+ "schema": {"type": "string"},+ }+ ],+ "responses": responses,+ }+ }+ },+ "components": {"responses": {"NoContent": NO_CONTENT}},+ }+++def respond(request: httpx2.Request) -> httpx2.Response:+ if request.url.path.endswith("/existing"):+ return httpx2.Response(204)+ return httpx2.Response(201, json=INVITATION)+++def server_for(responses: dict[str, Any], *, validate_output: bool = True) -> FastMCP:+ upstream = httpx2.AsyncClient(+ base_url="https://api.example.test",+ transport=httpx2.MockTransport(respond),+ )+ return FastMCP.from_openapi(+ openapi_spec=spec_with_responses(responses),+ client=upstream,+ validate_output=validate_output,+ )+++BODILESS_SIBLINGS = [+ pytest.param({"201": JSON_INVITATION, "204": NO_CONTENT}, id="201-and-204"),+ pytest.param({"200": JSON_INVITATION, "202": NO_CONTENT}, id="200-and-202"),+ pytest.param({"204": NO_CONTENT, "201": JSON_INVITATION}, id="204-listed-first"),+ pytest.param(+ {"201": JSON_INVITATION, "204": {"$ref": "#/components/responses/NoContent"}},+ id="referenced-204",+ ),+ pytest.param(+ {"201": JSON_INVITATION, "204": {"description": "None", "content": {}}},+ id="empty-content",+ ),+]++[email protected]("responses", BODILESS_SIBLINGS)[email protected]("validate_output", [True, False])+async def test_bodiless_success_response_drops_output_schema(+ responses: dict[str, Any], validate_output: bool+):+ server = server_for(responses, validate_output=validate_output)++ async with Client(server) as client:+ (tool,) = await client.list_tools()++ assert tool.output_schema is None+++async def test_bodiless_success_call_succeeds_next_to_json_success():+ server = server_for({"201": JSON_INVITATION, "204": NO_CONTENT})++ async with Client(server) as client:+ created = await client.call_tool("add_collaborator", {"username": "new"})+ existing = await client.call_tool("add_collaborator", {"username": "existing"})++ assert created.is_error is False+ assert created.structured_content == INVITATION+ assert existing.is_error is False+ assert existing.structured_content is None+++ "responses",+ [+ pytest.param({"200": JSON_INVITATION}, id="json-only"),+ pytest.param(+ {"201": JSON_INVITATION, "404": {"description": "Not found"}},+ id="bodiless-error",+ ),+ pytest.param(+ {"201": JSON_INVITATION, "default": {"description": "Unexpected error"}},+ id="bodiless-default",+ ),+ pytest.param(+ {"200": JSON_INVITATION, "201": JSON_INVITATION}, id="two-json-successes"+ ),+ ],+)+async def test_output_schema_kept_without_bodiless_success_response(+ responses: dict[str, Any],+):+ server = server_for(responses)++ async with Client(server) as client:+ (tool,) = await client.list_tools()++ assert tool.output_schema is not None+ assert tool.output_schema["properties"]["invitee"] == {"type": "string"}+++ ("payload", "schema"),+ [+ (3, {"type": "integer"}),+ (False, {"type": "boolean"}),+ ("ready", {"type": "string"}),+ ([1, 2], {"type": "array", "items": {"type": "integer"}}),+ ],+)[email protected]("validate_output", [True, False])+async def test_json_success_preserves_unwrapped_data_next_to_bodiless_success(+ payload: Any, schema: dict[str, Any], validate_output: bool+):+ responses = {+ "200": {+ "description": "Result",+ "content": {"application/json": {"schema": schema}},+ },+ "204": NO_CONTENT,+ }++ def respond_with_payload(request: httpx2.Request) -> httpx2.Response:+ if request.url.path.endswith("/existing"):+ return httpx2.Response(204)+ return httpx2.Response(200, json=payload)++ async with httpx2.AsyncClient(+ base_url="https://api.example.test",+ transport=httpx2.MockTransport(respond_with_payload),+ ) as upstream:+ server = FastMCP.from_openapi(+ openapi_spec=spec_with_responses(responses),+ client=upstream,+ validate_output=validate_output,+ )+ async with Client(server) as client:+ created = await client.call_tool("add_collaborator", {"username": "new"})+ existing = await client.call_tool(+ "add_collaborator", {"username": "existing"}+ )++ assert created.structured_content == {"result": payload}+ assert created.data == payload+ assert type(created.data) is type(payload)+ assert existing.structured_content is None+ assert existing.data is None+ assert existing.is_error is False+++async def test_untyped_json_object_with_result_key_is_not_unwrapped():+ payload = {"result": [1, 2]}+ responses = {+ "200": {"description": "Untyped JSON", "content": {"application/json": {}}},+ "204": NO_CONTENT,+ }+ async with httpx2.AsyncClient(+ base_url="https://api.example.test",+ transport=httpx2.MockTransport(+ lambda request: httpx2.Response(200, json=payload)+ ),+ ) as upstream:+ server = FastMCP.from_openapi(+ openapi_spec=spec_with_responses(responses), client=upstream+ )+ async with Client(server) as client:+ result = await client.call_tool("add_collaborator", {"username": "new"})++ assert result.structured_content == payload+ assert result.data == payload+ assert type(result.data) is dict+++async def test_disabled_validation_preserves_unexpected_array():+ responses = {+ "200": {+ "description": "Object",+ "content": {"application/json": {"schema": {"type": "object"}}},+ }+ }+ async with httpx2.AsyncClient(+ base_url="https://api.example.test",+ transport=httpx2.MockTransport(+ lambda request: httpx2.Response(200, json=[1, 2])+ ),+ ) as upstream:+ server = FastMCP.from_openapi(+ openapi_spec=spec_with_responses(responses),+ client=upstream,+ validate_output=False,+ )+ async with Client(server) as client:+ result = await client.call_tool("add_collaborator", {"username": "new"})++ assert result.structured_content == {"result": [1, 2]}+ assert result.data == {"result": [1, 2]}+ assert type(result.data) is dictdiff --git a/tests/utilities/openapi/test_parser.py b/tests/utilities/openapi/test_parser.pyindex dfb78b5a2..50eaf948e 100644--- a/tests/utilities/openapi/test_parser.py+++ b/tests/utilities/openapi/test_parser.py@@ -548,3 +548,40 @@ class TestParameterExamples:# 3. Parameter-level example overrides schema-level example and examplesassert props["overrideSchemaExamples"]["example"] == "PARAM_EXAMPLE"assert "examples" not in props["overrideSchemaExamples"]+++class TestBodilessSuccessResponses:+ """Test which success responses the parser keeps for an operation."""++ def test_only_primary_and_bodiless_success_responses_are_extracted(self):+ json_content = {"application/json": {"schema": {"type": "object"}}}+ spec = {+ "openapi": "3.0.0",+ "info": {"title": "Responses", "version": "1.0.0"},+ "paths": {+ "/collaborators": {+ "put": {+ "operationId": "add_collaborator",+ "responses": {+ "201": {"description": "Created", "content": json_content},+ "202": {"description": "Accepted"},+ "204": {"$ref": "#/components/responses/NoContent"},+ "206": {"description": "Partial", "content": json_content},+ "404": {"description": "Not found"},+ "default": {"description": "Error"},+ },+ }+ }+ },+ "components": {"responses": {"NoContent": {"description": "No content"}}},+ }++ (route,) = parse_openapi_to_http_routes(spec)++ assert list(route.responses) == ["201", "202", "204"]+ assert route.responses["201"].content_schema == {+ "application/json": {"type": "object"}+ }+ assert route.responses["202"].content_schema == {}+ assert route.responses["204"].description == "No content"+ assert route.responses["204"].content_schema == {}diff --git a/tests/utilities/openapi/test_schemas.py b/tests/utilities/openapi/test_schemas.pyindex b02e47f54..9217279c9 100644--- a/tests/utilities/openapi/test_schemas.py+++ b/tests/utilities/openapi/test_schemas.py@@ -9,11 +9,13 @@ from fastmcp.utilities.openapi.models import (HTTPRoute,ParameterInfo,RequestBodyInfo,+ ResponseInfo,)from fastmcp.utilities.openapi.schemas import (_combine_schemas,_combine_schemas_and_map_params,_replace_ref_with_defs,+ extract_output_schema_from_responses,)@@ -710,3 +712,53 @@ class TestEdgeCases:# $ref should be preserved in allOfassert result["properties"]["data"]["allOf"] == [{"$ref": "#/$defs/TestSchema"}]+++class TestExtractOutputSchema:+ """Test output schema extraction from a route's success responses."""++ invitation_schema: dict[str, Any] = {+ "type": "object",+ "properties": {"id": {"type": "integer"}},+ }++ @pytest.fixture+ def invitation(self) -> ResponseInfo:+ return ResponseInfo(+ description="Invitation created",+ content_schema={"application/json": self.invitation_schema},+ )++ @pytest.mark.parametrize(+ "bodiless_code", ["200", "202", "204", "2XX"], ids=lambda code: f"with-{code}"+ )+ def test_bodiless_success_response_next_to_json_success(+ self, invitation: ResponseInfo, bodiless_code: str+ ):+ responses = {+ "201": invitation,+ bodiless_code: ResponseInfo(description="No content"),+ }++ assert extract_output_schema_from_responses(responses) is None++ def test_only_bodiless_success_response(self):+ responses = {"204": ResponseInfo(description="No content")}++ assert extract_output_schema_from_responses(responses) is None++ @pytest.mark.parametrize("bodiless_code", ["302", "404", "default"])+ def test_bodiless_non_success_response_is_ignored(+ self, invitation: ResponseInfo, bodiless_code: str+ ):+ responses = {+ "200": invitation,+ bodiless_code: ResponseInfo(description="Not a success"),+ }++ assert extract_output_schema_from_responses(responses) == self.invitation_schema++ def test_json_success_responses(self, invitation: ResponseInfo):+ responses = {"200": invitation, "201": invitation}++ assert extract_output_schema_from_responses(responses) == self.invitation_schema