mcp: Implement support for SEP-2575 on client side (#975)

Implements the client half of the SEP-2575 / `2026-06-30` protocol. This
CL is client-only; server-side `server/discover` is still a
`MethodNotFound` stub.
### Changes
- **`server/discover` probe in `Client.Connect()`** (`client.go`). When
the caller opts into `protocolVersion >= 2026-06-30`, the client probes
the server with `server/discover` before falling back to the legacy
`initialize`
  handshake.
- **Per-request `_meta` injection** (`shared.go`, `injectRequestMeta`).
For`>= 2026-06-30` sessions every outgoing request gets the SEP-2575
triple (`protocolVersion`, `clientInfo`, `clientCapabilities`).
- **Server-side fix**: `ServerSession.handle` no longer pre-populates
`state.InitializeParams` from a `server/discover` request's `_meta`, so
a subsequent fallback `initialize` is not rejected as a duplicate.
### Fallback rules
Client falls back to the legacy `initialize` handshake when discover
returns:
- `MethodNotFound` (-32601),
- `UnsupportedProtocolVersionError` (-32004),
- an HTTP `Bad Request` (substring-matched on the error message, to
interop
  with pre-2026-06-30 servers).

Fixes #966
This commit is contained in:
Guglielmo Colombo 2026-06-02 14:17:01 +02:00 • committed by GitHub
commit c60a318d22
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -165,6 +165,7 @@ type ClientOptions struct {
// If non-zero, defines an interval for regular "ping" requests.
// If the peer fails to respond to pings originating from the keepalive check,
// the session is automatically closed.
// NOTE: The keepalive feature is only available for protocol versions < 2026-06-30
KeepAlive time.Duration
// KeepAliveFailureThreshold is the number of consecutive keepalive ping
// failures tolerated before the session is closed. A value of 0 or 1
@ -283,6 +284,27 @@ func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOp
if opts != nil && opts.protocolVersion != "" {
protocolVersion = opts.protocolVersion
}
if protocolVersion >= protocolVersion20260630 {
// Per SEP-2575, try the stateless server/discover RPC first. If the server
// signals it doesn't support it, fall back to the legacy initialize
// handshake.
discoverCtx := context.WithValue(ctx, protocolVersionContextKey{}, protocolVersion)
discRes, fallback, err := c.discover(discoverCtx, cs)
if err != nil {
return nil, err
}
if !fallback {
cs.state.InitializeResult = discRes
if hc, ok := cs.mcpConn.(clientConnection); ok {
hc.sessionUpdated(cs.state)
}
return cs, nil
}
// Fallback to the legacy initialize handshake.
protocolVersion = protocolVersion20251125
}
params := &InitializeParams{
ProtocolVersion: protocolVersion,
ClientInfo: c.impl,
@ -314,6 +336,66 @@ func (c *Client) Connect(ctx context.Context, t Transport, opts *ClientSessionOp
return cs, nil
}
// discover sends a SEP-2575 server/discover request to probe the server for
// stateless protocol support.
//
// The return values have three possible combinations:
// - (result, false, nil): discovery succeeded; caller should skip legacy initialization.
// - (nil, true, nil): the server explicitly signaled it doesn't support
// discovery (Method not found, or UnsupportedProtocolVersionError, or version mismatch);
// caller should fall back to the legacy initialize handshake.
// - (nil, false, err): any other failure (transport error, malformed response, etc.);
// caller should propagate the error.
func (c *Client) discover(ctx context.Context, cs *ClientSession) (*InitializeResult, bool, error) {
protocolVersion := protocolVersionFromContext(ctx)
caps := c.capabilities(protocolVersion)
params := &DiscoverParams{
Meta: Meta{
MetaKeyProtocolVersion: protocolVersion,
MetaKeyClientInfo: c.impl,
MetaKeyClientCapabilities: caps,
},
}
req := &DiscoverRequest{Session: cs, Params: params}
res, err := handleSend[*DiscoverResult](ctx, methodDiscover, req)
if err != nil {
// According to SEP-2575, only the two signals below (MethodNotFound
// and UnsupportedProtocolVersionError) should trigger a fallback.
var werr *jsonrpc.Error
if errors.As(err, &werr) && (werr.Code == jsonrpc.CodeMethodNotFound || werr.Code == CodeUnsupportedProtocolVersion) {
return nil, true, nil
}
return nil, false, err
}
// Pick the highest protocol version that both the server and this SDK support.
// Since supportedProtocolVersions is defined in descending order (newest to oldest),
// the first match we find is the highest supported version.
var negotiated string
if slices.Contains(res.SupportedVersions, protocolVersion) {
negotiated = protocolVersion
} else {
for _, v := range supportedProtocolVersions {
if slices.Contains(res.SupportedVersions, v) {
negotiated = v
break
}
}
}
if negotiated == "" || negotiated < protocolVersion20260630 {
// If there is no overlap, fall back to initialize so version
// negotiation can happen via the legacy path.
return nil, true, nil
}
return &InitializeResult{
Capabilities: res.Capabilities,
Instructions: res.Instructions,
ProtocolVersion: negotiated,
ServerInfo: res.ServerInfo,
}, false, nil
}
// A ClientSession is a logical connection with an MCP server. Its
// methods can be used to send requests or notifications to the server. Create
// a session by calling [Client.Connect].
@ -354,6 +436,42 @@ type clientSessionState struct {
func (cs *ClientSession) InitializeResult() *InitializeResult { return cs.state.InitializeResult }
// usesNewProtocol reports whether this session has negotiated a protocol
// version >= 2026-06-30, which requires the SEP-2575 per-request `_meta`
// triple on every outgoing request.
func (cs *ClientSession) usesNewProtocol() bool {
res := cs.state.InitializeResult
return res != nil && res.ProtocolVersion >= protocolVersion20260630
}
// injectRequestMeta populates the SEP-2575 per-request `_meta` triple
// (protocolVersion, clientInfo, clientCapabilities) on the given outgoing
// request params. Keys already present in params.Meta are not overwritten.
func injectRequestMeta[T any, P interface {
*T
Params
}](cs *ClientSession, params P) P {
res := cs.state.InitializeResult
if params.isNil() {
params = new(T)
}
m := params.GetMeta()
if m == nil {
m = map[string]any{}
}
if _, ok := m[MetaKeyProtocolVersion]; !ok {
m[MetaKeyProtocolVersion] = res.ProtocolVersion
}
if _, ok := m[MetaKeyClientInfo]; !ok {
m[MetaKeyClientInfo] = cs.client.impl
}
if _, ok := m[MetaKeyClientCapabilities]; !ok {
m[MetaKeyClientCapabilities] = cs.client.capabilities(res.ProtocolVersion)
}
params.SetMeta(m)
return params
}
func (cs *ClientSession) ID() string {
if c, ok := cs.mcpConn.(hasSessionID); ok {
return c.SessionID()
@ -1014,16 +1132,25 @@ func (cs *ClientSession) Ping(ctx context.Context, params *PingParams) error {
// ListPrompts lists prompts that are currently available on the server.
func (cs *ClientSession) ListPrompts(ctx context.Context, params *ListPromptsParams) (*ListPromptsResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*ListPromptsResult](ctx, methodListPrompts, newClientRequest(cs, orZero[Params](params)))
}
// GetPrompt gets a prompt from the server.
func (cs *ClientSession) GetPrompt(ctx context.Context, params *GetPromptParams) (*GetPromptResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*GetPromptResult](ctx, methodGetPrompt, newClientRequest(cs, orZero[Params](params)))
}
// ListTools lists tools that are currently available on the server.
func (cs *ClientSession) ListTools(ctx context.Context, params *ListToolsParams) (*ListToolsResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
result, err := handleSend[*ListToolsResult](ctx, methodListTools, newClientRequest(cs, orZero[Params](params)))
if err != nil {
return nil, err
@ -1047,6 +1174,9 @@ func (cs *ClientSession) CallTool(ctx context.Context, params *CallToolParams) (
if tool := cs.getCachedTool(params.Name); tool != nil {
ctx = context.WithValue(ctx, toolContextKey, tool)
}
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*CallToolResult](ctx, methodCallTool, newClientRequest(cs, orZero[Params](params)))
}
@ -1057,20 +1187,32 @@ func (cs *ClientSession) SetLoggingLevel(ctx context.Context, params *SetLogging
// ListResources lists the resources that are currently available on the server.
func (cs *ClientSession) ListResources(ctx context.Context, params *ListResourcesParams) (*ListResourcesResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*ListResourcesResult](ctx, methodListResources, newClientRequest(cs, orZero[Params](params)))
}
// ListResourceTemplates lists the resource templates that are currently available on the server.
func (cs *ClientSession) ListResourceTemplates(ctx context.Context, params *ListResourceTemplatesParams) (*ListResourceTemplatesResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*ListResourceTemplatesResult](ctx, methodListResourceTemplates, newClientRequest(cs, orZero[Params](params)))
}
// ReadResource asks the server to read a resource and return its contents.
func (cs *ClientSession) ReadResource(ctx context.Context, params *ReadResourceParams) (*ReadResourceResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*ReadResourceResult](ctx, methodReadResource, newClientRequest(cs, orZero[Params](params)))
}
func (cs *ClientSession) Complete(ctx context.Context, params *CompleteParams) (*CompleteResult, error) {
if cs.usesNewProtocol() {
params = injectRequestMeta(cs, params)
}
return handleSend[*CompleteResult](ctx, methodComplete, newClientRequest(cs, orZero[Params](params)))
}