1515from mcp .types import GetTaskResult , TaskStatusNotification
1616
1717from fastmcp .client .messages import Message , MessageHandler
18+ from fastmcp .exceptions import ToolError
1819from fastmcp .utilities .logging import get_logger
1920
2021logger = get_logger (__name__ )
@@ -335,6 +336,7 @@ def __init__(
335336 task_id : str ,
336337 tool_name : str ,
337338 immediate_result : CallToolResult | None = None ,
339+ raise_on_error : bool = True ,
338340 ):
339341 """
340342 Create a ToolTask wrapper.
@@ -344,9 +346,11 @@ def __init__(
344346 task_id: The task identifier
345347 tool_name: Name of the tool being executed
346348 immediate_result: If server executed synchronously, the immediate result
349+ raise_on_error: Whether task.result() should raise ToolError on errors
347350 """
348351 super ().__init__ (client , task_id , immediate_result )
349352 self ._tool_name = tool_name
353+ self ._raise_on_error = raise_on_error
350354
351355 async def result (self ) -> CallToolResult :
352356 """Wait for and return the tool result.
@@ -364,6 +368,14 @@ async def result(self) -> CallToolResult:
364368 if self ._is_immediate :
365369 assert self ._immediate_result is not None # Type narrowing
366370 result = self ._immediate_result
371+ if result .is_error and self ._raise_on_error :
372+ if result .content and isinstance (
373+ result .content [0 ], mcp .types .TextContent
374+ ):
375+ msg = result .content [0 ].text
376+ else :
377+ msg = f"Tool '{ self ._tool_name } ' returned an error"
378+ raise ToolError (msg )
367379 else :
368380 # Check client connected
369381 self ._check_client_connected ()
@@ -379,12 +391,16 @@ async def result(self) -> CallToolResult:
379391 # Raw dict from get_task_result - parse as CallToolResult
380392 mcp_result = mcp .types .CallToolResult .model_validate (raw_result )
381393 result = await self ._client ._parse_call_tool_result (
382- self ._tool_name , mcp_result , raise_on_error = True
394+ self ._tool_name ,
395+ mcp_result ,
396+ raise_on_error = self ._raise_on_error ,
383397 )
384398 elif isinstance (raw_result , mcp .types .CallToolResult ):
385399 # Already a CallToolResult from MCP protocol - parse it
386400 result = await self ._client ._parse_call_tool_result (
387- self ._tool_name , raw_result , raise_on_error = True
401+ self ._tool_name ,
402+ raw_result ,
403+ raise_on_error = self ._raise_on_error ,
388404 )
389405 else :
390406 # Legacy ToolResult format - convert to MCP type
@@ -397,7 +413,9 @@ async def result(self) -> CallToolResult:
397413 _meta = raw_result .meta , # type: ignore[call-arg] # _meta is Pydantic alias for meta field # ty:ignore[unknown-argument]
398414 )
399415 result = await self ._client ._parse_call_tool_result (
400- self ._tool_name , mcp_result , raise_on_error = True
416+ self ._tool_name ,
417+ mcp_result ,
418+ raise_on_error = self ._raise_on_error ,
401419 )
402420 else :
403421 # Unknown type - just return it
0 commit comments