Add isError support for non-text tool results (Fixes #348)
Closed
MU
3mo ago+244+244+012345678901234567890123456789-5-5-0123456789
Summary
This PR addresses issue #348 by adding support for returning tool errors with non-text content (images, audio, structured data) without raising exceptions.
Changes
Core Changes (src/mcp-types/mcp_types/_types.py and version-specific models)
- Added
CallToolResult.create_error()classmethod for creating error results with non-text content - Added
model_validatorto auto-convert SDK Image/Audio helpers to their wire content types (ImageContent,AudioContent)
Server Integration (src/mcp/server/mcpserver/utilities/func_metadata.py)
- Updated
convert_resultto handle Image/Audio helpers when passed directly inCallToolResult.content
Tests (tests/server/mcpserver/tools/test_base.py)
- Added tests for image, audio, and structured content error results
Usage Example
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.utilities.types import Image
from mcp.types import CallToolResult
mcp = MCPServer("test")
@mcp.tool()
async def my_tool() -> CallToolResult:
# Return an image error directly!
img = Image(data=b"...", format="png")
return CallToolResult.create_error(content=[img])
@mcp.tool()
async def structured_error() -> CallToolResult:
return CallToolResult.create_error(
content=[TextContent(type="text", text="Invalid input")],
structured_content={"error_code": "INVALID_INPUT", "details": {"field": "email"}},
)
Backwards Compatibility
- Existing code using
CallToolResultwithis_error=Truecontinues to work - The auto-conversion only applies when helper objects are detected (no breaking changes)
Testing
All 5,747 existing tests pass + 3 new tests added for the new functionality.