Skip to content

feat: add NewToolResultError #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 29, 2025
Merged

Conversation

daimatz
Copy link
Contributor

@daimatz daimatz commented Mar 28, 2025

Added the NewToolResultError method.
In MCP, when an error occurs during a tool invocation, it is defined that the error message should be included in the contents of the Result object, rather than as a protocol level error.

Summary by CodeRabbit

  • New Features
    • Introduced a standardized error reporting capability to consistently display tool error messages.

Copy link
Contributor

coderabbitai bot commented Mar 28, 2025

Walkthrough

The changes introduce a new function, NewToolResultError, in the mcp/utils.go file. This function creates a CallToolResult configured for error messages by assembling a Content slice with a TextContent element. The function takes a single string parameter for the error message. Existing tool result creation functions remain unaltered.

Changes

File Change Summary
mcp/utils.go Added the NewToolResultError function to create a CallToolResult with a text content representing an error.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 205a459 and 591a196.

📒 Files selected for processing (1)
  • mcp/utils.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • mcp/utils.go

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d3dc35c and 205a459.

📒 Files selected for processing (1)
  • mcp/utils.go (1 hunks)

@ezynda3 ezynda3 merged commit ec9e8a2 into mark3labs:main Mar 29, 2025
1 check passed
@daimatz daimatz deleted the add-ResultError branch March 29, 2025 14:18
@deviantony
Copy link
Contributor

deviantony commented Apr 3, 2025

I feel like this is the return of an error pattern that was previously documented/recommended.

Extract from the README in 0.10.0:

func helloHandler(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    name, ok := request.Params.Arguments["name"].(string)
    if !ok {
        return mcp.NewToolResultError("name must be a string"), nil
    }

    return mcp.NewToolResultText(fmt.Sprintf("Hello, %s!", name)), nil
}

However, the current version of the README favors the usage of errors.New:

s.AddTool(calculatorTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
    op := request.Params.Arguments["operation"].(string)
    x := request.Params.Arguments["x"].(float64)
    y := request.Params.Arguments["y"].(float64)

    var result float64
    switch op {
    case "add":
        result = x + y
    case "subtract":
        result = x - y
    case "multiply":
        result = x * y
    case "divide":
        if y == 0 {
            return nil, errors.New("Division by zero is not allowed")
        }
        result = x / y
    }
    
    return mcp.FormatNumberResult(result), nil
})

@daimatz @ezynda3 What's the idea around this one?

@fabiante
Copy link

fabiante commented Apr 4, 2025

@deviantony I agree with your note, I was also wondering if the error return should only be for technical or otherwise "exceptional" errors, but not for reporting wrong user input.

My use case for MCP is to integrate an API which is known to sometimes fail or timeout. I'd rather have the LLM report back to the user in a human-readable way, what the problem is.

@deviantony
Copy link
Contributor

ping @daimatz @ezynda3 keen to hear your thoughts around that one

@daimatz
Copy link
Contributor Author

daimatz commented Apr 11, 2025

I don't know the history, but according to the MCP protocol, it states that tool-generated errors and protocol-level errors should be separated.

https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/schema/2025-03-26/schema.ts#L686-L697

/**
 * The server's response to a tool call.
 *
 * Any errors that originate from the tool SHOULD be reported inside the result
 * object, with `isError` set to true, _not_ as an MCP protocol-level error
 * response. Otherwise, the LLM would not be able to see that an error occurred
 * and self-correct.
 *
 * However, any errors in _finding_ the tool, an error indicating that the
 * server does not support tool calls, or any other exceptional conditions,
 * should be reported as an MCP error response.
 */

In my personal use case, I use LibreChat to have an LLM generate SQL, which is then run on BigQuery via MCP. The problem is, the SQL that the LLM writes often contains syntax errors, resulting in SQL execution errors. In such cases, rather than returning a protocol-level error, we need to inform the LLM that its input is incorrect and that it should fix the syntax.

I believe this is exactly the kind of situation where the isError field should be used. In fact, instead of doing something like return nil, errors.New("SQL error")—which would be treated as a protocol-level error—I tried signaling the error using the isError field, and that led the LLM to successfully revise the SQL.

@deviantony
Copy link
Contributor

Good to hear @daimatz, I believe that it might be valuable to update the documentation in the README to match this instead of using the errors.New approach then.

I wonder when are you supposed to raise an error as a protocol level error though, any example that could be added as well? I could open a PR afterwards.

@daimatz
Copy link
Contributor Author

daimatz commented Apr 12, 2025

Thanks, adding such an example to the README sounds like a great idea.

MCP states:

  • However, any errors in finding the tool, an error indicating that the
  • server does not support tool calls, or any other exceptional conditions,
  • should be reported as an MCP error response.

This implies that such situations should be treated as protocol-level errors.
In my example, I think this would apply to cases like network failures or internal errors on the BigQuery server.

@deviantony
Copy link
Contributor

I've opened #140 to follow up on this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants