From d837b0905278695147f8642a88843c6beb9199ed Mon Sep 17 00:00:00 2001 From: Wynne Pirini Date: Mon, 26 Oct 2026 13:54:36 +1300 Subject: [PATCH] fix(mcp): serve server/discover statelessly so 2026-07-28 is advertised (#170) ChatGPT connects via OAuth, then action discovery fails because /mcp answers server/discover with supportedVersions ending at 2025-11-25. The client asks for 2026-07-28 and does not fall back, so it stops. Cause is transport mode, not the SDK. go-sdk v1.8.0 knows 2026-07-28 (SEP-2575), but StreamableServerTransport.SupportsProtocolVersion only serves versions >= 2026-07-28 when the transport is stateless. Calnode passed nil options, i.e. stateful, so filterSupportedVersions dropped the modern version. Clients that negotiate down (MCP Inspector, MiniMax, plain SDK clients) were never affected. Calnode holds no MCP session state: every request is authenticated independently by RequireBearerToken + MCPCallerMiddleware, and no tool sends server->client requests or notifications. So stateless is a safe fit. Trade-off: GET and DELETE /mcp now return 405, as there is no session to stream or terminate. Verified live: the reporter's own diagnostic curl now returns supportedVersions [2026-07-28, 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05]. Tests cover discovery advertising 2026-07-28 (and still listing the older versions), GET returning 405, and a full Streamable HTTP client session doing initialize + tools/list + tools/call over stateless. --- internal/server/mcp_discovery_test.go | 162 ++++++++++++++++++++++++++ internal/server/server.go | 24 +++- 2 files changed, 185 insertions(+), 1 deletion(-) create mode 100644 internal/server/mcp_discovery_test.go diff --git a/internal/server/mcp_discovery_test.go b/internal/server/mcp_discovery_test.go new file mode 100644 index 00000000..0e930784 --- /dev/null +++ b/internal/server/mcp_discovery_test.go @@ -0,0 +1,162 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// discoverReq mirrors what a SEP-2575-aware client sends: the version and method +// also travel as headers so the transport can route the request before parsing. +func discoverReq(t *testing.T, protocolVersion string) *http.Request { + t.Helper() + body := `{ + "jsonrpc": "2.0", + "id": "discovery-diagnostic", + "method": "server/discover", + "params": { + "_meta": { + "io.modelcontextprotocol/protocolVersion": "` + protocolVersion + `", + "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"}, + "io.modelcontextprotocol/clientCapabilities": {} + } + } + }` + req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json, text/event-stream") + req.Header.Set("Mcp-Protocol-Version", protocolVersion) + req.Header.Set("Mcp-Method", "server/discover") + return req +} + +// discoverResult pulls the JSON-RPC payload out of a Streamable HTTP response, +// which may arrive as SSE ("data: {...}") or as plain JSON. +func discoverResult(t *testing.T, body string) map[string]any { + t.Helper() + payload := body + for _, line := range strings.Split(body, "\n") { + if after, ok := strings.CutPrefix(strings.TrimSpace(line), "data:"); ok { + payload = strings.TrimSpace(after) + break + } + } + var out map[string]any + if err := json.Unmarshal([]byte(payload), &out); err != nil { + t.Fatalf("decode discovery response: %v (body: %q)", err, body) + } + return out +} + +// The transport must be stateless so the go-sdk advertises 2026-07-28. On a +// stateful transport it filters the modern version out and ChatGPT's connector +// discovery fails without ever falling back (#170). +func TestMCPDiscoverAdvertisesProtocol20260728(t *testing.T) { + srv := mcp.NewServer(&mcp.Implementation{Name: "calnode", Version: "test"}, nil) + h := newMCPStreamableHandler(srv) + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, discoverReq(t, "2026-07-28")) + + if rec.Code != http.StatusOK { + t.Fatalf("status = %d; want 200 (body: %s)", rec.Code, rec.Body.String()) + } + + res := discoverResult(t, rec.Body.String()) + result, ok := res["result"].(map[string]any) + if !ok { + t.Fatalf("no result in discovery response: %s", rec.Body.String()) + } + versions, ok := result["supportedVersions"].([]any) + if !ok { + t.Fatalf("no supportedVersions in discovery response: %s", rec.Body.String()) + } + + var got []string + for _, v := range versions { + if s, ok := v.(string); ok { + got = append(got, s) + } + } + if !contains(got, "2026-07-28") { + t.Errorf("supportedVersions = %v; want it to include 2026-07-28", got) + } + // The older versions must remain: clients that cannot do 2026-07-28 negotiate + // down to these, and that path has to keep working. + for _, want := range []string{"2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"} { + if !contains(got, want) { + t.Errorf("supportedVersions = %v; missing %s", got, want) + } + } +} + +// GET opens the standalone notification stream on a stateful transport. Stateless +// has no session to stream, so it must answer 405 rather than hang. +func TestMCPStatelessRejectsNotificationStream(t *testing.T) { + srv := mcp.NewServer(&mcp.Implementation{Name: "calnode", Version: "test"}, nil) + h := newMCPStreamableHandler(srv) + + req := httptest.NewRequest(http.MethodGet, "/mcp", nil) + req.Header.Set("Accept", "text/event-stream") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + if rec.Code != http.StatusMethodNotAllowed { + t.Errorf("GET /mcp status = %d; want 405 in stateless mode", rec.Code) + } +} + +func contains(haystack []string, needle string) bool { + for _, s := range haystack { + if s == needle { + return true + } + } + return false +} + +// Stateless must remain transparent to ordinary MCP clients: they connect, +// initialize (negotiating a version below 2026-07-28) and call tools over HTTP. +// This is the path MCP Inspector, MiniMax and other SDK clients take, and it has +// to keep working after #170's transport change. +func TestMCPStatelessServesNormalClientSession(t *testing.T) { + srv := mcp.NewServer(&mcp.Implementation{Name: "calnode", Version: "test"}, nil) + mcp.AddTool(srv, &mcp.Tool{Name: "ping", Description: "health check"}, + func(context.Context, *mcp.CallToolRequest, struct{}) (*mcp.CallToolResult, struct{}, error) { + return &mcp.CallToolResult{ + Content: []mcp.Content{&mcp.TextContent{Text: "pong"}}, + }, struct{}{}, nil + }) + + ts := httptest.NewServer(newMCPStreamableHandler(srv)) + defer ts.Close() + + ctx := context.Background() + client := mcp.NewClient(&mcp.Implementation{Name: "test-client", Version: "0"}, nil) + cs, err := client.Connect(ctx, &mcp.StreamableClientTransport{Endpoint: ts.URL}, nil) + if err != nil { + t.Fatalf("connect: %v", err) + } + t.Cleanup(func() { _ = cs.Close() }) + + tools, err := cs.ListTools(ctx, &mcp.ListToolsParams{}) + if err != nil { + t.Fatalf("ListTools: %v", err) + } + if len(tools.Tools) != 1 || tools.Tools[0].Name != "ping" { + t.Fatalf("tools = %+v; want the ping tool", tools.Tools) + } + + res, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "ping"}) + if err != nil { + t.Fatalf("CallTool: %v", err) + } + if res.IsError { + t.Fatalf("tool returned error: %+v", res.Content) + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 6c0c07ca..75d08cdb 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -36,6 +36,28 @@ import ( // uses it to back the HTTP server; the `calnode mcp` subcommand uses it to serve the // MCP server over stdio. The returned drain func blocks until the background worker // has finished its current poll cycle. +// newMCPStreamableHandler builds the Streamable HTTP transport for POST /mcp. +// +// Stateless is deliberate, not a default that slipped through. The go-sdk only +// advertises and serves protocol 2026-07-28 (SEP-2575's server/discover flow) on a +// stateless transport: StreamableServerTransport.SupportsProtocolVersion filters +// every version >= 2026-07-28 out of a stateful one, so /mcp answered discovery +// with a list ending at 2025-11-25. ChatGPT's connector flow asks for 2026-07-28 +// and does not fall back to an older version, so its action discovery failed +// (#170). Clients that negotiate down (MCP Inspector, MiniMax, plain SDK clients) +// were unaffected — which is why this went unnoticed. +// +// Calnode holds no MCP session state: each request is authenticated on its own by +// RequireBearerToken + MCPCallerMiddleware, and no tool sends server->client +// requests or notifications. The trade-off is that GET and DELETE /mcp answer 405, +// since there is no session to stream or terminate. +func newMCPStreamableHandler(srv *mcp.Server) http.Handler { + return mcp.NewStreamableHTTPHandler( + func(*http.Request) *mcp.Server { return srv }, + &mcp.StreamableHTTPOptions{Stateless: true}, + ) +} + func BuildHandler(ctx context.Context, cfg *config.Config, db *sql.DB, logger *slog.Logger) (*handler.Handler, func()) { h := handler.New(db, logger) h.SetBaseURL(cfg.BaseURL) @@ -300,7 +322,7 @@ func New(ctx context.Context, cfg *config.Config, db *sql.DB, logger *slog.Logge // an OAuth access token (the "Connect" flow) or a cno_ API key, both resolved by // verifyMCPBearer. A 401 advertises the OAuth discovery doc so clients can connect. mcpSrv := h.MCPServer() - mcpHTTP := mcp.NewStreamableHTTPHandler(func(*http.Request) *mcp.Server { return mcpSrv }, nil) + mcpHTTP := newMCPStreamableHandler(mcpSrv) mcpAuth := auth.RequireBearerToken(h.VerifyMCPBearer, &auth.RequireBearerTokenOptions{ ResourceMetadataURL: cfg.BaseURL + "/.well-known/oauth-protected-resource", })