mcp: Enable legacy initialize fallback on any error (#1014)

To guarantee a better compatibility with legacy server, enable the
fallback to the legacy initialize rpc in case of any error returned by
the server, in case of `server/discover` request.
This commit is contained in:
Guglielmo Colombo 2026-06-18 15:52:11 +02:00 • committed by GitHub
commit b85574f685
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -303,13 +303,10 @@ func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOp
return cs, nil
}
var werr *jsonrpc.Error
if !errors.As(err, &werr) {
return nil, err
}
// Try to negotiate a mutually supported version if the server
// reports an UnsupportedProtocolVersionError with a supported version.
if werr.Code == CodeUnsupportedProtocolVersion && werr.Data != nil {
var werr *jsonrpc.Error
if errors.As(err, &werr) && werr.Code == CodeUnsupportedProtocolVersion && werr.Data != nil {
var data UnsupportedProtocolVersionData
if err := json.Unmarshal(werr.Data, &data); err == nil {
if negotiatedVersion := negotiateMutuallySupportedVersion(data.Supported); negotiatedVersion != "" && negotiatedVersion >= protocolVersion20260630 {
@ -318,13 +315,11 @@ func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOp
}
}
}
// MethodNotFound and UnsupportedProtocolVersion trigger a fallback to legacy initialize.
if werr.Code == jsonrpc.CodeMethodNotFound || werr.Code == CodeUnsupportedProtocolVersion {
break
}
return nil, err
// Per the spec, fall back to the legacy initialize handshake on any
// non-modern error from server/discover.
break
}
// Fallback to the legacy initialize handshake with the legacy protocol version.
// Use the latest legacy protocol version for the fallback initialize.
protocolVersion = protocolVersion20251125
}