Skip to content

Add duplicate tool warning log and test logger for MCPServer #439

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

tosolveit
Copy link

@tosolveit tosolveit commented Jun 23, 2025

Description

Hi, Changes in this PR,

  • Added a logger field to MCPServer with a safe default logger.
  • Added a WithMCPLogger server option to inject a custom logger (useful for tests or structured logging).
  • Updated AddTools to emit an Infof log when a duplicate tool name is detected and overwritten.
  • Added a TestLogger helper under testutil to capture logs in tests.
  • Updated TestMCPServer_Tools to verify that the warning log is actually emitted when duplicate tools are added.
  • Made tool names in the race condition test more unique by adding a random suffix, ensuring no accidental duplicates interfere with concurrency checks.

Fixes #390

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • MCP spec compatibility implementation
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Code refactoring (no functional changes)
  • Performance improvement
  • Tests only (no functional changes)
  • Other (please describe):

Checklist

  • My code follows the code style of this project
  • I have performed a self-review of my own code
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the documentation accordingly

MCP Spec Compliance

  • This change is a server-side operational improvement (logging duplicate tool registrations) and does not change protocol semantics or MCP spec compliance.

Additional Information

This PR enhances server observability by logging when a tool is added with a name that already exists, avoiding silent overwrites.
Added a pluggable logger to MCPServer (with a safe default implementation) and a test logger for verifying log output in unit tests.
No protocol-level changes were made, so no client impact.

Summary by CodeRabbit

  • New Features

    • Added logging when a tool with the same name is overwritten, providing more transparency during tool management.
  • Bug Fixes

    • Improved uniqueness of tool names in concurrent add operations to reduce naming collisions during testing.
  • Tests

    • Added a test to verify that adding a tool with an existing name overwrites the previous entry and logs a message.
    • Introduced a test logger to capture and inspect log output during tests.

Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

"""

Walkthrough

The changes introduce a logger to the MCPServer, allowing it to log an informational message when a tool with a duplicate name is added and overwritten. A new test ensures this logging occurs, and a test logger utility is added for capturing log output. Minor improvements are made to race condition testing.

Changes

Files/Paths Change Summary
server/server.go Added logger field to MCPServer, new WithMCPLogger option, log message on duplicate tool overwrite.
server/server_test.go Added a test for overwriting tools and verifying log output for duplicate tool name warning.
testutil/testlogger.go Introduced TestLogger struct for capturing logs during tests.
server/server_race_test.go Improved uniqueness of tool names in race condition test by adding random integer to tool name.

Assessment against linked issues

Objective Addressed Explanation
Log a warning or error when attempting to add a tool with a duplicate name (#390)
Ensure AddTools does not silently override duplicated tools, but logs the event (#390)

Assessment against linked issues: Out-of-scope changes

Code Change (file_path) Explanation
Improve uniqueness of tool names in race test (server/server_race_test.go) This change improves test robustness but is not directly related to logging duplicate tool additions as required by #390.

Suggested labels

type: enhancement

Suggested reviewers

  • pottekkat
  • robert-jackson-glean
    """

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 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 2ae750a and 0811b7a.

📒 Files selected for processing (4)
  • server/server.go (5 hunks)
  • server/server_race_test.go (2 hunks)
  • server/server_test.go (4 hunks)
  • testutil/testlogger.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • server/server_race_test.go
  • testutil/testlogger.go
  • server/server.go
  • server/server_test.go
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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 (2)
testutil/testlogger.go (1)

12-18: Consider adding constructor function for better usability.

While the current implementation works, consider adding a constructor function to improve usability and ensure proper initialization:

+// NewTestLogger creates a new TestLogger with an initialized buffer
+func NewTestLogger() *TestLogger {
+	return &TestLogger{Buf: &bytes.Buffer{}}
+}
+
 func (l *TestLogger) Infof(format string, v ...any) {
 	fmt.Fprintf(l.Buf, "INFO: "+format, v...)
 }

This would prevent potential nil pointer dereferences if Buf is not properly initialized.

server/server_race_test.go (1)

60-60: Excellent improvement for reducing name collisions.

Adding rand.Int() to the tool name generation significantly reduces the likelihood of collisions during concurrent operations, making the race condition tests more robust.

Consider seeding the random number generator for better randomness:

+import (
+	"math/rand"
+	"time"
+)
+
+func init() {
+	rand.Seed(time.Now().UnixNano())
+}

However, this is optional since the current approach is sufficient for test purposes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f5b048 and 2ae750a.

📒 Files selected for processing (4)
  • server/server.go (5 hunks)
  • server/server_race_test.go (2 hunks)
  • server/server_test.go (4 hunks)
  • testutil/testlogger.go (1 hunks)
🔇 Additional comments (11)
testutil/testlogger.go (1)

8-10: LGTM: Clean test logger implementation.

The TestLogger struct is well-designed for its purpose of capturing log output during tests.

server/server_race_test.go (1)

6-6: Good addition for improved test robustness.

Adding the math/rand import supports the enhanced tool name generation.

server/server.go (5)

14-14: Good import addition for logging functionality.

The util import provides access to the Logger interface and DefaultLogger implementation.


164-164: Well-placed logger field in MCPServer struct.

Adding the logger field to the MCPServer struct enables configurable logging throughout the server lifecycle.


286-290: Excellent implementation of logger configuration option.

The WithMCPLogger function follows the established functional options pattern and provides a clean way to inject custom loggers for testing or structured logging.


319-319: Safe default logger initialization.

Initializing with util.DefaultLogger() ensures the server always has a functional logger, preventing nil pointer issues.


486-488: Appropriate logging for duplicate tool detection.

The informational log message when overwriting duplicate tools improves observability without being overly verbose. The placement within the existing mutex protection ensures thread safety.

server/server_test.go (4)

4-4: Good imports for enhanced testing capabilities.

The bytes and testutil imports support the new test logger functionality for verifying log output.

Also applies to: 16-16


347-380: Comprehensive test case for duplicate tool handling.

This test case effectively validates both the functional behavior (tool overwriting) and the expected notifications. The test structure is well-organized and follows the established pattern in the file.


386-390: Excellent integration of test logger.

The setup properly initializes the TestLogger and configures the server to use it via WithMCPLogger, enabling verification of logging behavior in tests.


418-421: Effective log output verification.

The conditional check ensures that log output verification only runs for the relevant test case, and the assertion properly validates that the expected warning message is logged when duplicate tools are added.

@tosolveit tosolveit force-pushed the enhancement/390-add-warning-to-AddTools branch from 2ae750a to 0811b7a Compare June 23, 2025 16:09
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.

feature: AddTools logic should handle duplicated tool names
2 participants