Debian Codegraph @

debian/go/src/github.com/modelcontextprotocol/go-sdk/mcp/streamable_client_test.go

raw symbols SCIP
1 // Copyright 2025 The Go MCP SDK Authors. All rights reserved.
2 // Use of this source code is governed by an MIT-style
3 // license that can be found in the LICENSE file.
4
5 package mcp
6
7 import (
8 "context"
9 "fmt"
10 "io"
11 "net/http"
12 "net/http/httptest"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "testing"
17 "time"
18
19 "github.com/google/go-cmp/cmp"
20 "github.com/modelcontextprotocol/go-sdk/auth"
21 "github.com/modelcontextprotocol/go-sdk/internal/jsonrpc2"
22 "github.com/modelcontextprotocol/go-sdk/jsonrpc"
23 "golang.org/x/oauth2"
24 )
25
26 type streamableRequestKey struct {
27 httpMethod string // http method
28 sessionID string // session ID header
29 jsonrpcMethod string // jsonrpc method, or "" for non-requests
30 lastEventID string // Last-Event-ID header
31 }
32
33 type header map[string]string
34
35 // TODO: replace body and status fields with responseFunc; add helpers to reduce duplication.
36 type streamableResponse struct {
37 header header // response headers
38 status int // or http.StatusOK; ignored if responseFunc is set
39 body string // or ""; ignored if responseFunc is set
40 responseFunc func(r *jsonrpc.Request) (string, int) // if set, overrides body and status
41 optional bool // if set, request need not be sent
42 wantProtocolVersion string // if "", unchecked
43 done chan struct{} // if set, receive from this channel before terminating the request
44 }
45
46 type fakeResponses map[streamableRequestKey]*streamableResponse
47
48 type fakeStreamableServer struct {
49 t *testing.T
50 responses fakeResponses
51
52 calledMu sync.Mutex
53 called map[streamableRequestKey]bool
54 }
55
56 func (s *fakeStreamableServer) missingRequests() []streamableRequestKey {
57 s.calledMu.Lock()
58 defer s.calledMu.Unlock()
59
60 var unused []streamableRequestKey
61 for k, resp := range s.responses {
62 if !s.called[k] && !resp.optional {
63 unused = append(unused, k)
64 }
65 }
66 return unused
67 }
68
69 func (s *fakeStreamableServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
70 key := streamableRequestKey{
71 httpMethod: req.Method,
72 sessionID: req.Header.Get(sessionIDHeader),
73 lastEventID: req.Header.Get(lastEventIDHeader),
74 }
75 var jsonrpcReq *jsonrpc.Request
76 if req.Method == http.MethodPost {
77 body, err := io.ReadAll(req.Body)
78 if err != nil {
79 s.t.Errorf("failed to read body: %v", err)
80 http.Error(w, "failed to read body", http.StatusInternalServerError)
81 return
82 }
83 msg, err := jsonrpc.DecodeMessage(body)
84 if err != nil {
85 s.t.Errorf("invalid body: %v", err)
86 http.Error(w, "invalid body", http.StatusInternalServerError)
87 return
88 }
89 if r, ok := msg.(*jsonrpc.Request); ok {
90 key.jsonrpcMethod = r.Method
91 jsonrpcReq = r
92 }
93 }
94
95 s.calledMu.Lock()
96 if s.called == nil {
97 s.called = make(map[streamableRequestKey]bool)
98 }
99 s.called[key] = true
100 s.calledMu.Unlock()
101
102 resp, ok := s.responses[key]
103 if !ok {
104 s.t.Errorf("missing response for %v", key)
105 http.Error(w, "no response", http.StatusInternalServerError)
106 return
107 }
108
109 // Determine body and status, potentially using responseFunc for dynamic responses.
110 body := resp.body
111 status := resp.status
112 if resp.responseFunc != nil {
113 body, status = resp.responseFunc(jsonrpcReq)
114 }
115 if status == 0 {
116 status = http.StatusOK
117 }
118
119 for k, v := range resp.header {
120 w.Header().Set(k, v)
121 }
122 rc := http.NewResponseController(w)
123 w.WriteHeader(status)
124 rc.Flush() // flush response headers
125
126 if v := req.Header.Get(protocolVersionHeader); v != resp.wantProtocolVersion && resp.wantProtocolVersion != "" {
127 s.t.Errorf("%v: bad protocol version header: got %q, want %q", key, v, resp.wantProtocolVersion)
128 }
129 w.Write([]byte(body))
130 rc.Flush() // flush response
131
132 if resp.done != nil {
133 <-resp.done
134 }
135 }
136
137 var (
138 initResult = &InitializeResult{
139 Capabilities: &ServerCapabilities{
140 Completions: &CompletionCapabilities{},
141 Logging: &LoggingCapabilities{},
142 Tools: &ToolCapabilities{ListChanged: true},
143 },
144 ProtocolVersion: latestProtocolVersion,
145 ServerInfo: &Implementation{Name: "testServer", Version: "v1.0.0"},
146 }
147 initResp = resp(1, initResult, nil)
148 )
149
150 func jsonBody(t *testing.T, msg jsonrpc2.Message) string {
151 data, err := jsonrpc2.EncodeMessage(msg)
152 if err != nil {
153 t.Fatalf("encoding failed: %v", err)
154 }
155 return string(data)
156 }
157
158 func TestStreamableClientTransportLifecycle(t *testing.T) {
159 ctx := context.Background()
160
161 // The lifecycle test verifies various behavior of the streamable client
162 // initialization:
163 // - check that it can handle application/json responses
164 // - check that it sends the negotiated protocol version
165 fake := &fakeStreamableServer{
166 t: t,
167 responses: fakeResponses{
168 {"POST", "", methodInitialize, ""}: {
169 header: header{
170 "Content-Type": "application/json",
171 sessionIDHeader: "123",
172 },
173 body: jsonBody(t, initResp),
174 },
175 {"POST", "123", notificationInitialized, ""}: {
176 status: http.StatusAccepted,
177 wantProtocolVersion: latestProtocolVersion,
178 },
179 {"GET", "123", "", ""}: {
180 header: header{
181 "Content-Type": "text/event-stream",
182 },
183 wantProtocolVersion: latestProtocolVersion,
184 },
185 {"DELETE", "123", "", ""}: {},
186 },
187 }
188
189 httpServer := httptest.NewServer(fake)
190 defer httpServer.Close()
191
192 transport := &StreamableClientTransport{Endpoint: httpServer.URL}
193 client := NewClient(testImpl, nil)
194 session, err := client.Connect(ctx, transport, nil)
195 if err != nil {
196 t.Fatalf("client.Connect() failed: %v", err)
197 }
198 if err := session.Close(); err != nil {
199 t.Errorf("closing session: %v", err)
200 }
201 if missing := fake.missingRequests(); len(missing) > 0 {
202 t.Errorf("did not receive expected requests: %v", missing)
203 }
204 if diff := cmp.Diff(initResult, session.state.InitializeResult); diff != "" {
205 t.Errorf("mismatch (-want, +got):\n%s", diff)
206 }
207 }
208
209 func TestStreamableClientRedundantDelete(t *testing.T) {
210 ctx := context.Background()
211
212 // The lifecycle test verifies various behavior of the streamable client
213 // initialization:
214 // - check that it can handle application/json responses
215 // - check that it sends the negotiated protocol version
216 fake := &fakeStreamableServer{
217 t: t,
218 responses: fakeResponses{
219 {"POST", "", methodInitialize, ""}: {
220 header: header{
221 "Content-Type": "application/json",
222 sessionIDHeader: "123",
223 },
224 body: jsonBody(t, initResp),
225 },
226 {"POST", "123", notificationInitialized, ""}: {
227 status: http.StatusAccepted,
228 wantProtocolVersion: latestProtocolVersion,
229 },
230 {"GET", "123", "", ""}: {
231 status: http.StatusMethodNotAllowed,
232 },
233 {"POST", "123", methodListTools, ""}: {
234 status: http.StatusNotFound,
235 },
236 },
237 }
238
239 httpServer := httptest.NewServer(fake)
240 defer httpServer.Close()
241
242 transport := &StreamableClientTransport{Endpoint: httpServer.URL}
243 client := NewClient(testImpl, nil)
244 session, err := client.Connect(ctx, transport, nil)
245 if err != nil {
246 t.Fatalf("client.Connect() failed: %v", err)
247 }
248 _, err = session.ListTools(ctx, nil)
249 if err == nil {
250 t.Errorf("Listing tools: got nil error, want non-nil")
251 }
252 _ = session.Wait() // must not hang
253 if missing := fake.missingRequests(); len(missing) > 0 {
254 t.Errorf("did not receive expected requests: %v", missing)
255 }
256 }
257
258 func TestStreamableClientGETHandling(t *testing.T) {
259 ctx := context.Background()
260
261 tests := []struct {
262 status int
263 wantErrorContaining string
264 contentType string
265 }{
266 {http.StatusOK, "", "text/event-stream"},
267 {http.StatusOK, "", "text/event-stream; charset=utf-8"},
268 {http.StatusMethodNotAllowed, "", "text/event-stream"},
269 //// The client error status code is not treated as an error in non-strict
270 //// mode.
271 {http.StatusNotFound, "", "text/event-stream"},
272 {http.StatusBadRequest, "", "text/event-stream"},
273 {http.StatusInternalServerError, "standalone SSE", "text/event-stream"},
274 {http.StatusOK, "", "text/html; charset=utf-8"},
275 }
276
277 for _, test := range tests {
278 t.Run(fmt.Sprintf("status=%d content_type=%q", test.status, test.contentType), func(t *testing.T) {
279 fake := &fakeStreamableServer{
280 t: t,
281 responses: fakeResponses{
282 {"POST", "", methodInitialize, ""}: {
283 header: header{
284 "Content-Type": "application/json; charset=utf-8", // should ignore the charset
285 sessionIDHeader: "123",
286 },
287 body: jsonBody(t, initResp),
288 },
289 {"POST", "123", notificationInitialized, ""}: {
290 status: http.StatusAccepted,
291 wantProtocolVersion: latestProtocolVersion,
292 },
293 {"GET", "123", "", ""}: {
294 header: header{
295 "Content-Type": test.contentType,
296 },
297 status: test.status,
298 wantProtocolVersion: latestProtocolVersion,
299 },
300 {"DELETE", "123", "", ""}: {optional: true},
301 },
302 }
303 httpServer := httptest.NewServer(fake)
304 defer httpServer.Close()
305
306 transport := &StreamableClientTransport{Endpoint: httpServer.URL}
307 client := NewClient(testImpl, nil)
308 session, err := client.Connect(ctx, transport, nil)
309 if err == nil {
310 defer session.Close()
311 }
312 if test.wantErrorContaining != "" {
313 if err == nil {
314 t.Fatalf("Connect succeeded unexpectedly, want error containing %q", test.wantErrorContaining)
315 }
316 if got := err.Error(); !strings.Contains(got, test.wantErrorContaining) {
317 t.Errorf("Connect error = %q, want containing %q", got, test.wantErrorContaining)
318 }
319 } else if err != nil {
320 t.Fatalf("Connect failed: %v", err)
321 }
322 })
323 }
324 }
325
326 func TestStreamableClientStrictness(t *testing.T) {
327 ctx := context.Background()
328
329 tests := []struct {
330 label string
331 strict bool
332 initializedStatus int
333 getStatus int
334 wantConnectError bool
335 }{
336 {"conformant server", true, http.StatusAccepted, http.StatusMethodNotAllowed, false},
337 {"strict initialized", true, http.StatusOK, http.StatusMethodNotAllowed, true},
338 {"unstrict initialized", false, http.StatusOK, http.StatusMethodNotAllowed, false},
339 {"strict GET", true, http.StatusAccepted, http.StatusNotFound, true},
340 // The client error status code is not treated as an error in non-strict
341 // mode.
342 {"unstrict GET on StatusNotFound", false, http.StatusOK, http.StatusNotFound, false},
343 {"unstrict GET on StatusBadRequest", false, http.StatusOK, http.StatusBadRequest, false},
344 {"GET on InternlServerError", false, http.StatusOK, http.StatusInternalServerError, true},
345 }
346 for _, test := range tests {
347 t.Run(test.label, func(t *testing.T) {
348 fake := &fakeStreamableServer{
349 t: t,
350 responses: fakeResponses{
351 {"POST", "", methodInitialize, ""}: {
352 header: header{
353 "Content-Type": "application/json",
354 sessionIDHeader: "123",
355 },
356 body: jsonBody(t, initResp),
357 },
358 {"POST", "123", notificationInitialized, ""}: {
359 status: test.initializedStatus,
360 wantProtocolVersion: latestProtocolVersion,
361 },
362 {"GET", "123", "", ""}: {
363 header: header{
364 "Content-Type": "text/event-stream",
365 },
366 status: test.getStatus,
367 wantProtocolVersion: latestProtocolVersion,
368 },
369 {"POST", "123", methodListTools, ""}: {
370 header: header{
371 "Content-Type": "application/json",
372 sessionIDHeader: "123",
373 },
374 body: jsonBody(t, resp(2, &ListToolsResult{Tools: []*Tool{}}, nil)),
375 optional: true,
376 },
377 {"DELETE", "123", "", ""}: {optional: true},
378 },
379 }
380 httpServer := httptest.NewServer(fake)
381 defer httpServer.Close()
382
383 transport := &StreamableClientTransport{Endpoint: httpServer.URL, strict: test.strict}
384 client := NewClient(testImpl, nil)
385 session, err := client.Connect(ctx, transport, nil)
386 if (err != nil) != test.wantConnectError {
387 t.Errorf("client.Connect() returned error %v; want error: %t", err, test.wantConnectError)
388 }
389 if err != nil {
390 return
391 }
392 _, err = session.ListTools(ctx, nil)
393 if err != nil {
394 t.Errorf("ListTools failed: %v", err)
395 }
396 if err := session.Close(); err != nil {
397 t.Errorf("closing session: %v", err)
398 }
399 })
400 }
401 }
402
403 func TestStreamableClientUnresumableRequest(t *testing.T) {
404 // This test verifies that the client fails fast when making a request that
405 // is unresumable, because it does not contain any events.
406 ctx := context.Background()
407 fake := &fakeStreamableServer{
408 t: t,
409 responses: fakeResponses{
410 {"POST", "", methodInitialize, ""}: {
411 header: header{
412 "Content-Type": "text/event-stream",
413 sessionIDHeader: "123",
414 },
415 body: "",
416 },
417 {"DELETE", "123", "", ""}: {optional: true},
418 },
419 }
420 httpServer := httptest.NewServer(fake)
421 defer httpServer.Close()
422
423 transport := &StreamableClientTransport{Endpoint: httpServer.URL}
424 client := NewClient(testImpl, nil)
425 cs, err := client.Connect(ctx, transport, nil)
426 if err == nil {
427 cs.Close()
428 t.Fatalf("Connect succeeded unexpectedly")
429 }
430 // This may be a bit of a change detector, but for now check that we're
431 // actually exercising the early failure codepath.
432 msg := "terminated without response"
433 if !strings.Contains(err.Error(), msg) {
434 t.Errorf("Connect: got error %v, want containing %q", err, msg)
435 }
436 }
437
438 func TestStreamableClientResumption_Cancelled(t *testing.T) {
439 // This test verifies that the resumed requests are closed when their context
440 // is cancelled (issue #662).
441
442 // This test (unfortunately) relies on timing, so may have false positives.
443 //
444 // Set the reconnect initial delay to some small(ish) value so that the test
445 // doesn't take too long. But this value must be large enough that we mostly
446 // avoid races in the tests below, where one test cases is intended to be in
447 // between the initial attempt and first reconnection.
448 //
449 // For easier tuning (and debugging), factor out the tick size.
450 //
451 // TODO(#680): experiment with instead using synctest.
452 const tick = 10 * time.Millisecond
453 defer func(delay int64) {
454 reconnectInitialDelay.Store(delay)
455 }(reconnectInitialDelay.Load())
456 reconnectInitialDelay.Store(int64(2 * tick))
457
458 // The setup: terminate a request stream and make the resumed request hang
459 // indefinitely. CallTool should still exit when its context is canceled.
460 //
461 // This should work whether we're handling the initial request, waiting to
462 // retry, or handling the retry.
463 //
464 // Furthermore, closing the client connection should not hang, because there
465 // should be no ongoing requests.
466
467 tests := []struct {
468 label string
469 cancelAfter time.Duration
470 }{
471 {"in process", 1 * tick}, // cancel while the request is being handled
472 // initial request terminates at 2 ticks (see below)
473 {"awaiting retry", 3 * tick}, // cancel in-between first and second attempt
474 // retry starts at 4 ticks (=2+2)
475 {"in retry", 5 * tick}, // cancel while second attempt is hanging
476 }
477
478 for _, test := range tests {
479 t.Run(test.label, func(t *testing.T) {
480 ctx := context.Background()
481
482 // done will be closed when the test exits: used to simulate requests that
483 // hang indefinitely.
484 initialRequestDone := make(chan struct{}) // closed below
485 allDone := make(chan struct{})
486
487 fake := &fakeStreamableServer{
488 t: t,
489 responses: fakeResponses{
490 {"POST", "", methodInitialize, ""}: {
491 header: header{
492 "Content-Type": "application/json",
493 sessionIDHeader: "123",
494 },
495 body: jsonBody(t, initResp),
496 },
497 {"POST", "123", notificationInitialized, ""}: {
498 status: http.StatusAccepted,
499 wantProtocolVersion: latestProtocolVersion,
500 },
501 {"GET", "123", "", ""}: {
502 header: header{
503 "Content-Type": "text/event-stream",
504 },
505 status: http.StatusMethodNotAllowed, // don't allow the standalone stream
506 },
507 {"POST", "123", methodCallTool, ""}: {
508 header: header{
509 "Content-Type": "text/event-stream",
510 },
511 status: http.StatusOK,
512 body: `id: 1
513 data: { "jsonrpc": "2.0", "method": "notifications/message", "params": { "level": "error", "data": "bad" } }
514
515 `,
516 done: initialRequestDone,
517 },
518 {"POST", "123", methodListTools, ""}: {
519 header: header{
520 "Content-Type": "application/json",
521 sessionIDHeader: "123",
522 },
523 body: jsonBody(t, resp(3, &ListToolsResult{Tools: []*Tool{}}, nil)),
524 },
525 {"GET", "123", "", "1"}: {
526 header: header{
527 "Content-Type": "text/event-stream",
528 },
529 status: http.StatusOK,
530 done: allDone, // hang indefinitely
531 },
532 {"POST", "123", notificationCancelled, ""}: {status: http.StatusAccepted},
533 {"DELETE", "123", "", ""}: {optional: true},
534 },
535 }
536 httpServer := httptest.NewServer(fake)
537 defer httpServer.Close()
538 defer close(allDone) // must be deferred *after* httpServer.Close, to avoid deadlock
539
540 transport := &StreamableClientTransport{Endpoint: httpServer.URL}
541 client := NewClient(testImpl, nil)
542 cs, err := client.Connect(ctx, transport, nil)
543 if err != nil {
544 t.Fatal(err)
545 }
546 defer cs.Close() // ensure the session is closed, though we're also closing below
547
548 // start the timer on the initial request
549 go func() {
550 <-time.After(2 * tick)
551 close(initialRequestDone)
552 }()
553
554 // start the timer on the call cancellation
555 timeoutCtx, cancel := context.WithTimeout(ctx, test.cancelAfter)
556 defer cancel()
557
558 go func() {
559 <-timeoutCtx.Done()
560 }()
561
562 if _, err := cs.CallTool(timeoutCtx, &CallToolParams{
563 Name: "tool",
564 }); err == nil {
565 t.Errorf("CallTool succeeded unexpectedly")
566 }
567
568 // ...but cancellation should not break the session.
569 // Check that an arbitrary request succeeds.
570 if _, err := cs.ListTools(ctx, nil); err != nil {
571 t.Errorf("ListTools failed after cancellation")
572 }
573 })
574 }
575 }
576
577 // TestStreamableClientTransientErrors verifies that transient errors (timeouts,
578 // 5xx HTTP status codes) do not permanently break the client connection.
579 // This tests the fix for issue #683.
580 func TestStreamableClientTransientErrors(t *testing.T) {
581 ctx := context.Background()
582
583 tests := []struct {
584 transientStatus int // HTTP status to return for the transient call
585 wantCallError bool // whether the transient call should error
586 wantSessionBroken bool // whether the session should be broken after
587 wantErrorContains string // substring expected in error message
588 }{
589 {
590 transientStatus: http.StatusServiceUnavailable,
591 wantCallError: true,
592 wantSessionBroken: false,
593 wantErrorContains: "Service Unavailable",
594 },
595 {
596 transientStatus: http.StatusBadGateway,
597 wantCallError: true,
598 wantSessionBroken: false,
599 wantErrorContains: "Bad Gateway",
600 },
601 {
602 transientStatus: http.StatusGatewayTimeout,
603 wantCallError: true,
604 wantSessionBroken: false,
605 wantErrorContains: "Gateway Timeout",
606 },
607 {
608 transientStatus: http.StatusTooManyRequests,
609 wantCallError: true,
610 wantSessionBroken: false,
611 wantErrorContains: "Too Many Requests",
612 },
613 {
614 transientStatus: http.StatusUnauthorized,
615 wantCallError: true,
616 wantSessionBroken: true,
617 wantErrorContains: "Unauthorized",
618 },
619 {
620 transientStatus: http.StatusNotFound,
621 wantCallError: true,
622 wantSessionBroken: true,
623 wantErrorContains: "not found", // NotFound has special handling
624 },
625 }
626
627 for _, test := range tests {
628 t.Run(http.StatusText(test.transientStatus), func(t *testing.T) {
629 var returnedError atomic.Bool
630 fake := &fakeStreamableServer{
631 t: t,
632 responses: fakeResponses{
633 {"POST", "", methodInitialize, ""}: {
634 header: header{
635 "Content-Type": "application/json",
636 sessionIDHeader: "123",
637 },
638 body: jsonBody(t, initResp),
639 },
640 {"POST", "123", notificationInitialized, ""}: {
641 status: http.StatusAccepted,
642 wantProtocolVersion: latestProtocolVersion,
643 },
644 {"GET", "123", "", ""}: {
645 status: http.StatusMethodNotAllowed,
646 },
647 {"POST", "123", methodListTools, ""}: {
648 header: header{
649 "Content-Type": "application/json",
650 sessionIDHeader: "123",
651 },
652 responseFunc: func(r *jsonrpc.Request) (string, int) {
653 // First call returns transient error, subsequent calls succeed.
654 if !returnedError.Swap(true) && test.transientStatus != 0 {
655 return "", test.transientStatus
656 }
657 return jsonBody(t, resp(r.ID.Raw().(int64), &ListToolsResult{Tools: []*Tool{}}, nil)), 0
658 },
659 optional: true,
660 },
661 {"DELETE", "123", "", ""}: {optional: true},
662 },
663 }
664
665 httpServer := httptest.NewServer(fake)
666 defer httpServer.Close()
667
668 transport := &StreamableClientTransport{Endpoint: httpServer.URL}
669 client := NewClient(testImpl, nil)
670 session, err := client.Connect(ctx, transport, nil)
671 if err != nil {
672 t.Fatalf("Connect failed: %v", err)
673 }
674 defer session.Close()
675
676 // First call: should trigger transient error.
677 _, err = session.ListTools(ctx, nil)
678 if test.wantCallError {
679 if err == nil {
680 t.Error("ListTools succeeded unexpectedly, want error")
681 } else if test.wantErrorContains != "" && !strings.Contains(err.Error(), test.wantErrorContains) {
682 t.Errorf("ListTools error = %q, want containing %q", err.Error(), test.wantErrorContains)
683 }
684 } else if err != nil {
685 t.Errorf("ListTools failed unexpectedly: %v", err)
686 }
687
688 // Second call: verifies whether the session is still usable.
689 _, err = session.ListTools(ctx, nil)
690 if test.wantSessionBroken {
691 if err == nil {
692 t.Error("second ListTools succeeded unexpectedly, want session broken")
693 }
694 } else {
695 if err != nil {
696 t.Errorf("second ListTools failed unexpectedly: %v (session should survive transient errors)", err)
697 }
698 }
699 })
700 }
701 }
702
703 // TestStreamableClientRetryWithoutProgress verifies that the client fails after
704 // exceeding the retry limit when no progress is made (Last-Event-ID does not advance).
705 // This tests the fix for issue #679.
706 func TestStreamableClientRetryWithoutProgress(t *testing.T) {
707 // Speed up reconnection delays for testing.
708 const tick = 10 * time.Millisecond
709 defer func(delay int64) {
710 reconnectInitialDelay.Store(delay)
711 }(reconnectInitialDelay.Load())
712 reconnectInitialDelay.Store(int64(tick))
713
714 // Use the fakeStreamableServer pattern like other tests to avoid race conditions.
715 ctx := context.Background()
716 const maxRetries = 2
717 var retryCount atomic.Int32
718
719 fake := &fakeStreamableServer{
720 t: t,
721 responses: fakeResponses{
722 {"POST", "", methodInitialize, ""}: {
723 header: header{
724 "Content-Type": "application/json",
725 sessionIDHeader: "test-session",
726 },
727 body: jsonBody(t, initResp),
728 },
729 {"POST", "test-session", notificationInitialized, ""}: {
730 status: http.StatusAccepted,
731 wantProtocolVersion: latestProtocolVersion,
732 },
733 {"GET", "test-session", "", ""}: {
734 // Disable standalone SSE stream to simplify the test.
735 status: http.StatusMethodNotAllowed,
736 },
737 {"POST", "test-session", methodCallTool, ""}: {
738 header: header{
739 "Content-Type": "text/event-stream",
740 },
741 // Return SSE stream with fixed event ID.
742 body: `id: fixed_1
743 data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"test"}}
744
745 `,
746 },
747 // Resumption attempts with the same event ID (no progress).
748 {"GET", "test-session", "", "fixed_1"}: {
749 header: header{
750 "Content-Type": "text/event-stream",
751 },
752 responseFunc: func(r *jsonrpc.Request) (string, int) {
753 retryCount.Add(1)
754 // Return the same event ID - no progress.
755 return `id: fixed_1
756 data: {"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"retry"}}
757
758 `, http.StatusOK
759 },
760 },
761 {"DELETE", "test-session", "", ""}: {optional: true},
762 },
763 }
764
765 httpServer := httptest.NewServer(fake)
766 defer httpServer.Close()
767
768 transport := &StreamableClientTransport{
769 Endpoint: httpServer.URL,
770 MaxRetries: maxRetries,
771 }
772 client := NewClient(testImpl, nil)
773 session, err := client.Connect(ctx, transport, nil)
774 if err != nil {
775 t.Fatalf("Connect failed: %v", err)
776 }
777 defer session.Close()
778
779 // Make a call that will trigger reconnections without progress.
780 _, err = session.CallTool(ctx, &CallToolParams{Name: "test"})
781 if err == nil {
782 t.Fatal("CallTool succeeded unexpectedly, want error due to exceeded retries")
783 }
784
785 // Check that the error mentions exceeding retries without progress.
786 wantErr := "exceeded"
787 if !strings.Contains(err.Error(), wantErr) {
788 t.Errorf("CallTool error = %q, want containing %q", err.Error(), wantErr)
789 }
790
791 // Verify that we actually retried the expected number of times.
792 // We expect maxRetries+1 attempts because we increment before checking the limit.
793 if got := retryCount.Load(); got != int32(maxRetries+1) {
794 t.Errorf("retry count = %d, want exactly %d", got, maxRetries+1)
795 }
796 }
797
798 func TestStreamableClientDisableStandaloneSSE(t *testing.T) {
799 ctx := context.Background()
800
801 tests := []struct {
802 name string
803 disableStandaloneSSE bool
804 expectGETRequest bool
805 }{
806 {
807 name: "default behavior (standalone SSE enabled)",
808 disableStandaloneSSE: false,
809 expectGETRequest: true,
810 },
811 {
812 name: "standalone SSE disabled",
813 disableStandaloneSSE: true,
814 expectGETRequest: false,
815 },
816 }
817
818 for _, test := range tests {
819 t.Run(test.name, func(t *testing.T) {
820 getRequestKey := streamableRequestKey{"GET", "123", "", ""}
821
822 fake := &fakeStreamableServer{
823 t: t,
824 responses: fakeResponses{
825 {"POST", "", methodInitialize, ""}: {
826 header: header{
827 "Content-Type": "application/json",
828 sessionIDHeader: "123",
829 },
830 body: jsonBody(t, initResp),
831 },
832 {"POST", "123", notificationInitialized, ""}: {
833 status: http.StatusAccepted,
834 wantProtocolVersion: latestProtocolVersion,
835 },
836 getRequestKey: {
837 header: header{
838 "Content-Type": "text/event-stream",
839 },
840 wantProtocolVersion: latestProtocolVersion,
841 optional: !test.expectGETRequest,
842 },
843 {"DELETE", "123", "", ""}: {
844 optional: true,
845 },
846 },
847 }
848
849 httpServer := httptest.NewServer(fake)
850 defer httpServer.Close()
851
852 transport := &StreamableClientTransport{
853 Endpoint: httpServer.URL,
854 DisableStandaloneSSE: test.disableStandaloneSSE,
855 }
856 client := NewClient(testImpl, nil)
857 session, err := client.Connect(ctx, transport, nil)
858 if err != nil {
859 t.Fatalf("client.Connect() failed: %v", err)
860 }
861
862 // Give some time for the standalone SSE connection to be established (if enabled)
863 time.Sleep(100 * time.Millisecond)
864
865 // Verify the connection state
866 streamableConn, ok := session.mcpConn.(*streamableClientConn)
867 if !ok {
868 t.Fatalf("Expected *streamableClientConn, got %T", session.mcpConn)
869 }
870
871 if got, want := streamableConn.disableStandaloneSSE, test.disableStandaloneSSE; got != want {
872 t.Errorf("disableStandaloneSSE field: got %v, want %v", got, want)
873 }
874
875 // Clean up
876 if err := session.Close(); err != nil {
877 t.Errorf("closing session: %v", err)
878 }
879
880 // Check if GET request was received
881 fake.calledMu.Lock()
882 getRequestReceived := false
883 if fake.called != nil {
884 getRequestReceived = fake.called[getRequestKey]
885 }
886 fake.calledMu.Unlock()
887
888 if got, want := getRequestReceived, test.expectGETRequest; got != want {
889 t.Errorf("GET request received: got %v, want %v", got, want)
890 }
891
892 // If we expected a GET request, verify it was actually received
893 if test.expectGETRequest {
894 if missing := fake.missingRequests(); len(missing) > 0 {
895 // Filter out optional requests
896 var requiredMissing []streamableRequestKey
897 for _, key := range missing {
898 if resp, ok := fake.responses[key]; ok && !resp.optional {
899 requiredMissing = append(requiredMissing, key)
900 }
901 }
902 if len(requiredMissing) > 0 {
903 t.Errorf("did not receive expected requests: %v", requiredMissing)
904 }
905 }
906 } else {
907 // If we didn't expect a GET request, verify it wasn't sent
908 if getRequestReceived {
909 t.Error("GET request was sent unexpectedly when DisableStandaloneSSE is true")
910 }
911 }
912 })
913 }
914 }
915
916 type mockOAuthHandler struct {
917 token *oauth2.Token
918 authorizeErr error
919 authorizeCalled bool
920 }
921
922 func (h *mockOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {
923 if h.token == nil {
924 return nil, nil
925 }
926 return oauth2.StaticTokenSource(h.token), nil
927 }
928
929 func (h *mockOAuthHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error {
930 h.authorizeCalled = true
931 return h.authorizeErr
932 }
933
934 func TestStreamableClientOAuth_AuthorizationHeader(t *testing.T) {
935 ctx := context.Background()
936 token := &oauth2.Token{AccessToken: "test-token"}
937 oauthHandler := &mockOAuthHandler{token: token}
938
939 fake := &fakeStreamableServer{
940 t: t,
941 responses: fakeResponses{
942 {"POST", "", methodInitialize, ""}: {
943 header: header{
944 "Content-Type": "application/json",
945 sessionIDHeader: "123",
946 },
947 body: jsonBody(t, initResp),
948 },
949 {"POST", "123", notificationInitialized, ""}: {
950 status: http.StatusAccepted,
951 wantProtocolVersion: latestProtocolVersion,
952 },
953 {"GET", "123", "", ""}: {
954 header: header{
955 "Content-Type": "text/event-stream",
956 },
957 },
958 {"DELETE", "123", "", ""}: {},
959 },
960 }
961 verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
962 if token != "test-token" {
963 return nil, auth.ErrInvalidToken
964 }
965 return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
966 }
967 httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
968 t.Cleanup(httpServer.Close)
969
970 transport := &StreamableClientTransport{
971 Endpoint: httpServer.URL,
972 OAuthHandler: oauthHandler,
973 }
974 client := NewClient(testImpl, nil)
975 session, err := client.Connect(ctx, transport, nil)
976 if err != nil {
977 t.Fatalf("client.Connect() failed: %v", err)
978 }
979 session.Close()
980 }
981
982 func TestStreamableClientOAuth_401(t *testing.T) {
983 ctx := context.Background()
984 oauthHandler := &mockOAuthHandler{token: nil}
985
986 fake := &fakeStreamableServer{
987 t: t,
988 responses: fakeResponses{
989 {"POST", "", methodInitialize, ""}: {
990 header: header{
991 "Content-Type": "application/json",
992 sessionIDHeader: "123",
993 },
994 body: jsonBody(t, initResp),
995 },
996 },
997 }
998 verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
999 // Accept any token.
1000 return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
1001 }
1002 httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
1003 t.Cleanup(httpServer.Close)
1004
1005 transport := &StreamableClientTransport{
1006 Endpoint: httpServer.URL,
1007 OAuthHandler: oauthHandler,
1008 }
1009 client := NewClient(testImpl, nil)
1010 _, err := client.Connect(ctx, transport, nil)
1011 if err == nil || !strings.Contains(err.Error(), "Unauthorized") {
1012 t.Fatalf("client.Connect() error does not contain 'Unauthorized': %v", err)
1013 }
1014
1015 if !oauthHandler.authorizeCalled {
1016 t.Errorf("expected Authorize to be called")
1017 }
1018 }
1019
1020 // blockingCountingOAuthHandler is an OAuthHandler that blocks inside
1021 // Authorize until the caller's context is cancelled, then returns a custom
1022 // error that does NOT wrap context.Canceled. This mirrors real-world OAuth
1023 // handlers that catch the cancellation internally and surface their own
1024 // error type. The fix for #882 checks ctx.Err() directly rather than
1025 // relying on the error from Authorize, so this must still trigger c.fail().
1026 // It records how many times Authorize is invoked.
1027 type blockingCountingOAuthHandler struct {
1028 mu sync.Mutex
1029 callCount int
1030 }
1031
1032 func (h *blockingCountingOAuthHandler) TokenSource(ctx context.Context) (oauth2.TokenSource, error) {
1033 return nil, nil
1034 }
1035
1036 func (h *blockingCountingOAuthHandler) Authorize(ctx context.Context, req *http.Request, resp *http.Response) error {
1037 h.mu.Lock()
1038 h.callCount++
1039 h.mu.Unlock()
1040 // Block until the caller's context is cancelled, mirroring an
1041 // interactive OAuth flow that the user has abandoned.
1042 <-ctx.Done()
1043 // Return a custom error that does not wrap context.Canceled, as a
1044 // real-world handler might. The code under test must check ctx.Err()
1045 // to detect the cancellation, not this error.
1046 return fmt.Errorf("oauth flow interrupted")
1047 }
1048
1049 func (h *blockingCountingOAuthHandler) Calls() int {
1050 h.mu.Lock()
1051 defer h.mu.Unlock()
1052 return h.callCount
1053 }
1054
1055 // TestStreamableClientOAuth_CancelledAuthorize_NoReprompt is a regression
1056 // test for #882. When OAuthHandler.Authorize returns a context-cancelled
1057 // error, the connection must enter a failed state so that the cancellation
1058 // notification the call layer sends in response to ctx cancellation does
1059 // not flow back through the same broken auth path and re-invoke Authorize.
1060 func TestStreamableClientOAuth_CancelledAuthorize_NoReprompt(t *testing.T) {
1061 handler := &blockingCountingOAuthHandler{}
1062
1063 fake := &fakeStreamableServer{
1064 t: t,
1065 responses: fakeResponses{
1066 {"POST", "", methodInitialize, ""}: {
1067 header: header{
1068 "Content-Type": "application/json",
1069 sessionIDHeader: "123",
1070 },
1071 body: jsonBody(t, initResp),
1072 },
1073 },
1074 }
1075 verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
1076 return &auth.TokenInfo{Expiration: time.Now().Add(time.Hour)}, nil
1077 }
1078 httpServer := httptest.NewServer(auth.RequireBearerToken(verifier, nil)(fake))
1079 t.Cleanup(httpServer.Close)
1080
1081 transport := &StreamableClientTransport{
1082 Endpoint: httpServer.URL,
1083 OAuthHandler: handler,
1084 }
1085 client := NewClient(testImpl, nil)
1086
1087 // Use a context with a tight deadline so the cancellation path runs
1088 // while the auth flow is in progress.
1089 ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
1090 defer cancel()
1091
1092 _, err := client.Connect(ctx, transport, nil)
1093 if err == nil {
1094 t.Fatal("expected client.Connect to fail")
1095 }
1096
1097 // Give the cancellation Notify path a moment to (try to) run.
1098 time.Sleep(50 * time.Millisecond)
1099
1100 // Authorize should be invoked exactly once. The bug in #882 caused
1101 // it to be invoked a second time when the call layer sent the
1102 // cancellation notification through the same auth-broken connection.
1103 if got := handler.Calls(); got != 1 {
1104 t.Errorf("expected Authorize to be called exactly 1 time, got %d", got)
1105 }
1106 }
1107
1108 func TestTokenInfo(t *testing.T) {
1109 ctx := context.Background()
1110
1111 // Create a server with a tool that returns TokenInfo.
1112 tokenInfo := func(ctx context.Context, req *CallToolRequest, _ struct{}) (*CallToolResult, any, error) {
1113 return &CallToolResult{Content: []Content{&TextContent{Text: fmt.Sprintf("%v", req.Extra.TokenInfo)}}}, nil, nil
1114 }
1115 server := NewServer(testImpl, nil)
1116 AddTool(server, &Tool{Name: "tokenInfo", Description: "return token info"}, tokenInfo)
1117
1118 streamHandler := NewStreamableHTTPHandler(func(req *http.Request) *Server { return server }, nil)
1119 verifier := func(ctx context.Context, token string, req *http.Request) (*auth.TokenInfo, error) {
1120 if token != "test-token" {
1121 return nil, auth.ErrInvalidToken
1122 }
1123 return &auth.TokenInfo{
1124 Scopes: []string{"scope"},
1125 // Expiration is far, far in the future.
1126 Expiration: time.Date(5000, 1, 2, 3, 4, 5, 0, time.UTC),
1127 }, nil
1128 }
1129 handler := auth.RequireBearerToken(verifier, nil)(streamHandler)
1130 httpServer := httptest.NewServer(mustNotPanic(t, handler))
1131 defer httpServer.Close()
1132
1133 transport := &StreamableClientTransport{
1134 Endpoint: httpServer.URL,
1135 OAuthHandler: &mockOAuthHandler{token: &oauth2.Token{AccessToken: "test-token"}},
1136 }
1137 client := NewClient(testImpl, nil)
1138 session, err := client.Connect(ctx, transport, nil)
1139 if err != nil {
1140 t.Fatalf("client.Connect() failed: %v", err)
1141 }
1142 defer session.Close()
1143
1144 res, err := session.CallTool(ctx, &CallToolParams{Name: "tokenInfo"})
1145 if err != nil {
1146 t.Fatal(err)
1147 }
1148 if len(res.Content) == 0 {
1149 t.Fatal("missing content")
1150 }
1151 tc, ok := res.Content[0].(*TextContent)
1152 if !ok {
1153 t.Fatal("not TextContent")
1154 }
1155 if g, w := tc.Text, "&{[scope] 5000-01-02 03:04:05 +0000 UTC map[]}"; g != w {
1156 t.Errorf("got %q, want %q", g, w)
1157 }
1158 }