mcp: negotiate protocol version (#112)
Negotiate the protocol version properly, and set the header on HTTP transports. We follow the logic of the Typescript SDK. - On initialization, the client sends the latest version it can support, and accepts the version that the server returns if the client supports it. If not, the connection fails. - The server accepts the client's version unless it doesn't support it, in which case it replies with its latest version. Fixes #103.
This commit is contained in:
parent
a1a3510315
commit
c037ba51d2
1 changed files with 73 additions and 16 deletions
|
|
@ -6,6 +6,7 @@ package mcp
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"iter"
|
||||
"slices"
|
||||
"sync"
|
||||
|
|
@ -86,6 +87,15 @@ func (c *Client) disconnect(cs *ClientSession) {
|
|||
})
|
||||
}
|
||||
|
||||
// TODO: Consider exporting this type and its field.
|
||||
type unsupportedProtocolVersionError struct {
|
||||
version string
|
||||
}
|
||||
|
||||
func (e unsupportedProtocolVersionError) Error() string {
|
||||
return fmt.Sprintf("unsupported protocol version: %q", e.version)
|
||||
}
|
||||
|
||||
// Connect begins an MCP session by connecting to a server over the given
|
||||
// transport, and initializing the session.
|
||||
//
|
||||
|
|
@ -106,19 +116,22 @@ func (c *Client) Connect(ctx context.Context, t Transport) (cs *ClientSession, e
|
|||
}
|
||||
|
||||
params := &InitializeParams{
|
||||
ProtocolVersion: latestProtocolVersion,
|
||||
ClientInfo: &implementation{Name: c.name, Version: c.version},
|
||||
Capabilities: caps,
|
||||
ProtocolVersion: "2025-03-26",
|
||||
}
|
||||
// TODO(rfindley): handle protocol negotiation gracefully. If the server
|
||||
// responds with 2024-11-05, surface that failure to the caller of connect,
|
||||
// so that they can choose a different transport.
|
||||
res, err := handleSend[*InitializeResult](ctx, cs, methodInitialize, params)
|
||||
if err != nil {
|
||||
_ = cs.Close()
|
||||
return nil, err
|
||||
}
|
||||
if !slices.Contains(supportedProtocolVersions, res.ProtocolVersion) {
|
||||
return nil, unsupportedProtocolVersionError{res.ProtocolVersion}
|
||||
}
|
||||
cs.initializeResult = res
|
||||
if hc, ok := cs.mcpConn.(httpConnection); ok {
|
||||
hc.setProtocolVersion(res.ProtocolVersion)
|
||||
}
|
||||
if err := handleNotify(ctx, cs, notificationInitialized, &InitializedParams{}); err != nil {
|
||||
_ = cs.Close()
|
||||
return nil, err
|
||||
|
|
|
|||
Loading…
Reference in a new issue