diff --git a/internal/mcp/aimlapi.go b/internal/mcp/aimlapi.go index 8dfbc6f6f..60d5da4aa 100644 --- a/internal/mcp/aimlapi.go +++ b/internal/mcp/aimlapi.go @@ -172,6 +172,7 @@ func scrubAIMLAPIKeys(message rpcMessage, keys ...string) rpcMessage { if message.Error != nil { scrubbed := *message.Error scrubbed.Message = redaction.RedactSecretValues(scrubbed.Message, sent...) + scrubbed.Data = scrubAIMLAPIKeysFromJSON(scrubbed.Data, sent) message.Error = &scrubbed } message.Method = redaction.RedactSecretValues(message.Method, sent...) @@ -237,9 +238,8 @@ func scrubAIMLAPIKeysFromValue(value any, keys []string) (any, bool) { // scrubAIMLAPIKeyError returns err with the injected keys removed from its text. // An error the keys do not appear in keeps its chain. One they do appear in is // replaced by its scrubbed text, because its chain still holds the key (a -// *url.Error keeps the URL the server chose); the replacement unwraps only to -// the context sentinel the original matched, so a cancellation still reads as -// one. +// *url.Error keeps the URL the server chose). Only a context sentinel or a +// sanitized initialize-rejection classification survives, never that chain. func scrubAIMLAPIKeyError(err error, keys ...string) error { if err == nil || len(keys) == 0 { return err @@ -256,6 +256,12 @@ func scrubAIMLAPIKeyError(err error, keys ...string) error { break } } + if replacement.cause == nil { + var rejected *initializeHTTPRejection + if errors.As(err, &rejected) { + replacement.cause = &initializeHTTPRejection{cause: errors.New(scrubbed), versions: append([]string(nil), rejected.versions...), unrelated: rejected.unrelated} + } + } return replacement } diff --git a/internal/mcp/aimlapi_scrub_test.go b/internal/mcp/aimlapi_scrub_test.go index b36705c87..01f1598a9 100644 --- a/internal/mcp/aimlapi_scrub_test.go +++ b/internal/mcp/aimlapi_scrub_test.go @@ -20,6 +20,21 @@ import ( // it; a shape pattern would leave it alone. const scrubTestKey = "aiml0123456789abcdef0123456789abcd" +func TestAIMLAPIErrorRedactionPreservesInitializeRejection(t *testing.T) { + original := &initializeHTTPRejection{cause: fmt.Errorf("HTTP 422: server echoed %s", scrubTestKey), versions: []string{"2025-06-18"}} + scrubbed := scrubAIMLAPIKeyError(original, scrubTestKey) + var rejected *initializeHTTPRejection + if !errors.As(scrubbed, &rejected) { + t.Fatalf("sanitized initialize rejection lost its retry classification: %v", scrubbed) + } + if len(rejected.versions) != 1 || rejected.versions[0] != "2025-06-18" { + t.Fatalf("sanitized initialize rejection lost its safe version hints: %v", rejected.versions) + } + for cause := scrubbed; cause != nil; cause = errors.Unwrap(cause) { + assertNoPartOf(t, cause.Error(), scrubTestKey) + } +} + // aimlapiEcho stands in for mcp.aimlapi.com over streamable HTTP. It answers // each JSON-RPC request with reply(method, id), as a JSON body or as one SSE // event, and records the Authorization header every request carried. @@ -479,12 +494,15 @@ func TestAIMLAPIMCPScrubsEveryKeySentAcrossRedirectHops(t *testing.T) { location string // hopKey is the key the redirect hop must carry, "" for none. hopKey string - second func(*http.Request, json.RawMessage) (*http.Response, error) + // A JSON-RPC initialize rejection gets one final legacy proposal. + wantHops int + second func(*http.Request, json.RawMessage) (*http.Response, error) }{ { name: "error echoes the first hop's key", location: "https://mcp.aimlapi.com/mcp/", hopKey: second, + wantHops: 3, second: func(request *http.Request, id json.RawMessage) (*http.Response, error) { return fakeHTTPResponse(request, http.StatusOK, rpcReply(id, "error", map[string]any{"code": -32001, "message": "stale " + first})), nil }, @@ -492,6 +510,7 @@ func TestAIMLAPIMCPScrubsEveryKeySentAcrossRedirectHops(t *testing.T) { { name: "status body after a hop that dropped the key", location: "https://user@mcp.aimlapi.com/mcp", + wantHops: 3, second: func(request *http.Request, _ json.RawMessage) (*http.Response, error) { return fakeHTTPResponse(request, http.StatusPaymentRequired, `{"error":"invalid credential `+first+`"}`), nil }, @@ -500,6 +519,7 @@ func TestAIMLAPIMCPScrubsEveryKeySentAcrossRedirectHops(t *testing.T) { name: "transport error quoting the redirect target", location: "https://mcp.aimlapi.com/mcp?session=" + first, hopKey: second, + wantHops: 2, second: func(*http.Request, json.RawMessage) (*http.Response, error) { return nil, errors.New("connection reset by peer") }, @@ -515,16 +535,21 @@ func TestAIMLAPIMCPScrubsEveryKeySentAcrossRedirectHops(t *testing.T) { echo.mu.Lock() auth := append([]string(nil), echo.auth...) echo.mu.Unlock() - if len(auth) != 2 || auth[0] != "Bearer "+first { + if len(auth) != tc.wantHops || auth[0] != "Bearer "+first { t.Fatalf("Authorization per hop = %q, want the first key on the first request and a redirect hop", auth) } - if tc.hopKey != "" && auth[1] != "Bearer "+tc.hopKey { - t.Fatalf("redirect hop Authorization = %q, want the key resolved again for it", auth[1]) + for _, authorization := range auth[1:] { + if tc.hopKey != "" && authorization != "Bearer "+tc.hopKey { + t.Fatalf("redirect/retry Authorization = %q, want the currently resolved key", authorization) + } } // With no key, net/http fills Basic auth from the hop's own userinfo. if tc.hopKey == "" && (strings.Contains(auth[1], first) || strings.Contains(auth[1], second)) { t.Fatalf("redirect hop Authorization = %q, want no automatic key", auth[1]) } + if tc.hopKey == "" && auth[2] != "Bearer "+second { + t.Fatalf("legacy retry Authorization = %q, want the current key on the original endpoint", auth[2]) + } if err == nil { t.Fatal("initialize succeeded against a failing server") } diff --git a/internal/mcp/aimlapi_test.go b/internal/mcp/aimlapi_test.go index 7d0689250..165ca1484 100644 --- a/internal/mcp/aimlapi_test.go +++ b/internal/mcp/aimlapi_test.go @@ -195,7 +195,7 @@ func TestAIMLAPIMCPHeadersOnlyForExactHost(t *testing.T) { if err := client.initialize(context.Background()); err != nil { t.Fatalf("%s: initialize: %v", rawURL, err) } - for _, header := range recorder.recorded() { + for index, header := range recorder.recorded() { if strings.Contains(rawURL, "user@") && strings.HasPrefix(header.Get("Authorization"), "Basic ") { // net/http turns URL userinfo into Basic auth on its own. header.Del("Authorization") @@ -206,6 +206,9 @@ func TestAIMLAPIMCPHeadersOnlyForExactHost(t *testing.T) { "Content-Type": {"application/json"}, "Accept": {"application/json, text/event-stream"}, } + if index > 0 { + want.Set("MCP-Protocol-Version", "2024-11-05") + } if fmt.Sprint(header) != fmt.Sprint(want) { t.Fatalf("%s: headers = %v, want %v", rawURL, header, want) } diff --git a/internal/mcp/client.go b/internal/mcp/client.go index 28b32ff18..d439874a6 100644 --- a/internal/mcp/client.go +++ b/internal/mcp/client.go @@ -238,17 +238,7 @@ func (client *Client) initialize(ctx context.Context) error { initCtx, cancel := context.WithTimeout(ctx, initializeTimeout) defer cancel() - var result struct { - ProtocolVersion string `json:"protocolVersion"` - } - if err := client.request(initCtx, "initialize", map[string]any{ - "protocolVersion": "2024-11-05", - "capabilities": map[string]any{}, - "clientInfo": map[string]any{ - "name": "zero", - "version": "dev", - }, - }, &result); err != nil { + if _, err := negotiateProtocol(initCtx, client.request); err != nil { return err } return client.notify("notifications/initialized", map[string]any{}) @@ -380,7 +370,7 @@ func (client *Client) request(ctx context.Context, method string, params any, ta } message := result.message if message.Error != nil { - return fmt.Errorf("MCP %s failed: %s", method, message.Error.Message) + return fmt.Errorf("MCP %s failed: %w", method, message.Error) } if target != nil && len(message.Result) > 0 { if err := json.Unmarshal(message.Result, target); err != nil { diff --git a/internal/mcp/negotiate.go b/internal/mcp/negotiate.go new file mode 100644 index 000000000..79b3a529d --- /dev/null +++ b/internal/mcp/negotiate.go @@ -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 + } + 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,;|/[]()\"'`") + list = protocolVersionConjunction.ReplaceAllString(list, "") + version := protocolVersionPrefix.FindString(list) + if version == "" { + break + } + versions[version] = true + list = list[len(version):] + } + } + } + return versions, true +} diff --git a/internal/mcp/negotiate_test.go b/internal/mcp/negotiate_test.go new file mode 100644 index 000000000..91d83f3a1 --- /dev/null +++ b/internal/mcp/negotiate_test.go @@ -0,0 +1,246 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "reflect" + "strings" + "testing" +) + +func TestNegotiateProtocol(t *testing.T) { + for _, tc := range []struct { + name string + selected string + rejection error + wantCalls []string + wantError string + }{ + {name: "latest", selected: "2025-11-25", wantCalls: []string{"2025-11-25"}}, + {name: "supported counteroffer", selected: "2024-11-05", wantCalls: []string{"2025-11-25"}}, + {name: "unsupported counteroffer", selected: "2026-07-28", wantCalls: []string{"2025-11-25"}, wantError: "unsupported protocol version"}, + {name: "missing counteroffer", wantCalls: []string{"2025-11-25"}}, + { + name: "newest shared version", selected: "2025-06-18", + rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`"Unsupported protocol version '2025-11-25'. Supported: 2026-07-28, 2024-11-05, 2025-06-18, 2025-03-26"`)}, + wantCalls: []string{"2025-11-25", "2025-06-18"}, + }, + { + name: "structured supported list", selected: "2025-03-26", + rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`{"supportedVersions":["2025-03-26","2024-11-05"]}`)}, + wantCalls: []string{"2025-11-25", "2025-03-26"}, + }, + { + name: "spec supported list", selected: "2025-03-26", + rejection: &rpcError{Code: -32602, Message: "Unsupported protocol version", Data: json.RawMessage(`{"supported":["2024-11-05","2025-03-26"],"requested":"2025-11-25"}`)}, + wantCalls: []string{"2025-11-25", "2025-03-26"}, + }, + { + name: "escaped supported list", selected: "2025-06-18", + rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`{"supportedVersions":["2025\u002d06\u002d18"]}`)}, + wantCalls: []string{"2025-11-25", "2025-06-18"}, + }, + { + name: "escaped plaintext rejection", selected: "2025-06-18", + rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`"Unsupported protocol version. Supported: \u0032025-06-18"`)}, + wantCalls: []string{"2025-11-25", "2025-06-18"}, + }, + { + name: "ignore unsupported list", selected: "2024-11-05", + rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`{"supportedVersions":["2024-11-05"],"unsupportedVersions":["2025-06-18"]}`)}, + wantCalls: []string{"2025-11-25", "2024-11-05"}, + }, + { + name: "nested escaped supported list", selected: "2025-03-26", + rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`{"details":{"supportedVersions":["2025-03-\u00326"]},"unsupportedVersions":["2025-06-18"]}`)}, + wantCalls: []string{"2025-11-25", "2025-03-26"}, + }, + { + name: "empty supported list", rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`{"supportedVersions":[],"unsupportedVersions":["2025-06-18"]}`)}, + wantCalls: []string{"2025-11-25", "2024-11-05"}, wantError: "Invalid params", + }, + { + name: "plaintext supported and unsupported lists", selected: "2024-11-05", + rejection: &rpcError{Code: -32602, Message: "Unsupported protocol version. Supported: 2024-11-05. Unsupported: 2025-06-18"}, + wantCalls: []string{"2025-11-25", "2024-11-05"}, + }, + { + name: "conjunction separated supported list", selected: "2025-06-18", + rejection: &rpcError{Code: -32602, Message: "Unsupported protocol version. Supported: 2026-07-28 and 2025-06-18"}, + wantCalls: []string{"2025-11-25", "2025-06-18"}, + }, + { + name: "or separated supported list", selected: "2025-03-26", + rejection: &rpcError{Code: -32602, Message: "Unsupported protocol version. Supported: 2026-07-28 OR 2025-03-26"}, + wantCalls: []string{"2025-11-25", "2025-03-26"}, + }, + { + name: "conjunction before unsupported label", selected: "2024-11-05", + rejection: &rpcError{Code: -32602, Message: "Unsupported protocol version. Supported: 2024-11-05 and Unsupported: 2025-06-18"}, + wantCalls: []string{"2025-11-25", "2024-11-05"}, + }, + { + name: "no overlap", rejection: &rpcError{Code: -32602, Message: "Unsupported protocol version 2025-11-25; supported: 2026-07-28"}, + wantCalls: []string{"2025-11-25", "2024-11-05"}, wantError: "Unsupported protocol version", + }, + { + name: "ordinary invalid params", rejection: &rpcError{Code: -32602, Message: "Invalid params", Data: json.RawMessage(`{"missing":"clientInfo"}`)}, + wantCalls: []string{"2025-11-25"}, wantError: "clientInfo", + }, + { + name: "RPC authentication failure", rejection: &rpcError{Code: -32001, Message: "Authentication required"}, + wantCalls: []string{"2025-11-25"}, wantError: "Authentication required", + }, + { + name: "authentication failure", rejection: errors.New("HTTP 401: unauthorized"), + wantCalls: []string{"2025-11-25"}, wantError: "unauthorized", + }, + } { + t.Run(tc.name, func(t *testing.T) { + var calls []string + version, err := negotiateProtocol(context.Background(), func(_ context.Context, method string, params any, target any) error { + if method != "initialize" { + t.Fatalf("method = %q", method) + } + calls = append(calls, params.(map[string]any)["protocolVersion"].(string)) + if tc.rejection != nil && (len(calls) == 1 || tc.wantError != "") { + return fmt.Errorf("wrapped RPC failure: %w", tc.rejection) + } + return json.Unmarshal([]byte(fmt.Sprintf(`{"protocolVersion":%q}`, tc.selected)), target) + }) + if !reflect.DeepEqual(calls, tc.wantCalls) { + t.Fatalf("proposals = %v, want %v", calls, tc.wantCalls) + } + if tc.wantError != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantError) { + t.Fatalf("error = %v, want %q", err, tc.wantError) + } + } else { + wantVersion := tc.selected + if wantVersion == "" { + wantVersion = clientProtocolVersions[0] + } + if err != nil || version != wantVersion { + t.Fatalf("negotiated = %q, %v, want %q", version, err, wantVersion) + } + } + }) + } +} + +func TestNegotiateProtocolKeepsFirstErrorAfterLegacyRejection(t *testing.T) { + first := &rpcError{Code: -32602, Message: "first invalid params"} + for _, last := range []error{&rpcError{Code: -32603, Message: "legacy fallback failed"}, errors.New("connection closed"), nil} { + var proposals []string + _, err := negotiateProtocol(context.Background(), func(_ context.Context, _ string, params any, target any) error { + proposals = append(proposals, params.(map[string]any)["protocolVersion"].(string)) + if len(proposals) == 1 { + return first + } + if last == nil { + return json.Unmarshal([]byte(`{"protocolVersion":"2024-10-07"}`), target) + } + return last + }) + if !reflect.DeepEqual(proposals, []string{"2025-11-25", "2024-11-05"}) || !errors.Is(err, first) || errors.Is(err, last) { + t.Fatalf("proposals=%v error=%v; want one legacy fallback and the first error", proposals, err) + } + } +} + +func TestNegotiateProtocolUsesHintsFromTheLegacyAttempt(t *testing.T) { + var proposals []string + version, err := negotiateProtocol(context.Background(), func(_ context.Context, _ string, params any, target any) error { + proposed := params.(map[string]any)["protocolVersion"].(string) + proposals = append(proposals, proposed) + switch proposed { + case "2025-11-25": + return &rpcError{Code: -32602, Message: "Invalid params"} + case "2024-11-05": + return &rpcError{Code: -32602, Message: "Unsupported protocol version", Data: json.RawMessage(`{"supported":["2025-06-18"]}`)} + default: + return json.Unmarshal([]byte(`{"protocolVersion":"2025-06-18"}`), target) + } + }) + if err != nil || version != "2025-06-18" || !reflect.DeepEqual(proposals, []string{"2025-11-25", "2024-11-05", "2025-06-18"}) { + t.Fatalf("version=%q proposals=%v error=%v; want the legacy attempt's advertised version", version, proposals, err) + } +} + +func TestNegotiateProtocolDoesNotRepeatRejectedVersions(t *testing.T) { + var calls int + _, err := negotiateProtocol(context.Background(), func(context.Context, string, any, any) error { + calls++ + return &rpcError{Code: -32602, Message: "Unsupported protocol version; supported: 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05"} + }) + if err == nil || calls != 4 { + t.Fatalf("negotiation = %v after %d requests, want failure after four", err, calls) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + _, err = negotiateProtocol(ctx, func(context.Context, string, any, any) error { + t.Fatal("canceled handshake sent a request") + return nil + }) + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled negotiation = %v", err) + } +} + +func TestRPCErrorDataIsPreservedAndScrubbed(t *testing.T) { + const key = "review-fake-injected-service-key" + var message rpcMessage + if err := json.Unmarshal([]byte(`{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params","data":{"detail":"protocol version rejected","review-fake-injected-service-key":["review-fake-injected-service-key"]}}}`), &message); err != nil { + t.Fatal(err) + } + if !strings.Contains(message.Error.Error(), key) || !strings.Contains(message.Error.Error(), "protocol version rejected") { + t.Fatalf("RPC error lost data: %v", message.Error) + } + scrubbed := scrubAIMLAPIKeys(message, key) + if strings.Contains(scrubbed.Error.Error(), key) || !strings.Contains(scrubbed.Error.Error(), "protocol version rejected") { + t.Fatalf("RPC error data was not safely retained: %v", scrubbed.Error) + } +} + +func TestHTTPVersionRejectionRequiresMatchingRPCResponse(t *testing.T) { + for _, id := range []int{1, 99} { + response := fakeHTTPResponse(nil, 400, fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"error":{"code":-32602,"message":"Invalid params","data":"Unsupported protocol version; supported: 2025-06-18"}}`, id)) + err := httpRPCStatusError(Server{Name: "versions", Type: ServerTypeHTTP}, response, rpcMessage{ID: 1, Method: "initialize"}) + var rpc *rpcError + if got := errors.As(err, &rpc); got != (id == 1) { + t.Fatalf("response id %d: retryable RPC error = %v (%v)", id, got, err) + } + } +} + +func TestHTTPVersionErrorsAreDecodedOnlyDuringInitialization(t *testing.T) { + for _, status := range []int{406, 422, 500} { + for _, method := range []string{"initialize", "tools/call"} { + response := fakeHTTPResponse(nil, status, `{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params","data":{"supported":["2024-11-05"]}}}`) + err := httpRPCStatusError(Server{Name: "versions", Type: ServerTypeHTTP}, response, rpcMessage{ID: 1, Method: method}) + var rpc *rpcError + if got := errors.As(err, &rpc); got != (method == "initialize") { + t.Fatalf("HTTP %d method %s: typed RPC error=%v, error=%v", status, method, got, err) + } + } + } +} + +func TestHTTPVersionRejectionScrubsJSONEncodedServiceKeys(t *testing.T) { + const key = "review-fake-injected-service-key" + response := fakeHTTPResponse(nil, 400, `{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params","data":{"detail":"Unsupported protocol version","echo":"\u0072eview-fake-injected-service-key"}}}`) + err := httpRPCStatusError(Server{Name: "versions", Type: ServerTypeHTTP}, response, rpcMessage{ID: 1, Method: "initialize"}, key) + var rpc *rpcError + if !errors.As(err, &rpc) { + t.Fatalf("version error lost its type: %v", err) + } + var data map[string]string + if err := json.Unmarshal(rpc.Data, &data); err != nil { + t.Fatal(err) + } + if strings.Contains(data["echo"], key) || data["detail"] != "Unsupported protocol version" { + t.Fatal("HTTP rejection retained an encoded service key or lost its version detail") + } +} diff --git a/internal/mcp/network_client.go b/internal/mcp/network_client.go index f67b3b3bb..e25d9053b 100644 --- a/internal/mcp/network_client.go +++ b/internal/mcp/network_client.go @@ -17,24 +17,26 @@ import ( ) type networkClient struct { - server Server - client *http.Client - mu sync.Mutex - nextID int - sessionID string + server Server + client *http.Client + mu sync.Mutex + nextID int + sessionID string + protocolVersion string } type remoteSSEClient struct { - server Server - client *http.Client - mu sync.Mutex - nextID int - endpointURL string - streamBody io.Closer - streamCancel context.CancelFunc - pending map[string]chan ssePendingResponse - streamErr error - closed bool + server Server + client *http.Client + mu sync.Mutex + nextID int + endpointURL string + streamBody io.Closer + streamCancel context.CancelFunc + pending map[string]chan ssePendingResponse + streamErr error + closed bool + protocolVersion string // streamKeys are the injected AI/ML API keys the stream request carried, // redirect hops included. openStream sets them once, before the reader // starts; the endpoint and the messages on the stream come from a server @@ -91,37 +93,29 @@ func connectRemoteSSE(ctx context.Context, server Server) (ToolClient, error) { } func (client *networkClient) initialize(ctx context.Context) error { - var result struct { - ProtocolVersion string `json:"protocolVersion"` - } - if err := client.request(ctx, "initialize", map[string]any{ - "protocolVersion": "2024-11-05", - "capabilities": map[string]any{}, - "clientInfo": map[string]any{ - "name": "zero", - "version": "dev", - }, - }, &result); err != nil { + initCtx, cancel := context.WithTimeout(ctx, initializeTimeout) + defer cancel() + version, err := negotiateProtocol(initCtx, client.request) + if err != nil { return err } - return client.notify(ctx, "notifications/initialized", map[string]any{}) + client.mu.Lock() + client.protocolVersion = version + client.mu.Unlock() + return client.notify(initCtx, "notifications/initialized", map[string]any{}) } func (client *remoteSSEClient) initialize(ctx context.Context) error { - var result struct { - ProtocolVersion string `json:"protocolVersion"` - } - if err := client.request(ctx, "initialize", map[string]any{ - "protocolVersion": "2024-11-05", - "capabilities": map[string]any{}, - "clientInfo": map[string]any{ - "name": "zero", - "version": "dev", - }, - }, &result); err != nil { + initCtx, cancel := context.WithTimeout(ctx, initializeTimeout) + defer cancel() + version, err := negotiateProtocol(initCtx, client.request) + if err != nil { return err } - return client.notify(ctx, "notifications/initialized", map[string]any{}) + client.mu.Lock() + client.protocolVersion = version + client.mu.Unlock() + return client.notify(initCtx, "notifications/initialized", map[string]any{}) } func (client *networkClient) ListTools(ctx context.Context) ([]RemoteTool, error) { @@ -228,7 +222,7 @@ func (client *networkClient) request(ctx context.Context, method string, params return fmt.Errorf("MCP %s response id mismatch for server %s", method, client.server.Name) } if message.Error != nil { - return fmt.Errorf("MCP %s failed: %s", method, message.Error.Message) + return fmt.Errorf("MCP %s failed: %w", method, message.Error) } if target != nil && len(message.Result) > 0 { if err := json.Unmarshal(message.Result, target); err != nil { @@ -285,7 +279,7 @@ func (client *remoteSSEClient) request(ctx context.Context, method string, param return fmt.Errorf("MCP %s response id mismatch for server %s", method, client.server.Name) } if message.Error != nil { - return fmt.Errorf("MCP %s failed: %s", method, message.Error.Message) + return fmt.Errorf("MCP %s failed: %w", method, message.Error) } if target != nil && len(message.Result) > 0 { if err := json.Unmarshal(message.Result, target); err != nil { @@ -350,6 +344,9 @@ func (client *networkClient) post(ctx context.Context, message rpcMessage, expec return rpcMessage{}, fmt.Errorf("create MCP %s request for %s: %w", client.server.Type, client.server.Name, err) } client.applyHeaders(request) + if message.Method == "initialize" { + request.Header.Del("MCP-Protocol-Version") + } response, err := client.client.Do(request) if err != nil { @@ -361,7 +358,7 @@ func (client *networkClient) post(ctx context.Context, message rpcMessage, expec client.sessionID = sessionID } if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices { - return rpcMessage{}, client.statusError(response) + return rpcMessage{}, httpRPCStatusError(client.server, response, message, sent.list()...) } if !expectResponse { _, _ = io.Copy(io.Discard, response.Body) @@ -435,6 +432,9 @@ func (client *remoteSSEClient) post(ctx context.Context, message rpcMessage) (se return nil, fmt.Errorf("create MCP SSE post for %s: %w", client.server.Name, err) } client.applyPostHeaders(request) + if message.Method == "initialize" { + request.Header.Del("MCP-Protocol-Version") + } response, err := client.client.Do(request) if err != nil { @@ -442,7 +442,7 @@ func (client *remoteSSEClient) post(ctx context.Context, message rpcMessage) (se } defer closeResponseBody(&err, client.server, response.Body) if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices { - return nil, httpStatusError(client.server, response) + return nil, httpRPCStatusError(client.server, response, message, append(append([]string(nil), client.streamKeys...), sent.list()...)...) } _, _ = io.Copy(io.Discard, response.Body) return nil, nil @@ -454,6 +454,10 @@ func (client *networkClient) applyHeaders(request *http.Request) { } request.Header.Set("Content-Type", "application/json") request.Header.Set("Accept", "application/json, text/event-stream") + request.Header.Del("MCP-Protocol-Version") + if client.protocolVersion != "" { + request.Header.Set("MCP-Protocol-Version", client.protocolVersion) + } if client.sessionID != "" { request.Header.Set("Mcp-Session-Id", client.sessionID) } @@ -465,6 +469,7 @@ func (client *remoteSSEClient) applyStreamHeaders(request *http.Request) { request.Header.Set(key, value) } request.Header.Set("Accept", "text/event-stream") + request.Header.Del("MCP-Protocol-Version") applyAIMLAPIRequestHeaders(client.server, request) } @@ -474,6 +479,13 @@ func (client *remoteSSEClient) applyPostHeaders(request *http.Request) { } request.Header.Set("Content-Type", "application/json") request.Header.Set("Accept", "application/json") + client.mu.Lock() + version := client.protocolVersion + client.mu.Unlock() + request.Header.Del("MCP-Protocol-Version") + if version != "" { + request.Header.Set("MCP-Protocol-Version", version) + } applyAIMLAPIRequestHeaders(client.server, request) } @@ -498,10 +510,6 @@ func (client *networkClient) decodeResponse(response *http.Response) (rpcMessage return message, nil } -func (client *networkClient) statusError(response *http.Response) error { - return httpStatusError(client.server, response) -} - func (client *remoteSSEClient) readStream(reader io.Reader, ready chan<- error) { endpointReady := false signalReady := func(err error) { @@ -640,6 +648,54 @@ func (client *remoteSSEClient) failPending(err error) { } } +// Servers may reject an initialize proposal with any HTTP error status. +// Preserve JSON-RPC error data for negotiation, while authentication failures +// retain the ordinary diagnostics and credential-body policy without a retry. +type initializeHTTPRejection struct { + cause error + // Only strings from clientProtocolVersions may be retained here. + versions []string + unrelated bool +} + +func (err *initializeHTTPRejection) Error() string { return err.cause.Error() } +func (err *initializeHTTPRejection) Unwrap() error { return err.cause } + +func httpRPCStatusError(server Server, response *http.Response, request rpcMessage, keys ...string) error { + if request.Method != "initialize" || response.StatusCode < http.StatusBadRequest || + response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden { + return httpStatusError(server, response) + } + omitBody := sentAIMLAPIServiceKey(server, response.Request) + const maxErrorBytes = 64 * 1024 + body, readErr := io.ReadAll(io.LimitReader(response.Body, maxErrorBytes+1)) + // The caller already deferred closing the original body. Restore these + // bytes for the ordinary status diagnostic if this is not a JSON-RPC error. + response.Body = io.NopCloser(bytes.NewReader(body)) + var rejected rpcMessage + expectedID, validID := rpcMessageID(request.ID) + if readErr == nil && len(body) <= maxErrorBytes && json.Unmarshal(body, &rejected) == nil && + rejected.JSONRPC == "2.0" && !rejected.isRequestOrNotification() && rejected.Error != nil && + (rejected.ID == nil || (validID && rpcIDMatches(rejected.ID, expectedID))) { + if omitBody { + // Keep server text and error data out of the entire error chain. + // Negotiation only needs the intersection with our fixed versions. + safe := &initializeHTTPRejection{cause: httpStatusError(server, response)} + safe.unrelated = unrelatedInitializeRejection(rejected.Error) + advertised, _ := advertisedProtocolVersions(rejected.Error) + for _, version := range clientProtocolVersions { + if advertised[version] { + safe.versions = append(safe.versions, version) + } + } + return safe + } + rejected = scrubAIMLAPIKeys(rejected, keys...) + return fmt.Errorf("MCP %s server %s returned HTTP %d: %w", server.Type, server.Name, response.StatusCode, rejected.Error) + } + return &initializeHTTPRejection{cause: httpStatusError(server, response)} +} + func httpStatusError(server Server, response *http.Response) error { hint := aimlapiUnauthorizedHint(server, response.StatusCode) if sentAIMLAPIServiceKey(server, response.Request) { diff --git a/internal/mcp/protocol.go b/internal/mcp/protocol.go index 0f388e20c..cf2f9e193 100644 --- a/internal/mcp/protocol.go +++ b/internal/mcp/protocol.go @@ -64,8 +64,16 @@ func (m *rpcMessage) UnmarshalJSON(data []byte) error { } type rpcError struct { - Code int `json:"code"` - Message string `json:"message"` + Code int `json:"code"` + Message string `json:"message"` + Data json.RawMessage `json:"data,omitempty"` +} + +func (err *rpcError) Error() string { + if len(err.Data) == 0 || string(err.Data) == "null" { + return err.Message + } + return err.Message + ": " + string(err.Data) } type messageReader struct { diff --git a/internal/mcp/protocol_legacy_compatibility_test.go b/internal/mcp/protocol_legacy_compatibility_test.go new file mode 100644 index 000000000..84ddbd017 --- /dev/null +++ b/internal/mcp/protocol_legacy_compatibility_test.go @@ -0,0 +1,163 @@ +package mcp + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// These fixtures use the public connection path and compile against main. +// Every successful row represents a server that already connects on main. +func TestHTTPProtocolLegacyCompatibility(t *testing.T) { + for _, mode := range []string{ + "counteroffer", "spec_error", "spec_error_400", "no_list", "invalid_params", + "must_be", "plain_400", "supported_message", "missing_version", "old_counteroffer", "echo", + "validation_422", "spec_error_422", "plain_406", "plain_500", + } { + t.Run(mode, func(t *testing.T) { + var mu sync.Mutex + var proposals []string + var initialized bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + message := readHTTPRPCMessage(t, r) + if message.Method != "initialize" { + if message.Method == "notifications/initialized" { + initialized = true + w.WriteHeader(http.StatusAccepted) + } else { + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"tools": []any{}}) + } + return + } + var params struct { + Version string `json:"protocolVersion"` + } + if err := json.Unmarshal(message.Params, ¶ms); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + proposals = append(proposals, params.Version) + switch mode { + case "counteroffer": + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"protocolVersion": "2024-11-05"}) + return + case "missing_version": + writeHTTPRPCResponse(t, w, message.ID, map[string]any{}) + return + case "old_counteroffer": + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"protocolVersion": "2024-10-07"}) + return + case "echo": + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"protocolVersion": params.Version}) + return + } + if params.Version == "2024-11-05" { + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"protocolVersion": params.Version}) + return + } + status := map[string]int{"plain_400": 400, "validation_422": 422, "plain_406": 406, "plain_500": 500}[mode] + if status != 0 { + body := "legacy server refused the proposal" + if mode == "validation_422" { + body = `{"detail":[{"loc":["body","params","protocolVersion"],"msg":"unsupported value"}]}` + } + http.Error(w, body, status) + return + } + rejection := map[string]any{"code": -32602, "message": "Unsupported protocol version"} + switch mode { + case "spec_error", "spec_error_400", "spec_error_422": + rejection["data"] = map[string]any{"supported": []string{"2024-11-05"}, "requested": params.Version} + case "invalid_params": + rejection["message"] = "Invalid params" + case "must_be": + rejection["message"] = "protocolVersion must be 2024-11-05" + case "supported_message": + rejection["message"] = "Unsupported protocol version. Supported versions: 2024-11-05" + } + w.Header().Set("Content-Type", "application/json") + if mode == "spec_error_400" { + w.WriteHeader(http.StatusBadRequest) + } else if mode == "spec_error_422" { + w.WriteHeader(http.StatusUnprocessableEntity) + } + if err := json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": message.ID, "error": rejection}); err != nil { + t.Error(err) + } + })) + defer server.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client, err := Connect(ctx, Server{Name: "legacy-compatibility", Type: ServerTypeHTTP, URL: server.URL}) + if client != nil { + defer client.Close() + } + if mode == "old_counteroffer" { + if err == nil || !strings.Contains(err.Error(), "2024-10-07") { + t.Fatalf("unsupported counteroffer: %v", err) + } + mu.Lock() + defer mu.Unlock() + if initialized { + t.Fatal("sent initialized after an unsupported counteroffer") + } + return + } + if err != nil { + t.Fatalf("legacy server no longer connects: %v", err) + } + if _, err := client.ListTools(ctx); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if !initialized || len(proposals) > 2 { + t.Fatalf("initialized=%v proposals=%v; want a bounded successful connection", initialized, proposals) + } + }) + } +} + +func TestHTTPProtocolAuthenticationFailureIsNotRetried(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden} { + for _, structured := range []bool{false, true} { + var mu sync.Mutex + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + calls++ + if structured { + message := readHTTPRPCMessage(t, r) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{"jsonrpc": "2.0", "id": message.ID, + "error": map[string]any{"code": -32602, "message": "Unsupported protocol version", + "data": map[string]any{"supported": []string{"2024-11-05"}}}}) + } else { + http.Error(w, "authentication refused", status) + } + })) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + client, err := Connect(ctx, Server{Name: "auth-refusal", Type: ServerTypeHTTP, URL: server.URL}) + if client != nil { + _ = client.Close() + } + cancel() + server.Close() + mu.Lock() + if err == nil || calls != 1 { + t.Errorf("HTTP %d: calls=%d error=%v; want one failed request", status, calls, err) + } + mu.Unlock() + } + } +} diff --git a/internal/mcp/protocol_negotiation_integration_test.go b/internal/mcp/protocol_negotiation_integration_test.go new file mode 100644 index 000000000..8b697c6b7 --- /dev/null +++ b/internal/mcp/protocol_negotiation_integration_test.go @@ -0,0 +1,269 @@ +package mcp + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync" + "testing" + "time" +) + +// This test also compiles against the unfixed client, so the same wire fixture +// can demonstrate the original failure without depending on the new helper. +func TestHTTPProtocolNegotiationAfterVersionRejection(t *testing.T) { + for _, status := range []int{http.StatusOK, http.StatusBadRequest} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var mu sync.Mutex + var proposals []string + var initialized bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + message := readHTTPRPCMessage(t, r) + if message.Method == "initialize" { + if got := r.Header.Get("MCP-Protocol-Version"); got != "" { + t.Errorf("initialize version header = %q, want absent", got) + } + var params struct { + Version string `json:"protocolVersion"` + } + if err := json.Unmarshal(message.Params, ¶ms); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + proposals = append(proposals, params.Version) + if params.Version != "2025-06-18" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{ + "jsonrpc": "2.0", "id": message.ID, + "error": map[string]any{"code": -32602, "message": "Invalid params", + "data": fmt.Sprintf("Unsupported protocol version '%s'. Supported: 2026-07-28, 2025-06-18, 2025-03-26", params.Version)}, + }) + return + } + w.Header().Set("Mcp-Session-Id", "negotiated-session") + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"protocolVersion": "2025-06-18"}) + return + } + if got := r.Header.Get("MCP-Protocol-Version"); got != "2025-06-18" { + t.Errorf("%s version header = %q", message.Method, got) + } + if got := r.Header.Get("Mcp-Session-Id"); got != "negotiated-session" { + t.Errorf("%s session header = %q", message.Method, got) + } + switch message.Method { + case "notifications/initialized": + initialized = true + w.WriteHeader(http.StatusAccepted) + case "tools/list": + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"tools": []any{}}) + default: + t.Errorf("unexpected method %s", message.Method) + w.WriteHeader(http.StatusBadRequest) + } + })) + defer server.Close() + client, err := Connect(ctx, Server{Name: "version-test", Type: ServerTypeHTTP, URL: server.URL, + Headers: map[string]string{"MCP-Protocol-Version": "wrong-configured-version"}}) + if err != nil { + t.Fatalf("Connect() = %v", err) + } + defer client.Close() + if _, err := client.ListTools(ctx); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if !initialized || !reflect.DeepEqual(proposals, []string{"2025-11-25", "2025-06-18"}) { + t.Fatalf("initialized=%v proposals=%v", initialized, proposals) + } + }) + } +} + +func TestHTTPProtocolCounterofferAndUnsupportedVersion(t *testing.T) { + for _, selected := range []string{"2024-11-05", "2026-07-28"} { + t.Run(selected, func(t *testing.T) { + var mu sync.Mutex + var initialized bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + defer mu.Unlock() + message := readHTTPRPCMessage(t, r) + if message.Method == "initialize" { + writeHTTPRPCResponse(t, w, message.ID, map[string]any{"protocolVersion": selected}) + return + } + initialized = true + if got := r.Header.Get("MCP-Protocol-Version"); got != selected { + t.Errorf("negotiated header = %q, want %q", got, selected) + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + client, err := Connect(ctx, Server{Name: "counteroffer", Type: ServerTypeHTTP, URL: server.URL}) + if client != nil { + defer client.Close() + } + mu.Lock() + defer mu.Unlock() + if selected == "2026-07-28" { + if err == nil || initialized || !strings.Contains(err.Error(), selected) { + t.Fatalf("unsupported offer = %v, initialized=%v", err, initialized) + } + } else if err != nil || !initialized { + t.Fatalf("supported offer = %v, initialized=%v", err, initialized) + } + }) + } +} + +func TestStdioProtocolNegotiation(t *testing.T) { + serverReader, clientWriter := io.Pipe() + clientReader, serverWriter := io.Pipe() + defer serverReader.Close() + defer clientWriter.Close() + defer clientReader.Close() + defer serverWriter.Close() + client := &Client{server: Server{Name: "stdio-versions"}, stdin: clientWriter, + reader: newMessageReader(clientReader), writer: newMessageWriter(clientWriter), nextID: 1} + defer client.Close() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + done := make(chan error, 1) + go func() { + reader, writer := newMessageReader(serverReader), newMessageWriter(serverWriter) + for _, expected := range []string{"2025-11-25", "2025-03-26"} { + message, err := reader.read() + if err != nil { + done <- err + return + } + var params struct { + Version string `json:"protocolVersion"` + } + if err := json.Unmarshal(message.Params, ¶ms); err != nil || (expected == "2025-03-26" && params.Version != expected) { + done <- fmt.Errorf("stdio proposal = %q, %v; want %q", params.Version, err, expected) + return + } + response := rpcMessage{JSONRPC: "2.0", ID: message.ID} + if expected == "2025-11-25" { + if err := json.Unmarshal([]byte(`{"code":-32602,"message":"Unsupported protocol version; supported: 2025-03-26"}`), &response.Error); err != nil { + done <- err + return + } + } else { + response.Result = json.RawMessage(`{"protocolVersion":"2025-03-26"}`) + } + if err := writer.write(response); err != nil { + done <- err + return + } + } + message, err := reader.read() + if err == nil && message.Method != "notifications/initialized" { + err = fmt.Errorf("last method = %q", message.Method) + } + done <- err + }() + if err := client.initialize(ctx); err != nil { + t.Fatal(err) + } + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal(ctx.Err()) + } +} + +func TestSSEProtocolNegotiation(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + events := make(chan string, 4) + var mu sync.Mutex + var proposals []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet { + if got := r.Header.Get("MCP-Protocol-Version"); got != "" { + t.Errorf("initial stream version header = %q", got) + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprint(w, "event: endpoint\ndata: /messages\n\n") + w.(http.Flusher).Flush() + for { + select { + case event := <-events: + _, _ = fmt.Fprint(w, event) + w.(http.Flusher).Flush() + case <-r.Context().Done(): + return + } + } + } + mu.Lock() + defer mu.Unlock() + message := readHTTPRPCMessage(t, r) + if message.Method == "initialize" { + if got := r.Header.Get("MCP-Protocol-Version"); got != "" { + t.Errorf("initialize version header = %q", got) + } + var params struct { + Version string `json:"protocolVersion"` + } + if err := json.Unmarshal(message.Params, ¶ms); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + proposals = append(proposals, params.Version) + if params.Version != "2025-06-18" { + data, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": message.ID, + "error": map[string]any{"code": -32602, "message": "Invalid params", + "data": "Unsupported protocol version; supported: 2025-06-18"}}) + events <- "event: message\ndata: " + string(data) + "\n\n" + } else { + events <- formatSSERPCResponse(t, message.ID, map[string]any{"protocolVersion": params.Version}) + } + } else { + if got := r.Header.Get("MCP-Protocol-Version"); got != "2025-06-18" { + t.Errorf("%s version header = %q", message.Method, got) + } + if message.Method == "tools/list" { + events <- formatSSERPCResponse(t, message.ID, map[string]any{"tools": []any{}}) + } else if message.Method != "notifications/initialized" { + t.Errorf("unexpected method %q", message.Method) + } + } + w.WriteHeader(http.StatusAccepted) + })) + defer server.Close() + client, err := Connect(ctx, Server{Name: "sse-versions", Type: ServerTypeSSE, URL: server.URL, + Headers: map[string]string{"MCP-Protocol-Version": "wrong-configured-version"}}) + if err != nil { + t.Fatal(err) + } + defer client.Close() + if _, err := client.ListTools(ctx); err != nil { + t.Fatal(err) + } + mu.Lock() + defer mu.Unlock() + if !reflect.DeepEqual(proposals, []string{"2025-11-25", "2025-06-18"}) { + t.Fatalf("SSE proposals = %v", proposals) + } +} diff --git a/internal/mcp/protocol_service_key_test.go b/internal/mcp/protocol_service_key_test.go new file mode 100644 index 000000000..540a3c314 --- /dev/null +++ b/internal/mcp/protocol_service_key_test.go @@ -0,0 +1,145 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "reflect" + "strings" + "testing" + + "github.com/Twigpine/zero/internal/aimlapi" +) + +func TestInjectedKeyHTTPRejectionRetainsOnlySupportedVersionHints(t *testing.T) { + for _, transport := range []ServerType{ServerTypeHTTP, ServerTypeSSE} { + for _, tc := range []struct { + name string + status int + id int + oversize bool + want string + }{ + {"rpc400", 400, 1, false, "2025-06-18"}, + {"rpc422", 422, 1, false, "2025-06-18"}, + {"wrong ID", 400, 2, false, legacyProtocolVersion}, + {"oversize", 400, 1, true, legacyProtocolVersion}, + } { + t.Run(fmt.Sprintf("%s/%s", transport, tc.name), func(t *testing.T) { + server := aimlapiTestServer("aimlapi", aimlapi.MCPServerURL) + server.Type = transport + httpRequest, err := http.NewRequest(http.MethodPost, server.URL, nil) + if err != nil { + t.Fatal(err) + } + httpRequest.Header.Set("Authorization", "Bearer "+scrubTestKey) + if !sentAIMLAPIServiceKey(server, httpRequest) { + t.Fatal("fixture did not reach the injected-key branch") + } + body := rpcReply(json.RawMessage(fmt.Sprint(tc.id)), "error", map[string]any{ + "code": -32602, "message": "Unsupported protocol version; echoed " + scrubTestKey, + "data": map[string]any{"supported": []string{"2099-01-01", scrubTestKey + "2025-06-18", "2025-06-18"}, "echo": scrubTestKey[:8]}, + }) + if tc.oversize { + body += strings.Repeat(" ", 64*1024) + } + var proposals []string + version, err := negotiateProtocol(context.Background(), func(_ context.Context, method string, params any, _ any) error { + proposal := params.(map[string]any)["protocolVersion"].(string) + proposals = append(proposals, proposal) + if proposal == tc.want { + return nil + } + response := fakeHTTPResponse(httpRequest, tc.status, body) + defer response.Body.Close() + rejection := httpRPCStatusError(server, response, rpcMessage{ID: 1, Method: method}, scrubTestKey) + var rpc *rpcError + if errors.As(rejection, &rpc) { + t.Fatal("injected-key response retained the server's RPC error") + } + for cause := rejection; cause != nil; cause = errors.Unwrap(cause) { + if !strings.Contains(cause.Error(), "response body omitted") || strings.Contains(cause.Error(), scrubTestKey[:8]) { + t.Fatalf("server body escaped omission policy: %s", cause.Error()) + } + } + return rejection + }) + if err != nil || version != tc.want { + t.Fatalf("negotiated %q: %v; want %s", version, err, tc.want) + } + if want := []string{clientProtocolVersions[0], tc.want}; !reflect.DeepEqual(proposals, want) { + t.Fatalf("proposals=%v want=%v", proposals, want) + } + }) + } + } +} + +func TestHTTPRejectionStopsForExplicitUnrelatedRPCFailures(t *testing.T) { + for _, transport := range []ServerType{ServerTypeHTTP, ServerTypeSSE} { + for _, injected := range []bool{false, true} { + for _, status := range []int{400, 422} { + for _, hints := range []bool{false, true} { + for _, kind := range []string{"authentication", "missing field", "generic invalid params"} { + t.Run(fmt.Sprintf("%s/injected=%v/%d/hints=%v/%s", transport, injected, status, hints, kind), func(t *testing.T) { + server := aimlapiTestServer("aimlapi", aimlapi.MCPServerURL) + server.Type = transport + if !injected { + server.Headers = map[string]string{"Authorization": "Bearer user-token"} + } + request, err := http.NewRequest(http.MethodPost, server.URL, nil) + if err != nil { + t.Fatal(err) + } + request.Header.Set("Authorization", "Bearer "+scrubTestKey) + data := map[string]any{"echo": scrubTestKey[:8]} + message := "Invalid params" + if kind == "authentication" { + message = "Unauthorized" + } + if kind == "missing field" { + data["missing"] = "clientInfo" + } + if hints { + data["supported"] = []string{"2025-06-18"} + } + body := rpcReply(json.RawMessage("1"), "error", map[string]any{"code": -32602, "message": message, "data": data}) + var proposals []string + _, err = negotiateProtocol(context.Background(), func(_ context.Context, method string, params any, _ any) error { + proposals = append(proposals, params.(map[string]any)["protocolVersion"].(string)) + if len(proposals) > 1 { + return nil + } + response := fakeHTTPResponse(request, status, body) + defer response.Body.Close() + return httpRPCStatusError(server, response, rpcMessage{ID: 1, Method: method}, scrubTestKey) + }) + if kind != "generic invalid params" { + if err == nil || len(proposals) != 1 { + t.Fatalf("explicit unrelated rejection: proposals=%v error=%v; want one failed request", proposals, err) + } + if injected { + for cause := err; cause != nil; cause = errors.Unwrap(cause) { + if !strings.Contains(cause.Error(), "response body omitted") || strings.Contains(cause.Error(), scrubTestKey[:8]) { + t.Fatal("unrelated-rejection classification retained server text") + } + } + } + } else { + want := legacyProtocolVersion + if hints { + want = "2025-06-18" + } + if err != nil || !reflect.DeepEqual(proposals, []string{clientProtocolVersions[0], want}) { + t.Fatalf("generic rejection: proposals=%v error=%v; want one compatible retry", proposals, err) + } + } + }) + } + } + } + } + } +}