mcp-go icon indicating copy to clipboard operation
mcp-go copied to clipboard

Returning errors from tools

Open corani opened this issue 8 months ago • 3 comments

The ToolHandlerFunc has a return type of (*CallToolResult, error). I had assumed that if something was wrong I could return an error (e.g. return nil, fmt.Errorf("entity not found: %v", id)) and this would bubble up to the LLM. This doesn't appear to be the case, it seems the LLM simply gets an empty response, and therefor doesn't know what happened. If instead I return NewToolResultText(fmt.Sprintf("entity not found: %v", id)), nil it does work.

I haven't debugged through it, so I may be mistaken...

What is the intended behavior here?

corani avatar Apr 16 '25 04:04 corani

@corani see the discussions in https://github.com/mark3labs/mcp-go/pull/87 and https://github.com/mark3labs/mcp-go/pull/140 about error handling.

TLDR: use NewToolResultError and NewToolResultErrorFromErr to propagate the error back to the LLM.

Looks like I forgot to update the first example in the README on my last pass.

deviantony avatar Apr 17 '25 19:04 deviantony

Thanks, so in practice there is almost no case where you would actually return an error from inside a tool handler?

corani avatar Apr 18 '25 07:04 corani

That's also my current understanding yep

deviantony avatar Apr 20 '25 05:04 deviantony