Skip to content

Fix tool calls #38

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 2 commits into from
Mar 5, 2025
Merged

Fix tool calls #38

merged 2 commits into from
Mar 5, 2025

Conversation

ezynda3
Copy link
Contributor

@ezynda3 ezynda3 commented Mar 5, 2025

Summary by CodeRabbit

  • Refactor
    • Streamlined the activation of backend features by deferring initialization until they are needed.
    • Enhanced feedback to users by providing clearer error responses when attempting to use unsupported functionalities.
  • Tests
    • Updated test assertions to reflect changes in expected behavior regarding capability initialization and responses.

Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

Walkthrough

The changes update the server’s approach to handling capabilities in server.go by deferring their initialization. Instead of instantiating tool, resource, and prompt capabilities immediately, these are now set to nil and only initialized when needed. The HandleMessage method now checks for nil to determine if a capability is supported. Additionally, functions like AddResource, AddResourceTemplate, AddPrompt, and AddTools have been modified to dynamically initialize capabilities instead of triggering panics. There are no changes to exported or public entities.

Changes

File(s) Change Summary
server/.../server.go Updated capability initialization in NewMCPServer (default set to nil) and modified HandleMessage to check for nil pointers. Changed panic calls in AddResource, AddResourceTemplate, AddPrompt, and AddTools to lazy initialization.
server/.../server_test.go Adjusted test assertions in TestMCPServer_Capabilities and TestMCPServer_Tools to expect nil values for capabilities, reflecting the new initialization logic. Enhanced validation for tool capabilities response.

Possibly related PRs


📜 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 e8056a1 and eb8d5f0.

📒 Files selected for processing (2)
  • server/server.go (11 hunks)
  • server/server_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/server.go
🔇 Additional comments (3)
server/server_test.go (3)

43-45: Update to nil assertions aligns with server implementation.

This change correctly updates the test assertions to reflect the updated server implementation that now initializes capabilities to nil by default instead of empty non-nil objects. This matches the behavioral change in server.go where capabilities are only initialized when needed.


117-118: Proper assertion for disabled tool capabilities.

The updated assertion properly verifies that tool capabilities are completely nil when WithToolCapabilities(false) is used, rather than checking for a non-nil object with a false flag. This aligns with the server implementation changes where capabilities are set to nil when explicitly disabled.


209-218: Improved validation logic for empty tools list.

The enhanced validation logic provides better test coverage by:

  1. Verifying the response is a proper JSONRPCResponse
  2. Checking that the result is of the expected ListToolsResult type
  3. Asserting the tools list is empty

This is more robust than the previous implementation and provides clearer error messages when tests fail.

✨ 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 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: 0

🔭 Outside diff range comments (3)
server/server.go (3)

524-566: ⚠️ Potential issue

Fix nil pointer dereference in handleInitialize

This section contains a critical error. Since capabilities are now initialized as nil, the handleInitialize method will cause a panic when trying to access fields of nil capability structures.

The pipeline failure confirms this issue: "Panic: runtime error: invalid memory address or nil pointer dereference in MCPServer.handleInitialize."

Here's how to fix it:

func (s *MCPServer) handleInitialize(
    ctx context.Context,
    id interface{},
    request mcp.InitializeRequest,
) mcp.JSONRPCMessage {
    capabilities := mcp.ServerCapabilities{}

-   capabilities.Resources = &struct {
-       Subscribe   bool `json:"subscribe,omitempty"`
-       ListChanged bool `json:"listChanged,omitempty"`
-   }{
-       Subscribe:   s.capabilities.resources.subscribe,
-       ListChanged: s.capabilities.resources.listChanged,
-   }
-
-   capabilities.Prompts = &struct {
-       ListChanged bool `json:"listChanged,omitempty"`
-   }{
-       ListChanged: s.capabilities.prompts.listChanged,
-   }
-
-   capabilities.Tools = &struct {
-       ListChanged bool `json:"listChanged,omitempty"`
-   }{
-       ListChanged: s.capabilities.tools.listChanged,
-   }

+   if s.capabilities.resources != nil {
+       capabilities.Resources = &struct {
+           Subscribe   bool `json:"subscribe,omitempty"`
+           ListChanged bool `json:"listChanged,omitempty"`
+       }{
+           Subscribe:   s.capabilities.resources.subscribe,
+           ListChanged: s.capabilities.resources.listChanged,
+       }
+   }
+
+   if s.capabilities.prompts != nil {
+       capabilities.Prompts = &struct {
+           ListChanged bool `json:"listChanged,omitempty"`
+       }{
+           ListChanged: s.capabilities.prompts.listChanged,
+       }
+   }
+
+   if s.capabilities.tools != nil {
+       capabilities.Tools = &struct {
+           ListChanged bool `json:"listChanged,omitempty"`
+       }{
+           ListChanged: s.capabilities.tools.listChanged,
+       }
+   }

    if s.capabilities.logging {
        capabilities.Logging = &struct{}{}
    }

    result := mcp.InitializeResult{
        ProtocolVersion: mcp.LATEST_PROTOCOL_VERSION,
        ServerInfo: mcp.Implementation{
            Name:    s.name,
            Version: s.version,
        },
        Capabilities: capabilities,
    }

    s.initialized.Store(true)
    return createResponse(id, result)
}
🧰 Tools
🪛 GitHub Actions: go

[error] 535-535: Panic: runtime error: invalid memory address or nil pointer dereference in MCPServer.handleInitialize.


379-385: 🛠️ Refactor suggestion

Inconsistent tools check in handleMessage

In the "tools/list" case, you're checking len(s.tools) == 0 while other capabilities check for nil. This is inconsistent with other methods like "tools/call" which check if s.capabilities.tools == nil.

For consistency with other capability checks, modify this section:

case "tools/list":
-   if len(s.tools) == 0 {
+   if s.capabilities.tools == nil {
        return createErrorResponse(
            baseMessage.ID,
            mcp.METHOD_NOT_FOUND,
            "Tools not supported",
        )
    }

489-495: 🛠️ Refactor suggestion

Missing capability initialization in SetTools

The SetTools method resets the tools map but doesn't initialize the tools capability if it's nil.

Add capability initialization:

// SetTools replaces all existing tools with the provided list
func (s *MCPServer) SetTools(tools ...ServerTool) {
+   if s.capabilities.tools == nil {
+       s.capabilities.tools = &toolCapabilities{}
+   }
    s.mu.Lock()
    s.tools = make(map[string]ServerTool)
    s.mu.Unlock()
    s.AddTools(tools...)
}
🧹 Nitpick comments (2)
server/server.go (2)

465-467: Consider initializing tools capability in AddTool

The AddTool method delegates to AddTools but doesn't initialize the capabilities itself, which is inconsistent with other similar methods.

For consistency with other capability initialization methods:

// AddTool registers a new tool and its handler
func (s *MCPServer) AddTool(tool mcp.Tool, handler ToolHandlerFunc) {
+   if s.capabilities.tools == nil {
+       s.capabilities.tools = &toolCapabilities{}
+   }
    s.AddTools(ServerTool{Tool: tool, Handler: handler})
}

497-512: Consider capability check in DeleteTools

The DeleteTools method doesn't check if the tools capability is initialized.

Add a protection against nil capability:

// DeleteTools removes a tool from the server
func (s *MCPServer) DeleteTools(names ...string) {
+   if s.capabilities.tools == nil {
+       return // Nothing to delete if tools capability isn't enabled
+   }
    s.mu.Lock()
    for _, name := range names {
        delete(s.tools, name)
    }
    initialized := s.initialized.Load()
    s.mu.Unlock()

    // Send notification if server is already initialized
    if initialized {
        if err := s.SendNotificationToClient("notifications/tools/list_changed", nil); err != nil {
            // We can't return the error, but in a future version we could log it
        }
    }
}
🧰 Tools
🪛 golangci-lint (1.62.2)

508-508: SA9003: empty branch

(staticcheck)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between caa195b and e8056a1.

📒 Files selected for processing (1)
  • server/server.go (8 hunks)
🧰 Additional context used
🪛 GitHub Actions: go
server/server.go

[error] 535-535: Panic: runtime error: invalid memory address or nil pointer dereference in MCPServer.handleInitialize.

🔇 Additional comments (4)
server/server.go (4)

214-216: Initialize capabilities to nil by default

The change from initializing capabilities with empty structs to nil values makes sense as it aligns with the updated approach of lazy initialization throughout the server code.


328-334: Check for nil capabilities across request handlers

The changes to check for nil capabilities pointers rather than checking fields is consistent and aligned with the new initialization approach.

Also applies to: 345-351, 362-368, 396-402


425-428: Dynamic initialization of capabilities

Good improvement! The code now dynamically initializes capabilities when they're needed instead of panicking, which improves robustness.

Also applies to: 442-444, 455-457


471-473: Initialize tools capabilities on demand

The change to initialize the tools capability structure on demand is consistent with the other capability initializations.

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.

1 participant