Skip to content

feat: Tool Handler Middleware #123

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 3 commits into from
Apr 11, 2025

Conversation

wimspaargaren
Copy link
Contributor

@wimspaargaren wimspaargaren commented Apr 8, 2025

While trying out mcp host with model --model ollama:llama3.2:latest and the mcp calculator server example, I noticed the tool call sometimes gets stuck. After some investigation, I figured out that the values of x and y are sometimes received as string instead of float64.

Because of this, the toolHandlerFunc in the server will panic (as the type cast is not being checked in the example) and the client will hang until the context times out.

From a client perspective it's hard to figure out what is going on when a toolHandlerFunc panics, as it waits until it receives a message where an ID is set.

I think this issue might be related as well: mark3labs/mcphost#11

In order to address this, this PR adds a ToolHandlerMiddlware which can be added via the ServerOption.

This PR includes:

  • A WithToolHandlerMiddleware option to add toolHandler middlewares
  • A WithRecovery option to let the server recover from panics in toolHandler function calls
  • A section in the README describing how to use toolHandlerMiddlewares
  • A recovery option in the calculator example

Summary by CodeRabbit

  • New Features
    • Introduced recovery middleware for enhanced error handling during tool calls.
    • Added a new section on tool handler middleware in documentation.
  • Documentation
    • Updated README to include details on new middleware options for improved server resilience.
  • Tests
    • Added tests to ensure the server recovers gracefully from panics in tool handlers.

Copy link
Contributor

coderabbitai bot commented Apr 8, 2025

Walkthrough

The pull request introduces a middleware mechanism for tool handlers in the MCP server. It updates the documentation to describe two new server options: one for adding tool handler middleware and another for recovery from panics during tool calls. In the implementation, a new middleware type and a middleware slice in the MCPServer have been added, along with functions to register middleware and recovery behavior. The middleware is applied in reverse order, and tests have been added to verify that the server recovers correctly from panics in tool handler execution.

Changes

File Change Summary
README.md Updated documentation to include new server options WithRecovery() and WithToolHandlerMiddleware(). Added a "Tool Handler Middleware" section explaining how to register middleware for tool calls.
server/server.go Introduced a middleware mechanism for tool handlers by adding a new type (ToolHandlerMiddleware), a middleware slice to the MCPServer, and functions WithToolHandlerMiddleware() and WithRecovery(). Updated handleToolCall to apply middleware in reverse order.
server/server_test.go Added a test function TestMCPServer_WithRecover to verify that the server can recover from panics in tool handlers when using the WithRecovery() option. The test checks for proper error handling and response structure upon panic.

📜 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 5766c8d and f5a3593.

📒 Files selected for processing (3)
  • README.md (2 hunks)
  • server/server.go (4 hunks)
  • server/server_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • README.md
  • server/server.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
server/server_test.go (3)
mcp/tools.go (2)
  • CallToolRequest (44-59)
  • CallToolResult (34-41)
server/server.go (2)
  • NewMCPServer (366-392)
  • WithRecovery (309-320)
mcp/types.go (2)
  • JSONRPCError (205-218)
  • INTERNAL_ERROR (226-226)
🔇 Additional comments (1)
server/server_test.go (1)

1349-1380: Well-implemented test for panic recovery in tool handlers.

This test effectively validates the new WithRecovery() functionality, which is a key part of the PR's objective to handle panics when tool handlers receive incorrect types. The test creates a scenario where a tool handler deliberately panics, and then verifies that the server recovers properly and returns a structured error response instead of crashing.

The test correctly:

  1. Creates a panic-inducing tool handler
  2. Instantiates a server with the recovery middleware
  3. Verifies the server returns an appropriate error response with the expected error code and message

This addresses the core issue mentioned in the PR description where type conversion errors were causing the client to hang until context timeout.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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

🧹 Nitpick comments (2)
server/server.go (2)

42-44: Fix the type name to avoid confusion
The type name appears to have a minor misspelling ("Middlware" instead of "Middleware"), which could lead to confusion or inconsistency in the codebase.

Apply this diff to correct the spelling:

-type ToolHandlerMiddlware func(ToolHandlerFunc) ToolHandlerFunc
+type ToolHandlerMiddleware func(ToolHandlerFunc) ToolHandlerFunc

298-310: Consider capturing stack traces for better debugging
While panic recovery is implemented correctly, adding a stack trace can assist in diagnosing issues that lead to panics.

Example diff:

 import (
+   "runtime/debug"
    ...
 )

 func WithRecovery() ServerOption {
     return WithToolHandlerMiddleware(func(next ToolHandlerFunc) ToolHandlerFunc {
         return func(ctx context.Context, request mcp.CallToolRequest) (result *mcp.CallToolResult, err error) {
             defer func() {
                 if r := recover(); r != nil {
-                    err = fmt.Errorf("panic recovered in %s tool handler: %v", request.Params.Name, r)
+                    stack := debug.Stack()
+                    err = fmt.Errorf("panic recovered in %s tool handler: %v\nStack trace:\n%s", request.Params.Name, r, stack)
                 }
             }()
             return next(ctx, request)
         }
     })
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a0e968a and 857743c.

📒 Files selected for processing (3)
  • README.md (2 hunks)
  • server/server.go (4 hunks)
  • server/server_test.go (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
server/server_test.go (3)
mcp/tools.go (3)
  • CallToolRequest (44-59)
  • CallToolResult (34-41)
  • NewTool (127-142)
server/server.go (2)
  • NewMCPServer (356-382)
  • WithRecovery (299-310)
mcp/types.go (2)
  • JSONRPCError (205-218)
  • INTERNAL_ERROR (226-226)
🔇 Additional comments (5)
server/server.go (2)

142-155: Initialization of new fields looks good
The added fields, including the new RWMutex and the additional slice for tool handler middlewares, appear consistent with the rest of the struct.


288-296: Straightforward middleware registration
The functional option pattern for adding tool handler middleware is clear and aligns well with existing patterns.

README.md (2)

125-125: Recovery middleware reference
Including the server.WithRecovery() call in the server initialization is a clear illustration of the new feature.


527-531: Documentation of tool handler middleware is succinct and clear
The new section effectively explains how to add and use tool handler middleware, including panic recovery.

server/server_test.go (1)

1347-1378: Good test coverage for panic recovery
The new test effectively validates that panics in tool handlers are recovered and translated into the correct JSON-RPC error response.

@wimspaargaren wimspaargaren force-pushed the mcp-go-tool-handler-middleware branch from 857743c to 5766c8d Compare April 8, 2025 11:20
@wimspaargaren wimspaargaren changed the title Tool Handler Middleware feat: Tool Handler Middleware Apr 8, 2025
@wimspaargaren wimspaargaren force-pushed the mcp-go-tool-handler-middleware branch from 5766c8d to f5a3593 Compare April 10, 2025 20:11
@ezynda3 ezynda3 merged commit b8dc82d into mark3labs:main Apr 11, 2025
2 checks passed
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.

2 participants