Skip to content

feat: implement Interface for MCPServer and update server references #424

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

paulgrammer
Copy link

@paulgrammer paulgrammer commented Jun 20, 2025

Description

Introduce Interface for server extensibility to decouple server implementations from the concrete MCPServer type, enabling custom server implementations while maintaining full backward compatibility.

This allows developers to implement custom server behavior (logging, metrics, rate limiting, etc.) by wrapping the core server functionality through a well-defined interface contract.

Type of Change

  • New feature (non-breaking change that adds functionality)
  • Code refactoring (no functional changes)

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

Additional Information

Problem

All transports (SSEServer, StdioServer, StreamableHTTPServer) are tightly coupled to *MCPServer, preventing custom server implementations for logging, metrics, rate limiting, etc.

Solution

Add Interface defining the complete server contract:

type Interface interface {
   // Message handling
   HandleMessage(ctx context.Context, message json.RawMessage) mcp.JSONRPCMessage
   
   // Session management
   RegisterSession(ctx context.Context, session ClientSession) error
   UnregisterSession(ctx context.Context, sessionID string)
   WithContext(ctx context.Context, session ClientSession) context.Context
   
   // Notifications
   SendNotificationToClient(ctx context.Context, method string, params map[string]any) error
   SendNotificationToSpecificClient(sessionID string, method string, params map[string]any) error
   SendNotificationToAllClients(method string, params map[string]any)
   
   // Session-specific tools
   AddSessionTool(sessionID string, tool mcp.Tool, handler ToolHandlerFunc) error
   AddSessionTools(sessionID string, tools ...ServerTool) error
   DeleteSessionTools(sessionID string, names ...string) error
   
   // Global server configuration
   AddTool(tool mcp.Tool, handler ToolHandlerFunc)
   AddTools(tools ...ServerTool)
   DeleteTools(names ...string)
   AddPrompt(prompt mcp.Prompt, handler PromptHandlerFunc)
   AddPrompts(prompts ...ServerPrompt)
   DeletePrompts(names ...string)
   AddResource(resource mcp.Resource, handler ResourceHandlerFunc)
   AddResources(resources ...ServerResource)
   RemoveResource(uri string)
   AddResourceTemplate(template mcp.ResourceTemplate, handler ResourceTemplateHandlerFunc)
}

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
  - Introduced a custom server with enhanced structured logging for all server operations, providing improved observability and diagnostics.
  - Added example tools and resources with detailed usage logging.

- **Refactor**
  - Generalized server components to accept any server implementation via an interface, enabling greater flexibility and extensibility for server integrations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Copy link
Contributor

coderabbitai bot commented Jun 20, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

"""

Walkthrough

This change introduces a new Interface abstraction for MCP server transports, updates all server implementations to use this interface instead of a concrete type, and adds an example custom server with structured logging. The update generalizes server dependencies, enabling flexible implementations and enhanced observability.

Changes

File(s) Change Summary
examples/custom_server/main.go Added a new example: custom MCP server with structured logging, tool/resource registration, and graceful shutdown.
server/server_interface.go Introduced Interface abstraction for MCP server transports, defining core session, message, and tool management.
server/sse.go, server/stdio.go, server/streamable_http.go Changed server fields and constructors to use the new Interface type instead of concrete *MCPServer.

Possibly related PRs

Suggested labels

type: enhancement, area: sdk

Suggested reviewers

  • robert-jackson-glean
  • pottekkat
    """

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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0fdb197 and 5533d56.

📒 Files selected for processing (5)
  • examples/custom_server/main.go (1 hunks)
  • server/server_interface.go (1 hunks)
  • server/sse.go (3 hunks)
  • server/stdio.go (2 hunks)
  • server/streamable_http.go (2 hunks)
🔇 Additional comments (5)
server/stdio.go (1)

28-28: LGTM! Clean interface abstraction.

The change from concrete *MCPServer to Interface type properly implements dependency inversion, enabling extensibility while maintaining backward compatibility.

Also applies to: 115-115

server/streamable_http.go (1)

120-120: LGTM! Consistent interface adoption.

The changes align with the interface abstraction pattern applied across all server implementations.

Also applies to: 135-135

server/sse.go (1)

121-121: LGTM! Complete interface migration including test utilities.

The interface abstraction is consistently applied to both the main constructor and test helper, ensuring uniformity across the codebase.

Also applies to: 261-261, 280-280

server/server_interface.go (1)

1-54: Excellent interface design with comprehensive documentation.

The Interface abstraction is well-structured with:

  • Clear method signatures covering all essential server operations
  • Thorough documentation for each method
  • Proper compile-time validation that MCPServer implements the interface
  • Good separation of concerns enabling custom implementations

This follows interface segregation and dependency inversion principles effectively.

examples/custom_server/main.go (1)

1-257: Excellent example implementation demonstrating interface extensibility.

This custom server implementation effectively showcases:

  • Clean wrapper pattern for adding cross-cutting concerns
  • Comprehensive structured logging using slog
  • Proper delegation to the wrapped server
  • Production-ready server lifecycle management with graceful shutdown

This serves as a great reference for developers wanting to extend MCP server functionality.

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)
examples/custom_server/main.go (1)

31-64: Handle JSON unmarshaling error for better robustness.

The logging implementation is comprehensive, but the JSON unmarshaling on line 37 should handle potential errors for better robustness.

Apply this diff to handle the unmarshaling error:

-	json.Unmarshal(message, &baseMsg)
+	if err := json.Unmarshal(message, &baseMsg); err != nil {
+		l.logger.WarnContext(ctx, "failed to parse message for logging", slog.String("error", err.Error()))
+	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5533d56 and d630605.

📒 Files selected for processing (5)
  • examples/custom_server/main.go (1 hunks)
  • server/server_interface.go (1 hunks)
  • server/sse.go (3 hunks)
  • server/stdio.go (2 hunks)
  • server/streamable_http.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • server/sse.go
  • server/streamable_http.go
  • server/stdio.go
  • server/server_interface.go
🔇 Additional comments (3)
examples/custom_server/main.go (3)

17-29: LGTM! Clean wrapper implementation.

The LoggingMCPServer struct properly demonstrates how to use the new server.Interface abstraction to create custom server implementations. The constructor follows standard Go patterns.


66-180: Excellent interface implementation with comprehensive logging.

All interface methods are properly implemented with consistent logging patterns, good error handling, and appropriate delegation to the underlying server. This provides excellent observability for MCP server operations.


182-257: Well-structured server setup and lifecycle management.

The main function demonstrates proper MCP server configuration with structured logging, example tools/resources, and graceful shutdown handling. The implementation correctly uses the new server.Interface abstraction and provides a good example for developers.

Note: The outdated comment mentioned in past reviews appears to have been already addressed.

@paulgrammer paulgrammer marked this pull request as draft June 20, 2025 13:01
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