feat(mcpserver): let ToolError carry content for is_error results
Closed
RA
1mo ago+58+58+01234567890123456789-3-3-0123456789
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
ToolErroraccepts an optional keywordcontent: list[ContentBlock] | None. When set, it becomes theCallToolResult.content; otherwise behavior is unchanged (the message is returned as text).- The tool layer (
Tool.run) preservescontentwhen it wraps a raisedToolError, so the content survives to the result. _handle_call_toolreturns 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/testpasses at 100% coverage;pyrightandruffare clean.
Disclosure
Developed with AI assistance. I've reviewed the change and can explain every line.