From ff1241a4a5fed7cf2a602392153b90f3bb0117e5 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 15 Nov 2026 23:55:04 -0500 Subject: [PATCH] fix(mcp): carry session and protocol headers after initialization --- internal/mcpclient/client.go | 50 ++++++++++++++++-------- internal/mcpclient/session_test.go | 61 ++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+), 15 deletions(-) create mode 100644 internal/mcpclient/session_test.go diff --git a/internal/mcpclient/client.go b/internal/mcpclient/client.go index 5bc73a733..b06091ad8 100644 --- a/internal/mcpclient/client.go +++ b/internal/mcpclient/client.go @@ -16,12 +16,14 @@ import ( // Client is a minimal Streamable HTTP MCP client that sends JSON-RPC 2.0 // tool-call requests to an MCP gateway and parses the response. type Client struct { - url string - hdrs map[string]string - http *http.Client - mu sync.Mutex - nextID int64 - init bool + url string + hdrs map[string]string + http *http.Client + mu sync.Mutex + nextID int64 + init bool + sessionID string + protocolVersion string } func New(url string, headers map[string]string) *Client { @@ -138,6 +140,7 @@ func (c *Client) CallToolContext(ctx context.Context, name string, args map[stri httpReq.Header.Set(k, v) } + c.setSessionHeaders(httpReq) resp, err := c.http.Do(httpReq) if err != nil { return "", fmt.Errorf("mcp request %s: %w", name, err) @@ -235,6 +238,7 @@ func (c *Client) ListToolsContext(ctx context.Context) ([]Tool, error) { for k, v := range c.hdrs { httpReq.Header.Set(k, v) } + c.setSessionHeaders(httpReq) resp, err := c.http.Do(httpReq) if err != nil { return nil, fmt.Errorf("mcp tools/list: %w", err) @@ -319,24 +323,31 @@ func (c *Client) ensureInit(ctx context.Context) error { c.init = true return nil } - var rpcResp rpcResponse - if json.Unmarshal(raw, &rpcResp) == nil && rpcResp.Error != nil { - // Non-fatal: continue even if init fails. + if resp.StatusCode >= 200 && resp.StatusCode < 300 { + var rpcResp rpcResponse + if json.Unmarshal(raw, &rpcResp) == nil && rpcResp.Error == nil { + c.sessionID = resp.Header.Get("Mcp-Session-Id") + var initialized struct { + ProtocolVersion string `json:"protocolVersion"` + } + if json.Unmarshal(rpcResp.Result, &initialized) == nil { + c.protocolVersion = initialized.ProtocolVersion + } + } } c.nextID++ - notifReq := rpcRequest{ - JSONRPC: "2.0", - ID: 0, - Method: "notifications/initialized", - } - notifBody, _ := json.Marshal(notifReq) + notifBody, _ := json.Marshal(map[string]string{ + "jsonrpc": "2.0", + "method": "notifications/initialized", + }) notifHTTP, _ := http.NewRequestWithContext(ctx, "POST", c.url, bytes.NewReader(notifBody)) notifHTTP.Header.Set("Content-Type", "application/json") notifHTTP.Header.Set("Accept", "application/json, text/event-stream") for k, v := range c.hdrs { notifHTTP.Header.Set(k, v) } + c.setSessionHeaders(notifHTTP) notifResp, err := c.http.Do(notifHTTP) if err == nil { notifResp.Body.Close() @@ -348,6 +359,15 @@ func (c *Client) ensureInit(ctx context.Context) error { return nil } +func (c *Client) setSessionHeaders(req *http.Request) { + if c.sessionID != "" { + req.Header.Set("Mcp-Session-Id", c.sessionID) + } + if c.protocolVersion != "" { + req.Header.Set("MCP-Protocol-Version", c.protocolVersion) + } +} + func (c *Client) readResponse(resp *http.Response) ([]byte, error) { ct := resp.Header.Get("Content-Type") if strings.Contains(ct, "text/event-stream") { diff --git a/internal/mcpclient/session_test.go b/internal/mcpclient/session_test.go new file mode 100644 index 000000000..a2596ee72 --- /dev/null +++ b/internal/mcpclient/session_test.go @@ -0,0 +1,61 @@ +package mcpclient + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" +) + +func TestStatefulMCPInitialization(t *testing.T) { + var notified atomic.Bool + endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var request struct { + ID json.RawMessage `json:"id"` + Method string `json:"method"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + http.Error(w, "invalid fixture request", http.StatusBadRequest) + return + } + if request.Method == "initialize" { + w.Header().Set("Mcp-Session-Id", "synthetic-session") + writeJSON(w, fmt.Sprintf(`{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":"2025-03-26"}}`, request.ID)) + return + } + if r.Header.Get("Mcp-Session-Id") != "synthetic-session" || + r.Header.Get("MCP-Protocol-Version") != "2025-03-26" { + http.Error(w, "session or protocol header missing", http.StatusBadRequest) + return + } + if request.Method == "notifications/initialized" { + if len(request.ID) != 0 { + http.Error(w, "notification must omit id", http.StatusBadRequest) + return + } + notified.Store(true) + w.WriteHeader(http.StatusAccepted) + return + } + if !notified.Load() { + http.Error(w, "no initialized notification", http.StatusBadRequest) + return + } + if request.Method == "tools/list" { + writeJSON(w, fmt.Sprintf(`{"jsonrpc":"2.0","id":%s,"result":{"tools":[{"name":"fixture"}]}}`, request.ID)) + return + } + writeJSON(w, fmt.Sprintf(`{"jsonrpc":"2.0","id":%s,"result":{"content":[{"type":"text","text":"done"}]}}`, request.ID)) + })) + defer endpoint.Close() + client := New(endpoint.URL, nil) + tools, err := client.ListTools() + if err != nil || len(tools) != 1 || tools[0].Name != "fixture" { + t.Fatalf("stateful list failed: %v, %v", tools, err) + } + if text, err := client.CallTool("fixture", nil); err != nil || text != "done" { + t.Fatalf("stateful call failed: %q, %v", text, err) + } +}