Repository navigation
fix(mcp): negotiate protocol versions across client transports #1246
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
base: main
Are you sure you want to change the base?
Changes from all commits
32c2674
37fef58
93710ea
c251748
e8151f3
59e2d37
3221cd0
720a2d3
9e6b85c
acae494
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,201 @@ | ||
| package mcp | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
| "regexp" | ||
| "strings" | ||
| ) | ||
|
|
||
| // These revisions use the initialize handshake. Newer, handshake-free | ||
| // transports require a separate implementation, not another candidate here. | ||
| var clientProtocolVersions = []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"} | ||
|
|
||
| const legacyProtocolVersion = "2024-11-05" | ||
|
|
||
| var protocolVersionPattern = regexp.MustCompile(`\b[0-9]{4}-[0-9]{2}-[0-9]{2}\b`) | ||
| var supportedVersionLabel = regexp.MustCompile(`(?i)\bsupported(?:[\s_-]+(?:protocol[\s_-]+)?versions?)?\s*(?::|=|\bare\b)\s*`) | ||
| var protocolVersionPrefix = regexp.MustCompile(`^[0-9]{4}-[0-9]{2}-[0-9]{2}\b`) | ||
| var protocolVersionConjunction = regexp.MustCompile(`(?i)^(?:and|or)\s+`) | ||
|
|
||
| func negotiateProtocol(ctx context.Context, request func(context.Context, string, any, any) error) (string, error) { | ||
| version := clientProtocolVersions[0] | ||
| tried := map[string]bool{} | ||
| var firstError error | ||
| for !tried[version] { | ||
| if err := ctx.Err(); err != nil { | ||
| return "", err | ||
| } | ||
| tried[version] = true | ||
| var result struct { | ||
| ProtocolVersion string `json:"protocolVersion"` | ||
| } | ||
| err := request(ctx, "initialize", map[string]any{ | ||
| "protocolVersion": version, | ||
| "capabilities": map[string]any{}, | ||
| "clientInfo": map[string]any{"name": "zero", "version": "dev"}, | ||
| }, &result) | ||
| if err == nil { | ||
| // Older servers may omit this field. Keep their existing connection | ||
| // working by treating the successful reply as accepting our proposal. | ||
| if result.ProtocolVersion == "" { | ||
| return version, nil | ||
| } | ||
| for _, supported := range clientProtocolVersions { | ||
| if result.ProtocolVersion == supported { | ||
| return supported, nil | ||
| } | ||
| } | ||
| if firstError != nil { | ||
| return "", firstError | ||
| } | ||
| return "", fmt.Errorf("MCP server selected unsupported protocol version %q (client supports %s)", result.ProtocolVersion, strings.Join(clientProtocolVersions, ", ")) | ||
| } | ||
| if err := ctx.Err(); err != nil { | ||
| return "", err | ||
| } | ||
| if firstError == nil { | ||
| firstError = err | ||
| } | ||
| var rejected *rpcError | ||
| var httpRejected *initializeHTTPRejection | ||
| if !errors.As(err, &rejected) && !errors.As(err, &httpRejected) { | ||
| return "", firstError | ||
| } | ||
| if httpRejected != nil && httpRejected.unrelated { | ||
| return "", firstError | ||
| } | ||
| next := "" | ||
| if rejected != nil { | ||
| advertised, versionError := advertisedProtocolVersions(rejected) | ||
| if unrelatedInitializeRejection(rejected) { | ||
| return "", firstError | ||
| } | ||
| if versionError { | ||
| for _, candidate := range clientProtocolVersions { | ||
| if advertised[candidate] && !tried[candidate] { | ||
| next = candidate | ||
| break | ||
| } | ||
| } | ||
| } | ||
| } | ||
| if next == "" && httpRejected != nil { | ||
| for _, candidate := range httpRejected.versions { | ||
| if !tried[candidate] { | ||
| next = candidate | ||
| break | ||
| } | ||
| } | ||
| } | ||
| // A legacy server may reject a newer proposal without advertising a | ||
| // version at all. Try the version main used once before giving up. | ||
| if next == "" && !tried[legacyProtocolVersion] { | ||
| next = legacyProtocolVersion | ||
|
Comment on lines
+95
to
+96
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do not retry unrelated RPC failures. If initialization returns Exclude known unrelated parameter and authentication failures. Keep fallback for ambiguous legacy version rejections.
|
||
| } | ||
| if next == "" { | ||
| return "", firstError | ||
| } | ||
| version = next | ||
| } | ||
| return "", fmt.Errorf("MCP protocol negotiation repeated version %q", version) | ||
| } | ||
|
|
||
| // A generic invalid-params rejection may be an older server refusing our | ||
| // version. Explicit missing-field or authentication diagnostics are different: | ||
| // changing the version cannot repair those failures. | ||
| func unrelatedInitializeRejection(rejected *rpcError) bool { | ||
| message := strings.ToLower(rejected.Message) | ||
| for _, marker := range []string{"unauthorized", "unauthenticated", "authentication", "authorization", "forbidden", "invalid credential", "invalid api key"} { | ||
| if strings.Contains(message, marker) { | ||
| return true | ||
| } | ||
| } | ||
| var detail struct { | ||
| Missing string `json:"missing"` | ||
| } | ||
| if json.Unmarshal(rejected.Data, &detail) == nil { | ||
| missing := strings.ReplaceAll(strings.ToLower(detail.Missing), "_", "") | ||
| return missing != "" && missing != "protocolversion" && missing != "version" | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| // Error data is JSON, so escaped digits and separators must be decoded before | ||
| // inspection. Explicit supported lists take precedence over incidental dates | ||
| // in messages, requested-version fields, and unsupported lists. | ||
| func advertisedProtocolVersions(rejected *rpcError) (map[string]bool, bool) { | ||
| versions := map[string]bool{} | ||
| texts := []string{rejected.Message} | ||
| explicit := false | ||
| var addList func(any) | ||
| addList = func(value any) { | ||
| switch typed := value.(type) { | ||
| case string: | ||
| for _, version := range protocolVersionPattern.FindAllString(typed, -1) { | ||
| versions[version] = true | ||
| } | ||
| case []any: | ||
| for _, item := range typed { | ||
| addList(item) | ||
| } | ||
| } | ||
| } | ||
| var inspect func(any) | ||
| inspect = func(value any) { | ||
| switch typed := value.(type) { | ||
| case string: | ||
| texts = append(texts, typed) | ||
| case []any: | ||
| for _, item := range typed { | ||
| inspect(item) | ||
| } | ||
| case map[string]any: | ||
| for key, item := range typed { | ||
| normalized := strings.NewReplacer("_", "", "-", "", " ", "").Replace(strings.ToLower(key)) | ||
| switch normalized { | ||
| case "supported", "supportedversions", "supportedprotocolversions": | ||
| explicit = true | ||
| addList(item) | ||
| case "unsupportedversions", "unsupportedprotocolversions": | ||
| // These are exclusions, never a source of retry candidates. | ||
| default: | ||
| inspect(item) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| var data any | ||
| if len(rejected.Data) > 0 && json.Unmarshal(rejected.Data, &data) == nil { | ||
| inspect(data) | ||
| } | ||
| if explicit { | ||
| return versions, true | ||
| } | ||
| lower := strings.ToLower(strings.Join(texts, " ")) | ||
| if !strings.Contains(lower, "protocol") || !strings.Contains(lower, "version") || | ||
| (!strings.Contains(lower, "support") && !strings.Contains(lower, "mismatch")) { | ||
| return versions, false | ||
| } | ||
| for _, text := range texts { | ||
| for _, label := range supportedVersionLabel.FindAllStringIndex(text, -1) { | ||
| if strings.HasSuffix(strings.ToLower(strings.TrimSpace(text[:label[0]])), "not") { | ||
| continue | ||
| } | ||
| list := text[label[1]:] | ||
| for { | ||
| list = strings.TrimLeft(list, " \t\r\n,;|/[]()\"'`") | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| list = protocolVersionConjunction.ReplaceAllString(list, "") | ||
| version := protocolVersionPrefix.FindString(list) | ||
| if version == "" { | ||
| break | ||
| } | ||
| versions[version] = true | ||
| list = list[len(version):] | ||
| } | ||
| } | ||
| } | ||
| return versions, true | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.