Skip to content

feat: implement protocol version negotiation #502

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 9 commits into from
Jul 25, 2025

Conversation

ezynda3
Copy link
Contributor

@ezynda3 ezynda3 commented Jul 22, 2025

Summary

  • Implement protocol version negotiation following the TypeScript SDK approach
  • Add client-side validation to ensure protocol compatibility
  • Support Mcp-Protocol-Version header in HTTP transports

Changes

  • Update LATEST_PROTOCOL_VERSION to "2025-06-18"
  • Add UnsupportedProtocolVersionError for incompatible versions
  • Validate server's protocol version in client initialization
  • Add HTTPConnection interface with SetProtocolVersion() method
  • Implement protocol version header support in StreamableHTTP and SSE transports
  • Add comprehensive tests for protocol negotiation scenarios

Motivation

The previous implementation didn't validate protocol versions, which could lead to compatibility issues if client and server use incompatible versions. This PR implements the same robust negotiation strategy as the TypeScript SDK.

Test plan

  • Added new test file client/protocol_negotiation_test.go with comprehensive tests
  • All existing tests updated and passing
  • Tests pass with race detector enabled (go test -race ./...)
  • Manual testing of protocol negotiation with different version scenarios

🤖 Generated with opencode

Summary by CodeRabbit

  • New Features

    • Enhanced protocol version negotiation for clients, including validation of supported versions and improved error reporting for unsupported versions.
    • Protocol version is now automatically set on HTTP-based transports after negotiation.
  • Bug Fixes

    • Consistent use of protocol version and session ID header constants across client and server components.
    • Server now defaults to a prior protocol version when none is specified by the client for improved backward compatibility.
  • Tests

    • Comprehensive tests added for protocol version negotiation, error handling, and HTTP header setting.
    • Minor whitespace and formatting improvements in existing tests.
  • Chores

    • Updated latest supported protocol version and valid protocol versions list.
    • Centralized HTTP header key definitions for easier maintenance.

Implement protocol version negotiation following the TypeScript SDK approach:
- Update LATEST_PROTOCOL_VERSION to 2025-06-18
- Add client-side validation of server protocol version
- Return UnsupportedProtocolVersionError for incompatible versions
- Add Mcp-Protocol-Version header support for HTTP transports
- Implement SetProtocolVersion method on HTTP connections
- Add comprehensive tests for protocol negotiation

This ensures both client and server agree on a mutually supported protocol
version, preventing compatibility issues.

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <[email protected]>
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Walkthrough

This change introduces protocol version negotiation to the MCP client and transport layers. The client now validates the server's protocol version during initialization, stores it, and sets it on HTTP-based transports. New error types and constants are added for protocol version handling. Corresponding updates are made to tests and header handling in both client and server code.

Changes

Files / File Groups Change Summary
client/client.go, mcp/errors.go, mcp/types.go Added protocol version negotiation: client validates, stores, and propagates the negotiated protocol version; introduced UnsupportedProtocolVersionError and helper; updated valid protocol versions and constants.
client/protocol_negotiation_test.go Added comprehensive tests for protocol negotiation, error handling, and HTTP transport header setting.
client/transport/interface.go, client/transport/sse.go, client/transport/streamable_http.go Added HTTPConnection interface; implemented SetProtocolVersion in SSE and StreamableHTTP transports; protocol version now included in outgoing HTTP headers if set.
client/transport/constants.go, server/constants.go Introduced centralized constants for session ID and protocol version HTTP header keys in both client and server packages.
client/stdio_test.go, server/streamable_http_test.go, testdata/mockstdio_server.go Updated tests to use protocol version constants instead of hardcoded strings; adjusted session ID header key usage to new constants.
client/transport/sse_test.go, client/transport/streamable_http_test.go, mcp/tools.go, server/session_test.go Whitespace and formatting cleanups in tests and utility code; no functional changes.
server/streamable_http.go Replaced internal session ID header constant with new centralized constant for all header handling.
server/server.go Added default protocol version fallback for clients omitting protocol version header.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

type: enhancement, area: sdk

Suggested reviewers

  • robert-jackson-glean
  • pottekkat

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 6a868bc and b5b7fea.

📒 Files selected for processing (1)
  • server/server_test.go (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • server/server_test.go
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/protocol-negotiation

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 generate unit tests to generate unit tests for 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)
mcp/errors.go (1)

15-19: Consider using errors.As for more robust type checking.

The current type assertion works, but using errors.As would be more robust for wrapped errors and follows modern Go error handling patterns.

-// IsUnsupportedProtocolVersion checks if an error is an UnsupportedProtocolVersionError
-func IsUnsupportedProtocolVersion(err error) bool {
-	_, ok := err.(UnsupportedProtocolVersionError)
-	return ok
-}
+// IsUnsupportedProtocolVersion checks if an error is an UnsupportedProtocolVersionError
+func IsUnsupportedProtocolVersion(err error) bool {
+	var target UnsupportedProtocolVersionError
+	return errors.As(err, &target)
+}

Don't forget to add "errors" to the imports.

client/protocol_negotiation_test.go (1)

149-182: Consider using t.Errorf for consistency with error handling practices.

The test effectively verifies HTTP transport protocol version setting. However, consider using t.Errorf instead of t.Fatalf on line 174 to align with the project's preference for giving callers flexibility in error handling (as noted in retrieved learnings).

-	if err != nil {
-		t.Fatalf("unexpected error: %v", err)
-	}
+	if err != nil {
+		t.Errorf("unexpected error: %v", err)
+		return
+	}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c38b56 and 557a80c.

📒 Files selected for processing (11)
  • client/client.go (3 hunks)
  • client/protocol_negotiation_test.go (1 hunks)
  • client/stdio_test.go (1 hunks)
  • client/transport/interface.go (1 hunks)
  • client/transport/sse.go (4 hunks)
  • client/transport/streamable_http.go (3 hunks)
  • mcp/errors.go (1 hunks)
  • mcp/types.go (1 hunks)
  • server/streamable_http.go (1 hunks)
  • server/streamable_http_test.go (6 hunks)
  • testdata/mockstdio_server.go (1 hunks)
🧠 Learnings (9)
testdata/mockstdio_server.go (3)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

client/stdio_test.go (2)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

server/streamable_http.go (1)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

mcp/errors.go (3)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

server/streamable_http_test.go (6)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

Learnt from: xinwo
PR: #35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in the mark3labs/mcp-go project should handle both InputSchema and RawInputSchema consistently between MarshalJSON and UnmarshalJSON methods, even though the tools response from MCP server typically doesn't contain rawInputSchema.

Learnt from: xinwo
PR: #35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.

Learnt from: floatingIce91
PR: #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.

client/transport/sse.go (1)

Learnt from: leavez
PR: #114
File: client/transport/sse.go:137-179
Timestamp: 2025-04-06T10:07:06.685Z
Learning: The SSE client implementation in the MCP-Go project uses a 30-second timeout for reading SSE events to match the behavior of the original implementation before the transport layer refactoring.

client/client.go (2)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: leavez
PR: #168
File: client/transport/streamable_http.go:183-186
Timestamp: 2025-04-17T15:58:33.813Z
Learning: In Go's atomic.Value, CompareAndSwap compares values using the == operator (value equality), not pointer identity. For strings, this means comparison by content, not memory address, so casting the loaded interface{} value to a string before comparison is unnecessary when using CompareAndSwap.

mcp/types.go (2)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

client/protocol_negotiation_test.go (2)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

🧬 Code Graph Analysis (3)
testdata/mockstdio_server.go (1)
mcp/types.go (1)
  • LATEST_PROTOCOL_VERSION (100-100)
client/stdio_test.go (1)
mcp/types.go (1)
  • LATEST_PROTOCOL_VERSION (100-100)
client/client.go (3)
mcp/types.go (1)
  • ValidProtocolVersions (103-107)
mcp/errors.go (1)
  • UnsupportedProtocolVersionError (7-9)
client/transport/interface.go (1)
  • HTTPConnection (52-55)
🧰 Additional context used
🧠 Learnings (9)
testdata/mockstdio_server.go (3)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

client/stdio_test.go (2)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

server/streamable_http.go (1)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

mcp/errors.go (3)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

server/streamable_http_test.go (6)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

Learnt from: xinwo
PR: #35
File: mcp/tools.go:0-0
Timestamp: 2025-03-04T07:00:57.111Z
Learning: The Tool struct in the mark3labs/mcp-go project should handle both InputSchema and RawInputSchema consistently between MarshalJSON and UnmarshalJSON methods, even though the tools response from MCP server typically doesn't contain rawInputSchema.

Learnt from: xinwo
PR: #35
File: mcp/tools.go:107-137
Timestamp: 2025-03-04T06:59:43.882Z
Learning: Tool responses from the MCP server shouldn't contain RawInputSchema, which is why the UnmarshalJSON method for the Tool struct is implemented to handle only the structured InputSchema format.

Learnt from: floatingIce91
PR: #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.

client/transport/sse.go (1)

Learnt from: leavez
PR: #114
File: client/transport/sse.go:137-179
Timestamp: 2025-04-06T10:07:06.685Z
Learning: The SSE client implementation in the MCP-Go project uses a 30-second timeout for reading SSE events to match the behavior of the original implementation before the transport layer refactoring.

client/client.go (2)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: leavez
PR: #168
File: client/transport/streamable_http.go:183-186
Timestamp: 2025-04-17T15:58:33.813Z
Learning: In Go's atomic.Value, CompareAndSwap compares values using the == operator (value equality), not pointer identity. For strings, this means comparison by content, not memory address, so casting the loaded interface{} value to a string before comparison is unnecessary when using CompareAndSwap.

mcp/types.go (2)

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

Learnt from: lariel-fernandes
PR: #428
File: www/docs/pages/servers/prompts.mdx:218-234
Timestamp: 2025-06-20T20:39:51.870Z
Learning: In the mcp-go library, the GetPromptParams.Arguments field is of type map[string]string, not map[string]interface{}, so direct string access without type assertions is safe and correct.

client/protocol_negotiation_test.go (2)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

🧬 Code Graph Analysis (3)
testdata/mockstdio_server.go (1)
mcp/types.go (1)
  • LATEST_PROTOCOL_VERSION (100-100)
client/stdio_test.go (1)
mcp/types.go (1)
  • LATEST_PROTOCOL_VERSION (100-100)
client/client.go (3)
mcp/types.go (1)
  • ValidProtocolVersions (103-107)
mcp/errors.go (1)
  • UnsupportedProtocolVersionError (7-9)
client/transport/interface.go (1)
  • HTTPConnection (52-55)
🔇 Additional comments (29)
client/transport/interface.go (1)

50-55: LGTM! Well-designed interface addition.

The HTTPConnection interface follows Go best practices by embedding the existing Interface and adding a single, focused method. The documentation clearly explains its purpose for HTTP transports that need protocol version header support.

mcp/types.go (1)

100-107: Protocol version update looks good.

The update to LATEST_PROTOCOL_VERSION and the reordering of ValidProtocolVersions maintains backward compatibility while promoting the new version. The latest version is correctly placed first in the slice, which is the expected pattern for version preference.

mcp/errors.go (1)

5-13: Well-designed error type.

The UnsupportedProtocolVersionError follows Go error conventions with a descriptive Error() method that includes the problematic version for debugging.

testdata/mockstdio_server.go (1)

55-55: Good change to use the constant instead of hardcoded version.

Replacing the hardcoded protocol version with mcp.LATEST_PROTOCOL_VERSION ensures the mock server stays consistent with the actual protocol version and automatically updates when the constant changes.

server/streamable_http.go (1)

211-212: Good addition of protocol version header constant.

The headerKeyProtocolVersion constant follows the established pattern and provides a centralized definition for the protocol version header name, preventing inconsistencies and typos.

client/stdio_test.go (1)

96-96: LGTM: Protocol version constant usage

Good change to use mcp.LATEST_PROTOCOL_VERSION instead of hardcoded string. This ensures test consistency with the protocol version negotiation implementation.

server/streamable_http_test.go (6)

31-31: LGTM: Consistent protocol version usage

Excellent systematic replacement of hardcoded protocol version with mcp.LATEST_PROTOCOL_VERSION constant. This ensures test consistency with the protocol negotiation implementation.


148-150: LGTM: Protocol version validation consistency

The assertion correctly uses the same mcp.LATEST_PROTOCOL_VERSION constant for validation, ensuring tests remain synchronized with protocol version updates.


341-343: LGTM: Consistent protocol version validation in stateless tests

Proper use of the protocol version constant in stateless mode testing maintains consistency across different test scenarios.


567-567: LGTM: Protocol version constant in custom mux test

Consistent application of the protocol version constant across all test scenarios, including custom mux configuration.


587-589: LGTM: Protocol version validation in HTTP handler test

The assertion maintains consistency by using the constant for both request and response validation.


845-895: LGTM: Code formatting consistency

Good formatting fix converting spaces to tabs, aligning with Go conventions and the rest of the file's indentation style.

client/transport/sse.go (4)

40-40: LGTM: Thread-safe protocol version storage

Good use of atomic.Value for thread-safe storage of the negotiated protocol version string.


328-333: LGTM: Protocol version header implementation

Correct implementation of protocol version header setting with proper nil and empty string checks before adding the header to requests.


444-447: LGTM: HTTPConnection interface implementation

Clean implementation of the SetProtocolVersion method that completes the transport.HTTPConnection interface for SSE transport.


471-476: LGTM: Consistent header handling in notifications

Excellent consistency in applying the protocol version header to both requests and notifications using the same logic and header constant.

client/transport/streamable_http.go (4)

106-106: LGTM: Thread-safe protocol version storage

Proper use of atomic.Value for thread-safe storage of the protocol version, consistent with the SSE transport implementation.


211-214: LGTM: HTTPConnection interface implementation

Clean and simple implementation of the SetProtocolVersion method to satisfy the transport.HTTPConnection interface.


218-218: LGTM: Consistent header constant

Good addition of the protocol version header constant, maintaining consistency with other HTTP transports using the same header name.


347-352: LGTM: Protocol version header in shared HTTP method

Excellent placement of the protocol version header logic in the shared sendHTTP method, ensuring both requests and notifications automatically include the header when a protocol version is set.

client/client.go (5)

8-8: LGTM: Import for protocol version validation

Appropriate addition of the slices package import for the Contains function used in protocol version validation.


26-26: LGTM: Protocol version storage

Good addition of the protocolVersion field to store the negotiated version string on the client.


181-184: LGTM: Protocol version validation logic

Excellent validation implementation using slices.Contains against mcp.ValidProtocolVersions and returning the appropriate UnsupportedProtocolVersionError for unsupported versions.


186-188: LGTM: Storage of negotiated values

Proper storage of both server capabilities and the negotiated protocol version after successful validation.


190-193: LGTM: Transport integration for HTTP connections

Excellent design using type assertion to check if the transport implements HTTPConnection interface before setting the protocol version. This allows the negotiated version to be propagated to HTTP-based transports while remaining compatible with other transport types.

client/protocol_negotiation_test.go (4)

1-12: LGTM! Clean package structure and imports.

The package declaration and imports are well-organized and include all necessary dependencies for the protocol negotiation tests.


14-55: LGTM! Well-structured mock transport implementation.

The mock transport properly implements the transport.Interface with appropriate state tracking and response mapping. The error handling for unknown methods is good practice for test isolation.


57-137: Excellent comprehensive test coverage for protocol negotiation.

The table-driven test approach covers all critical scenarios including supported versions, unsupported past versions, and future versions. The test properly verifies both error conditions and successful protocol version storage in the client. Good use of t.Errorf over t.Fatalf for better test flexibility.


139-147: LGTM! Clean extension for HTTP transport testing.

Good use of embedding to extend the base mock transport with HTTP-specific functionality. The simple SetProtocolVersion implementation effectively tracks calls for test verification.

ezynda3 and others added 2 commits July 23, 2025 10:15
- Move HTTP header constants to common location to avoid duplication
- Add errors.Is interface to UnsupportedProtocolVersionError for better Go error handling
- Add comprehensive edge case tests for empty and malformed protocol versions
- Ensure consistent header constant usage across client and server packages

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <[email protected]>
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)
client/protocol_negotiation_test.go (1)

155-157: Consider avoiding direct access to private fields in tests.

The test is directly accessing client.protocolVersion which appears to be a private field. This creates tight coupling between the test and implementation details. Consider adding a getter method or using a different approach to verify the stored protocol version.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2be3442 and 79460df.

📒 Files selected for processing (9)
  • client/protocol_negotiation_test.go (1 hunks)
  • client/transport/constants.go (1 hunks)
  • client/transport/sse.go (4 hunks)
  • client/transport/streamable_http.go (5 hunks)
  • mcp/errors.go (1 hunks)
  • server/constants.go (1 hunks)
  • server/session_test.go (1 hunks)
  • server/streamable_http.go (4 hunks)
  • server/streamable_http_test.go (14 hunks)
🧠 Learnings (2)
📓 Common learnings
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
client/protocol_negotiation_test.go (2)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

🧬 Code Graph Analysis (1)
client/protocol_negotiation_test.go (4)
mcp/types.go (9)
  • JSONRPCRequest (312-317)
  • JSONRPCResponse (326-330)
  • Result (233-237)
  • LATEST_PROTOCOL_VERSION (100-100)
  • InitializeRequest (401-405)
  • Params (164-164)
  • InitializeParams (407-413)
  • Implementation (483-486)
  • ClientCapabilities (442-452)
client/transport/interface.go (2)
  • JSONRPCRequest (57-62)
  • JSONRPCResponse (64-73)
client/client.go (1)
  • NewClient (62-72)
mcp/errors.go (2)
  • IsUnsupportedProtocolVersion (22-25)
  • UnsupportedProtocolVersionError (7-9)
✅ Files skipped from review due to trivial changes (5)
  • client/transport/constants.go
  • server/streamable_http.go
  • server/session_test.go
  • server/constants.go
  • server/streamable_http_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • client/transport/sse.go
  • mcp/errors.go
  • client/transport/streamable_http.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ezynda3
PR: mark3labs/mcp-go#461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.
client/protocol_negotiation_test.go (2)

Learnt from: octo
PR: #149
File: mcptest/mcptest.go:0-0
Timestamp: 2025-04-21T21:26:32.945Z
Learning: In the mcptest package, prefer returning errors from helper functions rather than calling t.Fatalf() directly, giving callers flexibility in how to handle errors.

Learnt from: ezynda3
PR: #461
File: server/sampling.go:22-26
Timestamp: 2025-06-30T07:13:17.052Z
Learning: In the mark3labs/mcp-go project, the MCPServer.capabilities field is a struct value (serverCapabilities), not a pointer, so it cannot be nil and doesn't require nil checking. Only pointer fields within the capabilities struct should be checked for nil.

🧬 Code Graph Analysis (1)
client/protocol_negotiation_test.go (4)
mcp/types.go (9)
  • JSONRPCRequest (312-317)
  • JSONRPCResponse (326-330)
  • Result (233-237)
  • LATEST_PROTOCOL_VERSION (100-100)
  • InitializeRequest (401-405)
  • Params (164-164)
  • InitializeParams (407-413)
  • Implementation (483-486)
  • ClientCapabilities (442-452)
client/transport/interface.go (2)
  • JSONRPCRequest (57-62)
  • JSONRPCResponse (64-73)
client/client.go (1)
  • NewClient (62-72)
mcp/errors.go (2)
  • IsUnsupportedProtocolVersion (22-25)
  • UnsupportedProtocolVersionError (7-9)
🔇 Additional comments (4)
client/protocol_negotiation_test.go (4)

14-55: LGTM! Well-structured mock transport implementation.

The mock transport provides a clean and flexible way to test protocol negotiation scenarios with its method-based response mapping.


163-171: LGTM! Clean extension of mock transport for HTTP testing.

The embedded struct pattern is used correctly to add HTTP-specific functionality.


173-206: LGTM! Test correctly verifies HTTP transport protocol version setting.

The test properly validates that the protocol version is propagated to HTTP transports after successful initialization.


208-216: Verify type-only comparison in UnsupportedProtocolVersionError.Is

The Is method in mcp/errors.go (16–19) currently does:

  • It asserts only that the target error is of type UnsupportedProtocolVersionError, ignoring the Version field.

In client/protocol_negotiation_test.go (208–216), the test expects

err1.Is(err2) // true even if err1.Version != err2.Version

to pass.

Please confirm whether we intend to treat all instances of UnsupportedProtocolVersionError as equal regardless of their Version values.

  • If yes, consider adding a comment or updating documentation to clarify that Is only checks the error type.
  • If not, update the implementation of Is to include a comparison of the Version field so that errors with different versions are not considered the same.

@@ -194,7 +195,7 @@ func (c *StreamableHTTP) Close() error {
c.logger.Errorf("failed to create close request: %v", err)
return
}
req.Header.Set(headerKeySessionID, sessionId)
req.Header.Set(HeaderKeySessionID, sessionId)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔, when client sends a DELETE request to server to terminate a session, should we also include "Mcp-Protocol-Version" header if provided?
Ref 1: sepc

If using HTTP, the client MUST include the MCP-Protocol-Version: HTTP header on all subsequent requests to the MCP server

Ref 2: typescrpt-sdk

  async terminateSession(): Promise<void> {
    if (!this._sessionId) {
      return; // No session to terminate
    }

    try {
      const headers = await this._commonHeaders();

      const init = {
        ...this._requestInit,
        method: "DELETE",
        headers,
     //....

  private async _commonHeaders(): Promise<Headers> {
     //...
    if (this._sessionId) {
      headers["mcp-session-id"] = this._sessionId;
    }
    if (this._protocolVersion) {
      headers["mcp-protocol-version"] = this._protocolVersion;
    }
    //...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: 278238b

@@ -97,12 +97,13 @@ func (t *URITemplate) UnmarshalJSON(data []byte) error {
type JSONRPCMessage any

// LATEST_PROTOCOL_VERSION is the most recent version of the MCP protocol.
const LATEST_PROTOCOL_VERSION = "2025-03-26"
const LATEST_PROTOCOL_VERSION = "2025-06-18"

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Upgrading LATEST_PROTOCOL_VERSION from 2025-03-26 to 2025-06-18 is a breaking change for (s *MCPServer) protocolVersion in server.go.

It would be safer to maintain backwards compatibility
image

Copy link
Collaborator

@dugenkui03 dugenkui03 Jul 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

func (s *MCPServer) protocolVersion(clientProtocolVersion string) string {
	// For backwards compatibility, if the server does not receive an MCP-Protocol-Version header,
	// and has no other way to identify the version - for example, by relying on the protocol version negotiated 
	// during initialization - the server SHOULD assume protocol version 2025-03-26
	// https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header
	if len(clientProtocolVersion) == 0 {
		clientProtocolVersion = "2025-03-26"
	}

	if slices.Contains(mcp.ValidProtocolVersions, clientProtocolVersion) {
		return clientProtocolVersion
	}

	return mcp.LATEST_PROTOCOL_VERSION
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: 6a868bc

…rmination

As per MCP specification, the MCP-Protocol-Version header must be included
on all subsequent requests to the MCP server, including DELETE requests
for terminating sessions.

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <[email protected]>
ezynda3

This comment was marked as outdated.

ezynda3 and others added 2 commits July 24, 2025 16:02
When the server does not receive an MCP-Protocol-Version header,
it should assume protocol version 2025-03-26 for backward compatibility
as per the MCP specification.

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <[email protected]>
Tests now expect protocol version 2025-03-26 when no protocol version
is provided during initialization, as per MCP specification for
backward compatibility.

🤖 Generated with [opencode](https://opencode.ai)

Co-Authored-By: opencode <[email protected]>
@ezynda3 ezynda3 requested review from cryo-zd and dugenkui03 July 24, 2025 13:08
@ezynda3 ezynda3 merged commit 3964d51 into main Jul 25, 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.

3 participants