Skip to content

feat(get-server-tools): add GetTools method for retrieve MCPServer.tools #437

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

ValeriiStepanets
Copy link

@ValeriiStepanets ValeriiStepanets commented Jun 23, 2025

Description

This PR adds the GetTools method for retrieving the MCPServer.tools.
Initially, I was developing the custom tools manager for my project, but faced the issue that I couldn't synchronize MCPServer.tools with the custom Tools manager list of tools, which could possibly lead to issues.

Fixes #<issue_number> (if applicable)

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 PR implements a feature defined in the MCP specification
  • Link to relevant spec section: Link text
  • Implementation follows the specification exactly

Additional Information

This PR adds comprehensive tests for the GetTools method in the MCPServer.

Changes

  • Added TestMCPServer_GetTools with 8 test cases covering:
    • Empty server state
    • Single tool retrieval
    • Multiple tools retrieval
    • Tool deletion effects
    • SetTools replacement behavior
    • Concurrent access (thread safety)
    • Consistent results across multiple calls
    • Complex tool schema preservation

Test Coverage

  • Thread safety testing with 100 concurrent goroutines
  • Complex tool schema with annotations
  • Error handling verification

All tests pass and integrate well with the existing test suite.

Summary by CodeRabbit

  • New Features

    • Introduced the ability to retrieve the current list of registered tools from the server.
  • Tests

    • Added comprehensive tests to ensure correct retrieval and management of tools, including edge cases and concurrent access scenarios.

Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

Walkthrough

A new method, GetTools, was added to the MCPServer type in the server implementation, providing thread-safe access to the registered tools map. Comprehensive tests for this method were introduced, covering empty, single, multiple, deletion, replacement, concurrency, repeated calls, copy integrity, and complex schema scenarios.

Changes

Files Change Summary
server/server.go Added GetTools method to MCPServer for thread-safe retrieval of the registered tools map.
server/server_test.go Added TestMCPServer_GetTools with multiple subtests validating GetTools behavior, concurrency, and schema handling.

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

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

📜 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 2cd60ac.

📒 Files selected for processing (2)
  • server/server.go (1 hunks)
  • server/server_test.go (1 hunks)
🔇 Additional comments (2)
server/server_test.go (2)

2026-2380: Excellent comprehensive test coverage.

The test suite covers all important scenarios including edge cases, concurrency, and complex schemas. The test structure with subtests is well-organized and the assertions are thorough.


2210-2259: Improve concurrent test to avoid potential race conditions.

The current concurrent test has timing issues where multiple goroutines add tools concurrently, but the verification logic doesn't guarantee all tools are added before GetTools is called in each goroutine.

Consider this improved approach:

 	t.Run("ConcurrentAccess", func(t *testing.T) {
 		server := NewMCPServer("test-server", "1.0.0")
 
-		// Number of goroutines for testing
-		numGoroutines := 100
-		numToolsPerGoroutine := 10
+		// Pre-add some tools to test concurrent reads
+		for i := 0; i < 50; i++ {
+			server.AddTool(mcp.Tool{
+				Name:        fmt.Sprintf("pre-tool-%d", i),
+				Description: fmt.Sprintf("Pre-added tool %d", i),
+			}, nil)
+		}
 
-		// Channel to collect results
-		results := make(chan map[string]ServerTool, numGoroutines)
+		numGoroutines := 100
+		results := make(chan map[string]ServerTool, numGoroutines)
+		var wg sync.WaitGroup
 
-		// Start goroutines that concurrently call GetTools
+		// Test concurrent reads (no race conditions in test logic)
 		for i := 0; i < numGoroutines; i++ {
+			wg.Add(1)
 			go func(id int) {
-				// Add some tools specific to this goroutine
-				for j := 0; j < numToolsPerGoroutine; j++ {
-					toolName := fmt.Sprintf("tool-%d-%d", id, j)
-					server.AddTool(mcp.Tool{
-						Name:        toolName,
-						Description: fmt.Sprintf("Tool %d from goroutine %d", j, id),
-					}, nil)
-				}
-
-				// Get tools
+				defer wg.Done()
 				tools, err := server.GetTools()
 				assert.NoError(t, err)
 				results <- tools
 			}(i)
 		}
 
+		wg.Wait()
+		close(results)
+		
 		// Collect all results
 		var allResults []map[string]ServerTool
-		for i := 0; i < numGoroutines; i++ {
-			result := <-results
+		for result := range results {
 			allResults = append(allResults, result)
 		}
 
 		// Verify that no data races occurred and all results are valid
 		for _, result := range allResults {
 			assert.NotNil(t, result)
-			// Each result should have at least some tools (may not have all due to timing)
-			assert.Greater(t, len(result), 0)
+			assert.Equal(t, 50, len(result), "All concurrent reads should return same number of tools")
 		}
-
-		// Final check - get all tools at the end
-		finalTools, err := server.GetTools()
-		assert.NoError(t, err)
-		assert.NotNil(t, finalTools)
-		// Should have exactly numGoroutines * numToolsPerGoroutine tools
-		assert.Equal(t, numGoroutines*numToolsPerGoroutine, len(finalTools))
 	})

Likely an incorrect or invalid review comment.

@zsvs
Copy link

zsvs commented Jun 23, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ValeriiStepanets
Copy link
Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jun 24, 2025

✅ Actions performed

Full review triggered.

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)

496-510: Consider returning empty map instead of error for no tools.

The current implementation returns an error when no tools are registered, but this may not align with Go conventions. Typically, empty collections return empty maps rather than errors unless the absence of data represents a true error condition.

Consider this approach instead:

-// GetTools retrieves the currently registered tools
-func (s *MCPServer) GetTools() (map[string]ServerTool, error) {
-	s.toolsMu.RLock()
-	defer s.toolsMu.RUnlock()
-	// Create a copy to prevent external modification
-	if len(s.tools) == 0 {
-		return nil, fmt.Errorf("no tools registered")
-	}
-	toolsCopy := make(map[string]ServerTool, len(s.tools))
-	for name, tool := range s.tools {
-		toolsCopy[name] = tool
-	}
-	return toolsCopy, nil
-}
+// GetTools retrieves the currently registered tools
+func (s *MCPServer) GetTools() (map[string]ServerTool, error) {
+	s.toolsMu.RLock()
+	defer s.toolsMu.RUnlock()
+	// Create a copy to prevent external modification
+	toolsCopy := make(map[string]ServerTool, len(s.tools))
+	for name, tool := range s.tools {
+		toolsCopy[name] = tool
+	}
+	return toolsCopy, nil
+}

However, if the current error behavior is intentional for your API design, the implementation is otherwise correct with proper concurrency safety and data encapsulation.

📜 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 d13b0ed.

📒 Files selected for processing (2)
  • server/server.go (1 hunks)
  • server/server_test.go (2 hunks)
🔇 Additional comments (2)
server/server_test.go (2)

11-11: Good addition of sync import for concurrent testing.

The sync import is appropriately added to support the concurrent access testing in the new test suite.


2027-2419: Excellent comprehensive test suite for GetTools method.

This test suite is exceptionally well-designed and thorough, covering:

  • Edge cases: Empty server state, single and multiple tools
  • State modifications: Tool deletion and replacement via SetTools
  • Concurrency safety: 100 goroutines testing thread safety
  • Data integrity: Verification that copies are returned, not references
  • Complex scenarios: Complex tool schemas with nested properties and annotations
  • Consistency: Multiple calls returning identical results

The concurrent test properly uses goroutines with synchronization to collect results and verify no data races occur. The copy verification test effectively demonstrates that external modifications don't affect the server's internal state.

Key strengths:

  • Proper use of sync.WaitGroup for concurrent testing
  • Comprehensive assertion coverage with meaningful error messages
  • Tests validate both data correctness and behavioral expectations
  • Good separation of concerns with focused sub-tests

@ValeriiStepanets
Copy link
Author

Hello @ezynda3, could you please take a look

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