Add isError support for non-text tool results (Fixes #348)

Closed
MU
3mo ago
+244-5

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_validator to 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_result to handle Image/Audio helpers when passed directly in CallToolResult.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 CallToolResult with is_error=True continues 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.