Skip to content

fix(server): Implement MCP version negotiation. #341

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 28, 2025

Conversation

octo
Copy link
Contributor

@octo octo commented May 27, 2025

Description

Fix protocol version negotiation to comply with MCP specification

Problem

The current server implementation violates the MCP protocol specification for version negotiation. It always responds with LATEST_PROTOCOL_VERSION regardless of client capabilities, causing some clients (e.g. Claude Desktop) to disconnect.

Root Cause

According to the MCP spec:

"If the server supports the requested protocol version, it MUST respond with the same version. Otherwise, the server MUST respond with another protocol version it supports."

Our server was not implementing this negotiation correctly, leading to Claude Desktop to terminate the MCP server immediately.

Solution

Implement protocol version negotiation per MCP specification:

  • If server supports client's requested version → respond with same version
  • If server doesn't support client's version → respond with server's preferred version

This fixes compatibility issues with clients like Claude Desktop that expect proper version negotiation.

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: Version Negotiation
  • Implementation follows the specification exactly

Summary by CodeRabbit

  • New Features
    • Improved protocol version negotiation during initialization, allowing the server to recognize and respond to supported client protocol versions.
  • Tests
    • Added tests to verify correct server behavior when handling various client protocol version requests.

According to [the MCP spec](https://modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle#version-negotiation):

> If the server supports the requested protocol version, it MUST respond with
> the same version. Otherwise, the server MUST respond with another protocol
> version it supports.

This adds `mcp.ValidProtocolVersions`, a slice with all currently specified MCP
versions.

In the `server` package we check if the client provided a known MCP version
and, if so, return that version. Otherwise `LATEST_PROTOCOL_VERSION` is
returned as previously.
Copy link
Contributor

coderabbitai bot commented May 27, 2025

Walkthrough

A new exported variable listing valid MCP protocol versions was added. The server now negotiates protocol versions by checking if the client’s version is valid and responds accordingly. The initialization handler uses this negotiation logic. A test was introduced to verify protocol version negotiation behavior for various client requests.

Changes

File(s) Change Summary
mcp/types.go Added exported variable ValidProtocolVersions containing supported protocol versions.
server/server.go Added protocolVersion method to negotiate protocol version; updated initialization logic.
server/server_test.go Added test TestMCPServer_ProtocolNegotiation for protocol version negotiation scenarios.

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

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

1949-2024: Excellent comprehensive test coverage for protocol version negotiation!

The test function thoroughly validates the MCP protocol version negotiation behavior according to the specification requirements. The test cases cover all critical scenarios:

  1. ✅ Supported client version → server responds with client's version
  2. ✅ Latest version request → server responds with latest
  3. ✅ Unsupported future version → server responds with latest supported
  4. ✅ Unsupported old version → server responds with latest supported

The test structure is clean and follows Go testing best practices.

Consider adding a test case for edge scenarios to make the test even more robust:

+		{
+			name:            "Client requests empty version - should respond with server's latest",
+			clientVersion:   "",
+			expectedVersion: mcp.LATEST_PROTOCOL_VERSION,
+		},

This would ensure the server handles malformed or missing protocol version requests gracefully.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 243a292 and d3db1f2.

📒 Files selected for processing (3)
  • mcp/types.go (1 hunks)
  • server/server.go (3 hunks)
  • server/server_test.go (1 hunks)
🔇 Additional comments (4)
mcp/types.go (1)

101-105:

✅ Verification successful

LGTM! Clean implementation of centralized protocol version management.

The ValidProtocolVersions variable provides a clean, centralized way to manage supported MCP protocol versions. The inclusion of both the older "2024-11-05" version and the latest version demonstrates proper backward compatibility support.

I'd like to verify that the server implementation correctly uses this variable for version negotiation. Could you run the following script to confirm the usage:


🏁 Script executed:

#!/bin/bash
# Description: Verify that ValidProtocolVersions is used correctly in the server implementation
# Expected: Find references to ValidProtocolVersions in server negotiation logic

echo "Searching for ValidProtocolVersions usage in server code:"
rg -A 5 -B 5 "ValidProtocolVersions"

echo -e "\nSearching for protocol negotiation logic:"
rg -A 10 "protocolVersion|ProtocolVersion" --type go

Length of output: 29870


Confirmed ValidProtocolVersions is used correctly in negotiation logic

The server’s protocolVersion method in server/server.go references mcp.ValidProtocolVersions via slices.Contains, returning the client’s version if it’s in the list, otherwise falling back to LATEST_PROTOCOL_VERSION. Initialize handlers and existing tests cover both the legacy "2024-11-05" version and the latest "2025-03-26":

  • server/server.go
    func (s *MCPServer) protocolVersion(clientVersion string) string {
        if slices.Contains(mcp.ValidProtocolVersions, clientVersion) {
            return clientVersion
        }
        return mcp.LATEST_PROTOCOL_VERSION
    }
  • Handlers assign
    ProtocolVersion: s.protocolVersion(request.Params.ProtocolVersion),
  • Tests in server/stdio_test.go, server/sse_test.go, server/streamable_http_test.go, etc., assert correct negotiation for both supported and unsupported client versions.

Everything looks solid—no further action needed.

server/server.go (3)

9-9: LGTM: Import addition supports protocol negotiation.

The addition of the slices import is necessary for the slices.Contains function used in the new protocol version negotiation logic.


554-554: LGTM: Proper protocol version negotiation implementation.

The change from hardcoded mcp.LATEST_PROTOCOL_VERSION to s.protocolVersion(request.Params.ProtocolVersion) correctly implements the MCP specification requirement for protocol version negotiation. The server now properly considers the client's requested version instead of always responding with the latest version.


574-580: LGTM: Protocol negotiation logic correctly implements MCP specification.

The protocolVersion method properly implements the MCP specification requirements:

  • Returns the client's requested version if it exists in mcp.ValidProtocolVersions
  • Falls back to mcp.LATEST_PROTOCOL_VERSION if the client's version is not supported
  • Uses slices.Contains for efficient membership checking
  • Is thread-safe since it only reads immutable data

This implementation should resolve the compatibility issues with clients like Claude Desktop that expect proper version negotiation.

@ezynda3 ezynda3 merged commit c7c0e13 into mark3labs:main May 28, 2025
4 checks passed
@pottekkat
Copy link
Collaborator

I missed reviewing this yesterday. Now it's already merged. Regardless, this looks good to me.

But are there any breaking changes to the specification between the two versions that has caused breaking changes to the SDK? If that's the case, then we need to enable/disable things based on the client supported MCP spec version right? I'm not sure if it is the case but thought of mentioning it here.

Maybe we can look at how other SDKs handle this.

cc: @octo @robert-jackson-glean

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.

4 participants