feat(mcpserver): let ToolError carry content for is_error results

Closed
RA
1mo ago
+58-3

Summary

Closes #348.

Tool authors currently have no way to return a CallToolResult with is_error=True that carries non-text content — raising an exception only surfaces the message as text. This implements the approach @Kludex suggested in the issue: give ToolError an optional content field that is translated to the error result internally.

What changed

  • ToolError accepts an optional keyword content: list[ContentBlock] | None. When set, it becomes the CallToolResult.content; otherwise behavior is unchanged (the message is returned as text).
  • The tool layer (Tool.run) preserves content when it wraps a raised ToolError, so the content survives to the result.
  • _handle_call_tool returns the attached content for an errored result when present.

A plain ToolError("...") behaves exactly as before — this is purely additive and non-breaking.

@mcp.tool()
def render() -> str:
    raise ToolError(
        "rendering failed",
        content=[ImageContent(type="image", data=..., mime_type="image/png")],
    )
# -> CallToolResult(content=[ImageContent(...)], is_error=True)

Tests / checks

  • Added a test covering an image-bearing ToolError.
  • Existing tool-error behavior (including the snapshot test) is unchanged.
  • ./scripts/test passes at 100% coverage; pyright and ruff are clean.

Disclosure

Developed with AI assistance. I've reviewed the change and can explain every line.