Skip to content

feat(MCPServer): avoid unnecessary notifications when Resource/Tool not exists #266

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
May 10, 2025

Conversation

cryo-zd
Copy link
Contributor

@cryo-zd cryo-zd commented May 10, 2025

Motivation

  While working on an MCPClient, I unintentionally sent DeleteResource request twice with the same URI. I observed that the MCPServer responded with two resources/list_changed notifications, even though the second deletion had no actual effect (the resource had already been removed).
  As a result, the client’s NotificationHandler was triggered twice, leading to redundant processing.
  This behavior highlighted that the server does not currently check whether a resource or tool actually exists before broadcasting a list_changed event.

Problem

  In the original implementation of RemoveResource (and similarly DeleteTools), the server always sends a list_changed notification, regardless of whether the deletion modified the internal state.
  Although safe from a language standpoint (Go’s delete is a no-op for nonexistent keys), this can lead to:

  • Unnecessary client-side handling of notifications,
  • Inaccurate signaling about state changes,
  • Potential for abuse by triggering repeated fake deletions to flood notifications.

  Also, from the specification:

When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification. Sending a DeleteResource request with non-existing resource URI actually incurs no changes to the list of available resource/tools

  I think it could be better for MCPServer to send notifications to MCPClients when the ResourceList/ToolsList actually changes.

What This PR Changes

 This PR updates RemoveResource and DeleteTools to:

  • Check whether the resource/tool actually existed before removal,
  • Only send a list_changed notification if the internal state was modified.

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of resource and tool deletions to ensure notifications are only sent when actual changes occur.
    • Prevented unnecessary notifications when attempting to remove non-existent resources or tools.
  • Tests

    • Updated existing tests to verify that no notifications are sent when removing non-existent resources.
    • Added a new test to confirm correct behavior when deleting non-existent tools.

Copy link
Contributor

coderabbitai bot commented May 10, 2025

Walkthrough

This change updates the logic for removing resources and tools in the server to ensure that deletions and notifications only occur when the specified items actually exist. Corresponding test cases are updated and expanded to verify that no notifications are sent when attempting to remove non-existent resources or tools.

Changes

Files Change Summary
server/server.go Added existence checks before deleting resources or tools; notifications are now only sent if actual deletions occur.
server/resource_test.go Updated test to expect zero notifications when removing a non-existent resource and clarified test naming.
server/server_test.go Added a test to verify that deleting non-existent tools does not trigger notifications or alter the tool list.

Possibly related PRs

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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

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

454-460: Existence tracking for tool deletion.

This implementation tracks whether any tools were actually deleted by setting the exists flag when a tool is found and removed. Minor suggestion: consider explicitly initializing exists to false for clarity, though it's implicitly initialized correctly as is.

-var exists bool
+var exists bool = false
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6429019 and d8ef217.

📒 Files selected for processing (3)
  • server/resource_test.go (2 hunks)
  • server/server.go (2 hunks)
  • server/server_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
server/resource_test.go (1)
mcp/types.go (2)
  • JSONRPCNotification (206-209)
  • JSONRPCMessage (89-89)
server/server_test.go (4)
server/server.go (2)
  • MCPServer (126-151)
  • ServerTool (50-53)
mcp/types.go (5)
  • JSONRPCNotification (206-209)
  • JSONRPCMessage (89-89)
  • MethodNotificationToolsListChanged (62-62)
  • JSONRPCResponse (212-216)
  • Result (187-191)
mcp/tools.go (3)
  • Tool (69-80)
  • NewTool (161-183)
  • ListToolsResult (19-22)
testdata/mockstdio_server.go (1)
  • JSONRPCResponse (18-26)
🔇 Additional comments (6)
server/resource_test.go (2)

100-101: Test name update clarifies intent.

Updated test name clearly indicates that we're now also verifying notification behavior for non-existent resources, which aligns with the PR objective to avoid unnecessary notifications.


133-137: Proper verification of absence of notifications.

These changes correctly implement the PR objective by:

  1. Setting expectedNotifications to 0
  2. Adding an explicit assertion to verify that no notifications are sent when attempting to remove a non-existent resource

This is consistent with the MCP specification which states that notifications should only be sent when the list actually changes.

server/server_test.go (1)

311-338: Good additional test case for non-existent tools.

This test correctly verifies that attempting to delete non-existent tools doesn't trigger unnecessary notifications, which aligns with the PR objective. The test:

  1. Sets up two existing tools with SetTools (generating one notification)
  2. Attempts to delete two non-existent tools
  3. Verifies only the original notification from SetTools is received
  4. Confirms the tool list remains unchanged with the two original tools

This is a good companion to the resource test update and ensures consistent behavior across both resources and tools.

server/server.go (3)

339-342: Existence check before resource deletion.

Good change to check if the resource exists before attempting to delete it. This allows tracking whether a deletion actually occurred, which is necessary to determine if a notification should be sent.


345-346: Conditional notification for resource deletion.

This change correctly implements the PR objective by sending notifications only when:

  1. The resource actually existed and was deleted (exists is true)
  2. The resource capabilities are enabled
  3. The listChanged capability is enabled

This prevents unnecessary notifications when trying to delete non-existent resources.


464-464: Conditional notification for tool deletion.

This change correctly implements the PR objective by sending notifications only when:

  1. At least one tool actually existed and was deleted (exists is true)
  2. The tool capabilities are enabled
  3. The listChanged capability is enabled

This prevents unnecessary notifications when trying to delete non-existent tools.

@robert-jackson-glean robert-jackson-glean merged commit 3442d32 into mark3labs:main May 10, 2025
3 checks passed
@coderabbitai coderabbitai bot mentioned this pull request May 14, 2025
16 tasks
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.

3 participants