Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(mcp): terminate Go Streamable HTTP sessions (#19151)

Lem0nTea200277ef6032086b
diff --git a/internal/utility/mcp_call.go b/internal/utility/mcp_call.go
index dcb85761dc..29479fcf9e 100644
--- a/internal/utility/mcp_call.go
+++ b/internal/utility/mcp_call.go
@@ -102,7 +102,7 @@ func CallTool(ctx context.Context, opts CallOptions) (*CallResult, error) {
// Empty ServerType is treated as streamable-http because
// that is the default per the spec. Servers explicitly
// declaring the legacy SSE transport get the legacy path.
- return callToolStreamableHTTP(connectCtx, opts.URL, headers, opts.HTTPClient, opts.ToolName, opts.Arguments)
+ return callToolStreamableHTTP(connectCtx, opts.URL, headers, opts.HTTPClient, opts.ToolName, opts.Arguments, opts.Timeout)
case TransportSSE:
return nil, errors.New("MCP tools/call on legacy SSE transport is not yet implemented in Go (Phase 3.7 deferred; use streamable-http)")
default:
@@ -112,15 +112,18 @@ func CallTool(ctx context.Context, opts CallOptions) (*CallResult, error) {
// callToolStreamableHTTP drives the streamable-HTTP session:
// initialize → notifications/initialized → tools/call. The
-// session is torn down at the end (the server is free to
-// garbage-collect the session id; future calls re-initialize).
-func callToolStreamableHTTP(ctx context.Context, endpoint string, headers map[string]string, client *http.Client, toolName string, args json.RawMessage) (*CallResult, error) {
+// session is explicitly terminated at the end; future calls
+// re-initialize.
+func callToolStreamableHTTP(ctx context.Context, endpoint string, headers map[string]string, client *http.Client, toolName string, args json.RawMessage, cleanupTimeout time.Duration) (*CallResult, error) {
sessionID, initRes, err := streamableSend(ctx, client, endpoint, "", headers, jsonRPCRequest{
JSONRPC: jsonRPCVersion,
ID: 0,
Method: "initialize",
Params: initializeParams(),
}, true)
+ if sessionID != "" {
+ defer terminateStreamableSessionBestEffort(ctx, client, endpoint, sessionID, headers, cleanupTimeout)
+ }
if err != nil {
return nil, err
}
diff --git a/internal/utility/mcp_call_test.go b/internal/utility/mcp_call_test.go
index 2b7c9f9a0a..968ced6e0e 100644
--- a/internal/utility/mcp_call_test.go
+++ b/internal/utility/mcp_call_test.go
@@ -17,12 +17,17 @@
package utility
import (
+ "context"
"encoding/json"
+ "errors"
"io"
"net/http"
"net/http/httptest"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
+ "time"
)
// TestParseCallResult_TextBlocksConcatenated: text content
@@ -106,15 +111,42 @@ func TestParseCallResult_Empty(t *testing.T) {
}
// TestCallTool_StreamableHTTP: drive the full session
-// (initialize → notifications/initialized → tools/call) against
+// (initialize → notifications/initialized → tools/call → DELETE) against
// a local httptest server. Verifies the request shape, the
-// session id propagation, and the response parsing.
+// rendered headers, session id propagation, request order, and
+// response parsing.
func TestCallTool_StreamableHTTP(t *testing.T) {
defer allowLoopbackForTests(t)()
+ var deleteCount int32
+ var mu sync.Mutex
+ var requestOrder []string
+ recordRequest := func(method string) {
+ mu.Lock()
+ defer mu.Unlock()
+ requestOrder = append(requestOrder, method)
+ }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Authorization"); got != "Bearer test-token" {
+ t.Errorf("Authorization=%q, want rendered header", got)
+ }
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&deleteCount, 1)
+ recordRequest(http.MethodDelete)
+ if got := r.Header.Get(sessionHeader); got != "test-session-42" {
+ t.Errorf("DELETE session header=%q, want test-session-42", got)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ if r.Method != http.MethodPost {
+ t.Errorf("request method=%s, want POST or DELETE", r.Method)
+ http.Error(w, "unexpected method", http.StatusMethodNotAllowed)
+ return
+ }
body, _ := io.ReadAll(r.Body)
var req jsonRPCRequest
_ = json.Unmarshal(body, &req)
+ recordRequest(req.Method)
w.Header().Set("Content-Type", "application/json")
// First call (initialize) returns a session id.
if req.Method == "initialize" {
@@ -122,6 +154,9 @@ func TestCallTool_StreamableHTTP(t *testing.T) {
_, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":0,"result":{"protocolVersion":"2025-03-26"}}`))
return
}
+ if got := r.Header.Get(sessionHeader); got != "test-session-42" {
+ t.Errorf("%s session header=%q, want test-session-42", req.Method, got)
+ }
// tools/call returns the canned result.
if req.Method == "tools/call" {
_, _ = w.Write([]byte(`{
@@ -140,8 +175,16 @@ func TestCallTool_StreamableHTTP(t *testing.T) {
ServerType: TransportStreamableHTTP,
ToolName: "echo",
Arguments: json.RawMessage(`{"msg":"hi"}`),
+ Headers: map[string]string{
+ "${header_name}": "Bearer ${token}",
+ sessionHeader: "stale-session",
+ },
+ Variables: map[string]string{
+ "header_name": "Authorization",
+ "token": "test-token",
+ },
HTTPClient: srv.Client(),
- Timeout: srv.Client().Timeout,
+ Timeout: 2 * time.Second,
})
if err != nil {
t.Fatalf("CallTool: %v", err)
@@ -152,6 +195,281 @@ func TestCallTool_StreamableHTTP(t *testing.T) {
if res.IsError {
t.Errorf("IsError should be false")
}
+ if got := atomic.LoadInt32(&deleteCount); got != 1 {
+ t.Errorf("DELETE count=%d, want 1", got)
+ }
+ mu.Lock()
+ gotOrder := strings.Join(requestOrder, ",")
+ mu.Unlock()
+ if want := "initialize,notifications/initialized,tools/call,DELETE"; gotOrder != want {
+ t.Errorf("request order=%q, want %q", gotOrder, want)
+ }
+}
+
+func TestCallTool_StreamableHTTPSessionTerminationStatusPreservesResult(t *testing.T) {
+ defer allowLoopbackForTests(t)()
+
+ for _, status := range []int{http.StatusMethodNotAllowed, http.StatusInternalServerError} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ var deleteCount int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&deleteCount, 1)
+ w.WriteHeader(status)
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ var req jsonRPCRequest
+ _ = json.Unmarshal(body, &req)
+ w.Header().Set("Content-Type", "application/json")
+ switch req.Method {
+ case "initialize":
+ w.Header().Set(sessionHeader, "test-session")
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":0,"result":{}}`))
+ case "tools/call":
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"kept"}]}}`))
+ default:
+ w.WriteHeader(http.StatusAccepted)
+ }
+ }))
+
+ res, err := CallTool(t.Context(), CallOptions{
+ URL: srv.URL,
+ ServerType: TransportStreamableHTTP,
+ ToolName: "echo",
+ Arguments: json.RawMessage(`{}`),
+ HTTPClient: srv.Client(),
+ Timeout: 2 * time.Second,
+ })
+ srv.Close()
+ if err != nil {
+ t.Fatalf("CallTool returned cleanup error: %v", err)
+ }
+ if res.Text != "kept" {
+ t.Errorf("Text=%q, want kept", res.Text)
+ }
+ if got := atomic.LoadInt32(&deleteCount); got != 1 {
+ t.Errorf("DELETE count=%d, want 1", got)
+ }
+ })
+ }
+}
+
+func TestCallTool_StreamableHTTPDeletesAfterMalformedInitializeResponse(t *testing.T) {
+ defer allowLoopbackForTests(t)()
+ var deleteCount int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&deleteCount, 1)
+ if got := r.Header.Get(sessionHeader); got != "test-session" {
+ t.Errorf("DELETE session header=%q, want test-session", got)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ w.Header().Set(sessionHeader, "test-session")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"jsonrpc":`))
+ }))
+ defer srv.Close()
+
+ _, err := CallTool(t.Context(), CallOptions{
+ URL: srv.URL,
+ ServerType: TransportStreamableHTTP,
+ ToolName: "echo",
+ Arguments: json.RawMessage(`{}`),
+ HTTPClient: srv.Client(),
+ Timeout: 2 * time.Second,
+ })
+ if err == nil || !strings.Contains(err.Error(), "parse MCP response") {
+ t.Fatalf("CallTool error=%v, want initialize response parse error", err)
+ }
+ if got := atomic.LoadInt32(&deleteCount); got != 1 {
+ t.Errorf("DELETE count=%d after malformed initialize response, want 1", got)
+ }
+}
+
+func TestCallTool_StreamableHTTPSessionTerminationDoesNotFollowRedirect(t *testing.T) {
+ defer allowLoopbackForTests(t)()
+
+ for _, status := range []int{http.StatusTemporaryRedirect, http.StatusPermanentRedirect} {
+ t.Run(http.StatusText(status), func(t *testing.T) {
+ var sourceDeleteCount int32
+ var targetDeleteCount int32
+ redirectTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&targetDeleteCount, 1)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer redirectTarget.Close()
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&sourceDeleteCount, 1)
+ w.Header().Set("Location", redirectTarget.URL)
+ w.WriteHeader(status)
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ var req jsonRPCRequest
+ _ = json.Unmarshal(body, &req)
+ w.Header().Set("Content-Type", "application/json")
+ switch req.Method {
+ case "initialize":
+ w.Header().Set(sessionHeader, "test-session")
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":0,"result":{}}`))
+ case "tools/call":
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"kept"}]}}`))
+ default:
+ w.WriteHeader(http.StatusAccepted)
+ }
+ }))
+ defer srv.Close()
+
+ res, err := CallTool(t.Context(), CallOptions{
+ URL: srv.URL,
+ ServerType: TransportStreamableHTTP,
+ ToolName: "echo",
+ Arguments: json.RawMessage(`{}`),
+ HTTPClient: srv.Client(),
+ Timeout: 2 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("CallTool returned cleanup error: %v", err)
+ }
+ if res.Text != "kept" {
+ t.Errorf("Text=%q, want kept", res.Text)
+ }
+ if got := atomic.LoadInt32(&sourceDeleteCount); got != 1 {
+ t.Errorf("source DELETE count=%d, want 1", got)
+ }
+ if got := atomic.LoadInt32(&targetDeleteCount); got != 0 {
+ t.Errorf("redirect target DELETE count=%d, want 0", got)
+ }
+ })
+ }
+}
+
+func TestCallTool_StreamableHTTPDeletesAfterCallerCancellation(t *testing.T) {
+ defer allowLoopbackForTests(t)()
+ var deleteCount int32
+ callStarted := make(chan struct{}, 1)
+ deleteStarted := make(chan struct{}, 1)
+ deleteStopped := make(chan struct{}, 1)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&deleteCount, 1)
+ deleteStarted <- struct{}{}
+ <-r.Context().Done()
+ deleteStopped <- struct{}{}
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ var req jsonRPCRequest
+ _ = json.Unmarshal(body, &req)
+ w.Header().Set("Content-Type", "application/json")
+ switch req.Method {
+ case "initialize":
+ w.Header().Set(sessionHeader, "test-session")
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":0,"result":{}}`))
+ case "tools/call":
+ callStarted <- struct{}{}
+ <-r.Context().Done()
+ default:
+ w.WriteHeader(http.StatusAccepted)
+ }
+ }))
+ defer srv.Close()
+
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ errCh := make(chan error, 1)
+ go func() {
+ _, err := CallTool(ctx, CallOptions{
+ URL: srv.URL,
+ ServerType: TransportStreamableHTTP,
+ ToolName: "echo",
+ Arguments: json.RawMessage(`{}`),
+ HTTPClient: srv.Client(),
+ Timeout: 250 * time.Millisecond,
+ })
+ errCh <- err
+ }()
+
+ select {
+ case <-callStarted:
+ cancel()
+ case <-time.After(2 * time.Second):
+ t.Fatal("tools/call did not start")
+ }
+ select {
+ case <-deleteStarted:
+ case <-time.After(2 * time.Second):
+ t.Fatal("session DELETE did not start after caller cancellation")
+ }
+ select {
+ case err := <-errCh:
+ if err == nil {
+ t.Fatal("CallTool error=nil after caller cancellation")
+ }
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("CallTool error=%v, want context.Canceled", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("CallTool did not return within the session cleanup budget")
+ }
+ select {
+ case <-deleteStopped:
+ case <-time.After(2 * time.Second):
+ t.Fatal("session DELETE context was not canceled at the cleanup deadline")
+ }
+ if got := atomic.LoadInt32(&deleteCount); got != 1 {
+ t.Errorf("DELETE count=%d after cancellation, want 1", got)
+ }
+}
+
+func TestCallTool_StreamableHTTPWithoutSessionIDSkipsDelete(t *testing.T) {
+ defer allowLoopbackForTests(t)()
+ var deleteCount int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&deleteCount, 1)
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
+ body, _ := io.ReadAll(r.Body)
+ var req jsonRPCRequest
+ _ = json.Unmarshal(body, &req)
+ w.Header().Set("Content-Type", "application/json")
+ switch req.Method {
+ case "initialize":
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":0,"result":{}}`))
+ case "tools/call":
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"ok"}]}}`))
+ default:
+ w.WriteHeader(http.StatusAccepted)
+ }
+ }))
+ defer srv.Close()
+
+ res, err := CallTool(t.Context(), CallOptions{
+ URL: srv.URL,
+ ServerType: TransportStreamableHTTP,
+ ToolName: "echo",
+ Arguments: json.RawMessage(`{}`),
+ HTTPClient: srv.Client(),
+ Timeout: 2 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("CallTool: %v", err)
+ }
+ if res.Text != "ok" {
+ t.Errorf("Text=%q, want ok", res.Text)
+ }
+ if got := atomic.LoadInt32(&deleteCount); got != 0 {
+ t.Errorf("DELETE count=%d without session id, want 0", got)
+ }
}
// TestCallTool_ServerError: a JSON-RPC error response surfaces
diff --git a/internal/utility/mcp_client.go b/internal/utility/mcp_client.go
index eb9429c17a..11ba976ada 100644
--- a/internal/utility/mcp_client.go
+++ b/internal/utility/mcp_client.go
@@ -112,7 +112,7 @@ func FetchTools(ctx context.Context, opts FetchOptions) ([]Tool, error) {
switch strings.ToLower(opts.ServerType) {
case TransportStreamableHTTP:
- return fetchToolsStreamableHTTP(connectCtx, opts.URL, headers, opts.HTTPClient)
+ return fetchToolsStreamableHTTP(connectCtx, opts.URL, headers, opts.HTTPClient, opts.Timeout)
case TransportSSE:
return fetchToolsSSE(connectCtx, opts.URL, headers, opts.HTTPClient)
default:
@@ -207,15 +207,25 @@ func initializeParams() map[string]interface{} {
// ---------- streamable-HTTP transport ----------
-const sessionHeader = "Mcp-Session-Id"
+const (
+ sessionHeader = "Mcp-Session-Id"
+ maxStreamableSessionCleanupTimeout = 5 * time.Second
+)
+
+func streamableSessionCleanupBudget(timeout time.Duration) time.Duration {
+ return min(timeout, maxStreamableSessionCleanupTimeout)
+}
-func fetchToolsStreamableHTTP(ctx context.Context, endpoint string, headers map[string]string, client *http.Client) ([]Tool, error) {
+func fetchToolsStreamableHTTP(ctx context.Context, endpoint string, headers map[string]string, client *http.Client, cleanupTimeout time.Duration) ([]Tool, error) {
sessionID, initRes, err := streamableSend(ctx, client, endpoint, "", headers, jsonRPCRequest{
JSONRPC: jsonRPCVersion,
ID: 0,
Method: "initialize",
Params: initializeParams(),
}, true)
+ if sessionID != "" {
+ defer terminateStreamableSessionBestEffort(ctx, client, endpoint, sessionID, headers, cleanupTimeout)
+ }
if err != nil {
return nil, err
}
@@ -244,6 +254,47 @@ func fetchToolsStreamableHTTP(ctx context.Context, endpoint string, headers map[
return parseToolsResult(listRes.Result)
}
+func terminateStreamableSessionBestEffort(ctx context.Context, client *http.Client, endpoint, sessionID string, headers map[string]string, timeout time.Duration) {
+ if sessionID == "" {
+ return
+ }
+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), streamableSessionCleanupBudget(timeout))
+ defer cancel()
+ cleanupClient := *client
+ cleanupClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
+ return http.ErrUseLastResponse
+ }
+
+ BestEffort("terminate MCP streamable HTTP session", func() error {
+ req, err := http.NewRequestWithContext(cleanupCtx, http.MethodDelete, endpoint, nil)
+ if err != nil {
+ return fmt.Errorf("build MCP session termination request: %w", err)
+ }
+ req.Header.Set("Accept", "application/json, text/event-stream")
+ for k, v := range headers {
+ req.Header.Set(k, v)
+ }
+ req.Header.Set(sessionHeader, sessionID)
+
+ resp, err := cleanupClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("send MCP session termination request: %w", err)
+ }
+ _, drainErr := io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))
+ closeErr := resp.Body.Close()
+ if drainErr != nil {
+ return fmt.Errorf("drain MCP session termination response: %w", drainErr)
+ }
+ if closeErr != nil {
+ return fmt.Errorf("close MCP session termination response: %w", closeErr)
+ }
+ if (resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices) || resp.StatusCode == http.StatusMethodNotAllowed {
+ return nil
+ }
+ return fmt.Errorf("MCP server returned HTTP %d for session termination", resp.StatusCode)
+ })
+}
+
// streamableSend POSTs a JSON-RPC payload to the streamable-HTTP endpoint.
// When expectResponse is false (notifications), the response body is not
// parsed. The session id returned by the initial initialize call is
@@ -298,17 +349,17 @@ func streamableSend(ctx context.Context, client *http.Client, endpoint, sessionI
var r *jsonRPCResponse
r, err = readJSONRPCFromSSE(resp.Body, payload.ID)
if err != nil {
- return "", nil, err
+ return sessionID, nil, err
}
return sessionID, r, nil
}
raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
if err != nil {
- return "", nil, fmt.Errorf("read MCP response: %w", err)
+ return sessionID, nil, fmt.Errorf("read MCP response: %w", err)
}
parsed, err := parseJSONRPC(raw, payload.ID)
if err != nil {
- return "", nil, err
+ return sessionID, nil, err
}
return sessionID, parsed, nil
}
diff --git a/internal/utility/mcp_client_test.go b/internal/utility/mcp_client_test.go
index d41ce471aa..8293998b4c 100644
--- a/internal/utility/mcp_client_test.go
+++ b/internal/utility/mcp_client_test.go
@@ -23,6 +23,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"sync/atomic"
"testing"
"time"
@@ -41,13 +42,51 @@ func allowLoopbackForTests(t *testing.T) func() {
return func() { LookupHost = orig }
}
+func TestStreamableSessionCleanupBudget(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ timeout time.Duration
+ want time.Duration
+ }{
+ {name: "shorter operation timeout", timeout: 100 * time.Millisecond, want: 100 * time.Millisecond},
+ {name: "cleanup timeout cap", timeout: 30 * time.Second, want: 5 * time.Second},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := streamableSessionCleanupBudget(tc.timeout); got != tc.want {
+ t.Errorf("streamableSessionCleanupBudget(%s)=%s, want %s", tc.timeout, got, tc.want)
+ }
+ })
+ }
+}
+
func TestFetchToolsStreamableHTTPJSON(t *testing.T) {
defer allowLoopbackForTests(t)()
- var initCount, listCount, notifyCount int32
+ var initCount, listCount, notifyCount, deleteCount int32
+ var mu sync.Mutex
+ var requestOrder []string
+ recordRequest := func(method string) {
+ mu.Lock()
+ defer mu.Unlock()
+ requestOrder = append(requestOrder, method)
+ }
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Authorization"); got != "Bearer fetch-token" {
+ t.Errorf("Authorization=%q, want rendered header", got)
+ }
+ if r.Method == http.MethodDelete {
+ atomic.AddInt32(&deleteCount, 1)
+ recordRequest(http.MethodDelete)
+ if got := r.Header.Get(sessionHeader); got != "test-session" {
+ t.Errorf("DELETE session header=%q, want test-session", got)
+ }
+ w.WriteHeader(http.StatusNoContent)
+ return
+ }
if r.Method != http.MethodPost {
- t.Errorf("expected POST, got %s", r.Method)
+ t.Errorf("request method=%s, want POST or DELETE", r.Method)
+ http.Error(w, "unexpected method", http.StatusMethodNotAllowed)
+ return
}
body, _ := io.ReadAll(r.Body)
var req map[string]interface{}
@@ -58,7 +97,14 @@ func TestFetchToolsStreamableHTTPJSON(t *testing.T) {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
- switch req["method"] {
+ method, _ := req["method"].(string)
+ recordRequest(method)
+ if method != "initialize" {
+ if got := r.Header.Get(sessionHeader); got != "test-session" {
+ t.Errorf("%s session header=%q, want test-session", method, got)
+ }
+ }
+ switch method {
case "initialize":
atomic.AddInt32(&initCount, 1)
w.Header().Set(sessionHeader, "test-session")
@@ -83,6 +129,14 @@ func TestFetchToolsStreamableHTTPJSON(t *testing.T) {
tools, err := FetchTools(t.Context(), FetchOptions{
URL: srv.URL,
ServerType: TransportStreamableHTTP,
+ Headers: map[string]string{
+ "${header_name}": "Bearer ${token}",
+ sessionHeader: "stale-session",
+ },
+ Variables: map[string]string{
+ "header_name": "Authorization",
+ "token": "fetch-token",
+ },
HTTPClient: srv.Client(),
Timeout: 2 * time.Second,
})
@@ -98,8 +152,14 @@ func TestFetchToolsStreamableHTTPJSON(t *testing.T) {
if tools[1].Name != "fetch" {
t.Errorf("tool 1 = %+v", tools[1])
}
- if atomic.LoadInt32(&initCount) != 1 || atomic.LoadInt32(&notifyCount) != 1 || atomic.LoadInt32(&listCount) != 1 {
- t.Errorf("expected 1 init / 1 notify / 1 list, got %d/%d/%d", initCount, notifyCount, listCount)
+ if atomic.LoadInt32(&initCount) != 1 || atomic.LoadInt32(&notifyCount) != 1 || atomic.LoadInt32(&listCount) != 1 || atomic.LoadInt32(&deleteCount) != 1 {
+ t.Errorf("expected 1 init / 1 notify / 1 list / 1 delete, got %d/%d/%d/%d", initCount, notifyCount, listCount, deleteCount)
+ }
+ mu.Lock()
+ gotOrder := strings.Join(requestOrder, ",")
+ mu.Unlock()
+ if want := "initialize,notifications/initialized,tools/list,DELETE"; gotOrder != want {
+ t.Errorf("request order=%q, want %q", gotOrder, want)
}
}