π The fast, Pythonic way to build MCP servers and clients.
Raise ToolError when a tool with an output schema returns an unserializable value (#5063)
massimiliano199178e12564d42a
diff --git a/fastmcp_slim/fastmcp/tools/base.py b/fastmcp_slim/fastmcp/tools/base.pyindex 9e11ad5c9..6c6d69d74 100644--- a/fastmcp_slim/fastmcp/tools/base.py+++ b/fastmcp_slim/fastmcp/tools/base.py@@ -30,6 +30,7 @@ from pydantic import ()from pydantic.json_schema import SkipJsonSchema+from fastmcp.exceptions import ToolErrorfrom fastmcp.utilities.authorization import AuthCheckfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_logger@@ -410,7 +411,18 @@ class Tool(FastMCPComponent):try:structured = _serialize_to_jsonable(raw_value, self.return_type)- except (pydantic_core.PydanticSerializationError, UnicodeDecodeError):+ except (pydantic_core.PydanticSerializationError, UnicodeDecodeError) as e:+ if self.output_schema is not None:+ # The declared output schema obligates structured content+ # (the MCP SDK's client-side validation rejects the result+ # without it), so a silent content-only fallback would report+ # success while breaking that contract.+ raise ToolError(+ f"Could not serialize the return value of tool {self.name!r} "+ f"for its output schema: {e}. If this is unexpected, set the "+ "tool's output_schema to None to disable automatic "+ "serialization."+ ) from ereturn ToolResult(content=content)if not is_content_result:diff --git a/tests/tools/tool/test_results.py b/tests/tools/tool/test_results.pyindex 9edcbb327..3b94e9b38 100644--- a/tests/tools/tool/test_results.py+++ b/tests/tools/tool/test_results.py@@ -433,3 +433,42 @@ class TestSerializeByAlias:assert result.structured_content == {"_id": "123"}assert set(tools["get_biofile"].output_schema["properties"]) == {"_id"} # type: ignore[index]+++class TestUnserializableReturnValue:+ """An unserializable return value must not become a silent success (#5030)."""++ def _make_server(self) -> FastMCP:+ import threading++ mcp = FastMCP()++ @mcp.tool+ def with_schema() -> dict:+ return {"host": "db1", "lock": threading.Lock()}++ @mcp.tool+ def without_schema():+ return {"host": "db1", "lock": threading.Lock()}++ return mcp++ async def test_output_schema_raises_tool_error(self):+ """With an output schema, serialization failure is an error result,+ not a success carrying the value's repr with no structured content."""+ async with Client(self._make_server()) as client:+ result = await client.call_tool("with_schema", {}, raise_on_error=False)++ assert result.is_error+ assert "Could not serialize" in result.content[0].text # type: ignore[union-attr]+ assert "with_schema" in result.content[0].text # type: ignore[union-attr]++ async def test_no_output_schema_keeps_content_fallback(self):+ """Without an output schema there is no structured-content contract,+ so the content-only fallback stays."""+ async with Client(self._make_server()) as client:+ result = await client.call_tool("without_schema", {})++ assert not result.is_error+ assert result.structured_content is None+ assert "db1" in result.content[0].text # type: ignore[union-attr]