Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion tool/mcp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ func (c *clientImpl) connect(ctx context.Context) (*sdkmcp.ClientSession, *sdkmc
return nil, nil, fmt.Errorf("failed to create transport: %w", err)
}

session, err := mcpClient.Connect(ctx, transport, nil)
session, err := c.connectSession(ctx, mcpClient, transport)
if err != nil {
return nil, nil, fmt.Errorf("failed to connect to MCP server: %w", err)
}
Expand Down
71 changes: 71 additions & 0 deletions tool/mcp/discover_session_mismatch.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2026 Redpanda Data, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package mcp

import (
"context"
"fmt"
"strings"

sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
)

// legacyProtocolVersion is the newest MCP revision that opens a session with
// initialize instead of server/discover. Revision 2026-07-28 replaced the
// handshake with the stateless server/discover request (SEP-2575).
const legacyProtocolVersion = "2025-11-25"

// connectSession opens an MCP session, and retries with initialize only when
// the server/discover handshake leaves the client holding two session IDs.
//
// go-sdk v1.8.0 keeps the Mcp-Session-Id of every response that it accepts,
// the rejection of server/discover included. A server that rejects discover
// with a session ID of its own, then answers the initialize fallback with
// another one, makes the client fail with "mismatching session IDs". The
// retry asks for the newest revision that does not send server/discover, so
// only one session ID ever exists.
//
// REMOVE THIS FILE, and its test, after go.mod carries go-sdk v1.9.0 or newer,
// which includes https://github.com/modelcontextprotocol/go-sdk/pull/1523.
// Until then the retry is harmless: it only runs on that error.
func (c *clientImpl) connectSession(ctx context.Context, mcpClient *sdkmcp.Client, transport sdkmcp.Transport) (*sdkmcp.ClientSession, error) {
session, err := mcpClient.Connect(ctx, transport, nil)
// go-sdk builds this error with fmt.Errorf and exports no sentinel, so match its text.
if err == nil || !strings.Contains(err.Error(), "mismatching session IDs") {
return session, err
}

// A transport is spent after a failed Connect, so the retry needs its own.
retryTransport, transportErr := c.transportFactory()
if transportErr != nil {
return nil, fmt.Errorf("failed to create transport for the initialize-only retry: %w (after %w)", transportErr, err)
}

session, retryErr := mcpClient.Connect(ctx, retryTransport, &sdkmcp.ClientSessionOptions{
// This is the fix. Below 2026-07-28 go-sdk sends no server/discover, so
// the stray session ID never arrives and initialize gives the only one.
ProtocolVersion: legacyProtocolVersion,
})
if retryErr != nil {
return nil, fmt.Errorf("%w (after retrying with initialize only: %w)", err, retryErr)
}

c.logger.Warn("MCP server gave mismatching session IDs for server/discover, connected with initialize only",
"server_id", c.serverID,
"err", err,
)

return session, nil
}
193 changes: 193 additions & 0 deletions tool/mcp/discover_session_mismatch_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
// Copyright 2026 Redpanda Data, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package mcp

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"

sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// discoverRejectSessionID is the session ID that the stand-in server puts on
// its server/discover rejection. It only has to differ from the session ID the
// real handler mints for initialize, which is random.
const discoverRejectSessionID = "session-from-the-discover-rejection"

// newDiscoverRejectingServer starts an MCP server over streamable HTTP that
// rejects server/discover the way some servers do: HTTP 200, a JSON-RPC
// error, and a Mcp-Session-Id header. Every other request goes
// to a real MCP handler, which mints its own session ID on initialize.
//
// The two session IDs are what the client trips over, so the test needs a
// server that answers discover and initialize with different ones. A plain
// HTTP 400 rejection, which is what the MCP Python SDK sends on its own, does
// not reproduce it: the client drops the response before it reads the header.
func newDiscoverRejectingServer(t *testing.T) *discoverRejectingServer {
t.Helper()

rec := &discoverRejectingServer{}

server := sdkmcp.NewServer(&sdkmcp.Implementation{
Name: "discover-rejecting-server",
Version: "v1.0.0",
}, nil)
sdkmcp.AddTool(server, &sdkmcp.Tool{
Name: "ping",
Description: "Returns pong.",
}, func(_ context.Context, _ *sdkmcp.CallToolRequest, _ struct{}) (*sdkmcp.CallToolResult, any, error) {
return &sdkmcp.CallToolResult{
Content: []sdkmcp.Content{&sdkmcp.TextContent{Text: "pong"}},
}, nil, nil
})

handler := sdkmcp.NewStreamableHTTPHandler(func(*http.Request) *sdkmcp.Server {
return server
}, nil)

httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)

return
}

var envelope struct {
Method string `json:"method"`
ID json.RawMessage `json:"id"`
}
_ = json.Unmarshal(body, &envelope)
rec.record(envelope.Method, r.Header.Get("Mcp-Session-Id"))

if envelope.Method == "server/discover" {
reject := fmt.Sprintf(
`{"jsonrpc":"2.0","id":%s,"error":{"code":-32600,"message":"Bad Request: Missing session ID"}}`,
envelope.ID,
)

w.Header().Set("Content-Type", "application/json")
w.Header().Set("Mcp-Session-Id", discoverRejectSessionID)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(reject))

return
}

if envelope.Method == "initialize" {
// A gateway answers initialize with a session of its own, whatever
// session ID the client carries over from the discover rejection.
// The real handler would answer a stale session ID with HTTP 404
// instead, which is a different failure.
r.Header.Del("Mcp-Session-Id")
}

r.Body = io.NopCloser(bytes.NewReader(body))
handler.ServeHTTP(w, r)
}))
t.Cleanup(httpServer.Close)
rec.url = httpServer.URL

return rec
}

// discoverRejectingServer is the stand-in server from newDiscoverRejectingServer.
// It records each request that it gets, so the test can show which handshake
// opened the session.
type discoverRejectingServer struct {
url string

mu sync.Mutex
requests []recordedRequest
}

// recordedRequest is one JSON-RPC request that the stand-in server got, with
// the Mcp-Session-Id that the client sent on it.
type recordedRequest struct {
method string
sessionID string
}

func (s *discoverRejectingServer) record(method, sessionID string) {
s.mu.Lock()
defer s.mu.Unlock()

s.requests = append(s.requests, recordedRequest{method: method, sessionID: sessionID})
}

// requestsFor returns the recorded requests for method, in order.
func (s *discoverRejectingServer) requestsFor(method string) []recordedRequest {
s.mu.Lock()
defer s.mu.Unlock()

var out []recordedRequest

for _, r := range s.requests {
if r.method == method {
out = append(out, r)
}
}

return out
}

// TestIntegrationConnectToDiscoverRejectingServer checks that the client
// reaches a usable session against a server that rejects server/discover with
// a session ID of its own.
func TestIntegrationConnectToDiscoverRejectingServer(t *testing.T) {
t.Parallel()

if testing.Short() {
t.Skip("skipping integration test in short mode")
}

server := newDiscoverRejectingServer(t)

client, err := NewClient("discover-rejecting-server", NewStreamableTransport(server.url))
require.NoError(t, err)

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)

require.NoError(t, client.Start(ctx))
t.Cleanup(func() {
assert.NoError(t, client.Close())
})

tools, err := client.ListTools(ctx)
require.NoError(t, err)
require.Len(t, tools, 1)
assert.Equal(t, "discover-rejecting-server__ping", tools[0].Name)

// The cause, made visible. On go-sdk v1.8.0 the first initialize carries the
// session ID of the discover rejection and fails. The retry sends no
// server/discover, so the initialize that opens the working session carries
// no session ID. Both checks also hold on go-sdk v1.9.0, where no retry runs.
assert.Len(t, server.requestsFor("server/discover"), 1, "the retry must not send server/discover again")
initializes := server.requestsFor("initialize")
require.NotEmpty(t, initializes)
assert.Empty(t, initializes[len(initializes)-1].sessionID,
"the initialize that opened the session must not carry the discover rejection's session ID")
}
Loading