Skip to content
Open
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
50 changes: 35 additions & 15 deletions internal/mcpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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") {
Expand Down
61 changes: 61 additions & 0 deletions internal/mcpclient/session_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}