Skip to content

Conversation

tjhop
Copy link
Contributor

@tjhop tjhop commented Sep 3, 2025

I noticed that #569 was merged (thanks!) and looked at the diff again
with fresh eyes and noticed that I reused the existing mutex for tool
middlewares within the resource middlewares. This means that, at least
while processing middlewares, it's possible a resource call could be
blocked waiting on a lock because of a tool call or vice-versa.

Since there's a separate mutex for tools, resources, etc, it seems
there's a desire to not block each other. This commit renames the
existing middleware mutex to better clarify it's specifically for tool
middlewares, and adds a new mutex for use specifically with resource
middlewares.

Signed-off-by: TJ Hoplock [email protected]

Summary by CodeRabbit

  • Refactor
    • Decoupled middleware concurrency control for tools and resources to reduce lock contention during parallel operations.
    • Improves responsiveness and scalability under concurrent workloads without changing user-facing behavior or configuration.
    • Enhances stability by isolating middleware execution paths, minimizing cross-impact between resource handling and tool calls.

I noticed that mark3labs#569 was merged (thanks!) and looked at the diff again
with fresh eyes and noticed that I reused the existing mutex for tool
middlewares within the resource middlewares. This means that, at least
while processing middlewares, it's possible a resource call could be
blocked waiting on a lock because of a tool call or vice-versa.

Since there's a separate mutex for tools, resources, etc, it seems
there's a desire to not block each other. This commit renames the
existing middleware mutex to better clarify it's specifically for tool
middlewares, and adds a new mutex for use specifically with resource
middlewares.

Signed-off-by: TJ Hoplock <[email protected]>
Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Walkthrough

Introduces per-type middleware locking in MCPServer by replacing a single mutex with separate RWMutexes for resource and tool middlewares, updating registration functions to use these locks, and applying read locks during middleware invocation in handleReadResource and handleToolCall. Struct fields updated accordingly; initialization otherwise unchanged.

Changes

Cohort / File(s) Summary of Changes
Middleware locking refactor
server/server.go
Replaced middlewareMu with resourceMiddlewareMu and toolMiddlewareMu (both sync.RWMutex). Updated WithResourceHandlerMiddleware and WithToolHandlerMiddleware to use respective mutexes. Wrapped resource middleware in handleReadResource with RLock/RUnlock and tool middleware in handleToolCall with RLock/RUnlock. No other init changes.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 (2)
server/server.go (2)

880-886: Snapshot middlewares under lock before applying them.

Take a shallow copy while holding RLock so later in-place mutations (should they be introduced) can’t race with iteration here.

Apply:

-        s.resourceMiddlewareMu.RLock()
-        mw := s.resourceHandlerMiddlewares
+        s.resourceMiddlewareMu.RLock()
+        mw := append([]ResourceHandlerMiddleware(nil), s.resourceHandlerMiddlewares...)
         // Apply middlewares in reverse order
         for i := len(mw) - 1; i >= 0; i-- {
             finalHandler = mw[i](finalHandler)
         }
-        s.resourceMiddlewareMu.RUnlock()
+        s.resourceMiddlewareMu.RUnlock()

Also, confirm whether resource middlewares are intentionally not applied to template handlers below (matchedHandler path). If they should be, we can adapt by wrapping a ResourceHandlerFunc adapter around matchedHandler.


1142-1149: Do the same snapshot for tool middlewares.

Mirror the resource change to avoid any future in-place edits racing with reads.

Apply:

-    s.toolMiddlewareMu.RLock()
-    mw := s.toolHandlerMiddlewares
+    s.toolMiddlewareMu.RLock()
+    mw := append([]ToolHandlerMiddleware(nil), s.toolHandlerMiddlewares...)
     // Apply middlewares in reverse order
     for i := len(mw) - 1; i >= 0; i-- {
         finalHandler = mw[i](finalHandler)
     }
-    s.toolMiddlewareMu.RUnlock()
+    s.toolMiddlewareMu.RUnlock()
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3d1bfca and 9a9ef76.

📒 Files selected for processing (1)
  • server/server.go (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-23T11:10:42.948Z
Learnt from: floatingIce91
PR: mark3labs/mcp-go#401
File: server/server.go:1082-1092
Timestamp: 2025-06-23T11:10:42.948Z
Learning: In Go MCP server, ServerTool.Tool field is only used for tool listing and indexing, not for tool execution or middleware. During handleToolCall, only the Handler field is used, so dynamic tools don't need the Tool field populated.

Applied to files:

  • server/server.go
🔇 Additional comments (3)
server/server.go (3)

225-228: Correct: exclusive lock around append to tool middlewares.

Write-side is properly synchronized.


237-240: Correct: exclusive lock around append to resource middlewares.

Write-side is properly synchronized.


150-150: No leftover middlewareMu references; split locks confirmed safe.

@ezynda3 ezynda3 merged commit 71a5805 into mark3labs:main Sep 11, 2025
4 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