π The fast, Pythonic way to build MCP servers and clients.
Harden client tool result error handling (#3778)
aimable100556fd8fa4270
diff --git a/src/fastmcp/client/mixins/tools.py b/src/fastmcp/client/mixins/tools.pyindex d6c37a5bd..aec595019 100644--- a/src/fastmcp/client/mixins/tools.py+++ b/src/fastmcp/client/mixins/tools.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport uuidimport weakref-from typing import TYPE_CHECKING, Any, Literal, cast, overload+from typing import TYPE_CHECKING, Any, Literal, overloadimport mcp.typesfrom pydantic import RootModel@@ -386,9 +386,12 @@ async def _parse_call_tool_result(data = Noneif result.isError and raise_on_error:- msg = cast(mcp.types.TextContent, result.content[0]).text+ if result.content and isinstance(result.content[0], mcp.types.TextContent):+ msg = result.content[0].text+ else:+ msg = f"Tool '{name}' returned an error"raise ToolError(msg)- elif result.structuredContent:+ elif result.structuredContent and not result.isError:try:raw_fastmcp_meta = (result.meta or {}).get("fastmcp")fastmcp_meta = (diff --git a/tests/client/client/test_error_handling.py b/tests/client/client/test_error_handling.pyindex 5f5c22175..49a488022 100644--- a/tests/client/client/test_error_handling.py+++ b/tests/client/client/test_error_handling.py@@ -1,10 +1,12 @@"""Client error handling tests."""+import mcp.typesimport pytestfrom mcp.types import TextContentfrom pydantic import AnyUrlfrom fastmcp.client import Client+from fastmcp.client.mixins.tools import _parse_call_tool_resultfrom fastmcp.client.transports import FastMCPTransportfrom fastmcp.exceptions import ResourceError, ToolErrorfrom fastmcp.server.server import FastMCP@@ -164,3 +166,102 @@ class TestErrorHandling:with pytest.raises(Exception) as excinfo:await client.read_resource(AnyUrl("error://resource/123"))assert "This is a resource error (xyz)" in str(excinfo.value)+++class TestCallToolRaiseOnError:+ """Tests for call_tool error handling with raise_on_error."""++ async def test_call_tool_raises_tool_error_by_default(self):+ mcp = FastMCP("TestServer")++ @mcp.tool+ def failing_tool() -> str:+ raise ValueError("something broke")++ async with Client(transport=FastMCPTransport(mcp)) as client:+ with pytest.raises(ToolError, match="something broke"):+ await client.call_tool("failing_tool", {})++ async def test_call_tool_no_raise_returns_error_result(self):+ mcp = FastMCP("TestServer")++ @mcp.tool+ def failing_tool() -> str:+ raise ValueError("something broke")++ async with Client(transport=FastMCPTransport(mcp)) as client:+ result = await client.call_tool("failing_tool", {}, raise_on_error=False)+ assert result.is_error is True+ assert result.data is None+++class TestParseToolResultEdgeCases:+ """Unit tests for _parse_call_tool_result with non-standard error payloads.++ These edge cases can't be triggered through the public Client API because+ FastMCP's server always produces TextContent on errors. Testing the parser+ directly covers defensive handling of third-party MCP servers.+ """++ async def test_error_with_empty_content_raises_with_fallback_message(self):+ result = mcp.types.CallToolResult(content=[], isError=True)++ with pytest.raises(ToolError, match="Tool 'my_tool' returned an error"):+ await _parse_call_tool_result(+ name="my_tool",+ result=result,+ tool_output_schemas={},+ list_tools_fn=None,+ raise_on_error=True,+ )++ async def test_error_with_non_text_content_raises_with_fallback_message(self):+ result = mcp.types.CallToolResult(+ content=[+ mcp.types.ImageContent(type="image", data="abc", mimeType="image/png")+ ],+ isError=True,+ )++ with pytest.raises(ToolError, match="Tool 'my_tool' returned an error"):+ await _parse_call_tool_result(+ name="my_tool",+ result=result,+ tool_output_schemas={},+ list_tools_fn=None,+ raise_on_error=True,+ )++ async def test_error_with_text_content_raises_with_message(self):+ result = mcp.types.CallToolResult(+ content=[mcp.types.TextContent(type="text", text="custom error msg")],+ isError=True,+ )++ with pytest.raises(ToolError, match="custom error msg"):+ await _parse_call_tool_result(+ name="my_tool",+ result=result,+ tool_output_schemas={},+ list_tools_fn=None,+ raise_on_error=True,+ )++ async def test_error_with_structured_content_does_not_parse_data(self):+ result = mcp.types.CallToolResult(+ content=[mcp.types.TextContent(type="text", text="error happened")],+ isError=True,+ structuredContent={"key": "value"},+ )++ parsed = await _parse_call_tool_result(+ name="my_tool",+ result=result,+ tool_output_schemas={},+ list_tools_fn=None,+ raise_on_error=False,+ )++ assert parsed.is_error is True+ assert parsed.data is None+ assert parsed.structured_content == {"key": "value"}