From 7ac7a3df6ba6dd51a57dcc7d9851b4d33f67ffce Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Tue, 15 Sep 2026 13:30:29 +1000 Subject: [PATCH] fix(mcp): cancel in-flight SSE reconnect on Stop WIRE: the SSE transport's Stop contract already says it closes the connection and waits for background readers, but the reconnect loop issued its HTTP GET with the Start context, which Stop could not cancel, so Stop blocked on readerWg.Wait() against an unreachable endpoint. Wire a per-lifecycle cancel (mirroring the stdio transport's stopCh plus guarded commit) so Stop interrupts the in-flight reconnect request. --- internal/tools/mcp/transport_sse.go | 25 ++++++++++- internal/tools/mcp/transport_sse_test.go | 55 ++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 2 deletions(-) diff --git a/internal/tools/mcp/transport_sse.go b/internal/tools/mcp/transport_sse.go index 9a1b99200..0d1f2879b 100644 --- a/internal/tools/mcp/transport_sse.go +++ b/internal/tools/mcp/transport_sse.go @@ -75,6 +75,12 @@ type SSETransport struct { // stopCh is closed by Stop(). Background goroutines select on this. stopCh chan struct{} + // lifecycleCancel cancels the lifecycle context handed to the background + // reader and reconnect goroutines. Stop calls it so an in-flight reconnect + // HTTP request can be interrupted immediately instead of blocking Stop + // until the OS-level connect/read gives up. + lifecycleCancel context.CancelFunc + // The SSE reader goroutine. readerWg sync.WaitGroup // Track HTTP response body so Stop can close it. @@ -101,10 +107,12 @@ func (t *SSETransport) Start(ctx context.Context) error { } t.state = StateStarting t.stopCh = make(chan struct{}) + lifecycleCtx, cancel := context.WithCancel(ctx) + t.lifecycleCancel = cancel t.messageEndpoint = t.config.MessageEndpoint // fallback; endpoint event overrides t.mu.Unlock() - return t.connect(ctx) + return t.connect(lifecycleCtx) } // Stop closes the SSE connection, fails pending requests, and transitions @@ -123,6 +131,9 @@ func (t *SSETransport) Stop(_ context.Context) error { close(t.stopCh) } } + if t.lifecycleCancel != nil { + t.lifecycleCancel() + } if t.respBody != nil { _ = t.respBody.Close() t.respBody = nil @@ -335,14 +346,24 @@ func (t *SSETransport) reconnect(ctx context.Context) { backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff()) continue } + + // Guarded commit: Stop may have won while the reconnect GET was in + // flight. Do not install a reader (or a response body Stop has already + // missed) once Stop has closed stopCh. t.mu.Lock() + if t.isStopped() || t.state != StateRunning { + t.state = StateStopped + t.mu.Unlock() + _ = resp.Body.Close() + return + } if msgURL != "" { t.messageEndpoint = msgURL } t.respBody = resp.Body + t.readerWg.Add(1) t.mu.Unlock() - t.readerWg.Add(1) go t.runReader(ctx, resp.Body, reader) return } diff --git a/internal/tools/mcp/transport_sse_test.go b/internal/tools/mcp/transport_sse_test.go index 5dd68c312..47cb637d8 100644 --- a/internal/tools/mcp/transport_sse_test.go +++ b/internal/tools/mcp/transport_sse_test.go @@ -9,6 +9,7 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "time" ) @@ -275,3 +276,57 @@ func TestSSETransportConcurrentSendsGetCorrectResponses(t *testing.T) { t.Error(e) } } + +// TestSSETransportStopCancelsInFlightReconnect pins the Stop contract: when +// the SSE stream drops and reconnect is blocked on an unreachable endpoint, +// Stop must cancel that in-flight HTTP request instead of waiting for the +// OS-level connect/read to time out. +func TestSSETransportStopCancelsInFlightReconnect(t *testing.T) { + var requests atomic.Int32 + reconnectStarted := make(chan struct{}) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch requests.Add(1) { + case 1: + // Initial connect: deliver the endpoint event, then return so the + // client reader sees EOF and drops into reconnect. + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = fmt.Fprintf(w, "event: endpoint\ndata: http://127.0.0.1:1/messages\n\n") + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + default: + // Reconnect: block until the client cancels the request (via Stop). + close(reconnectStarted) + <-r.Context().Done() + } + })) + defer srv.Close() + + tr := NewSSETransport(SSETransportConfig{ + SSEEndpoint: srv.URL + "/sse", + ReconnectBackoff: time.Millisecond, + MaxReconnectBackoff: time.Millisecond, + }) + if err := tr.Start(context.Background()); err != nil { + t.Fatalf("Start: %v", err) + } + + select { + case <-reconnectStarted: + case <-time.After(2 * time.Second): + t.Fatal("reconnect request never started") + } + + done := make(chan error, 1) + go func() { done <- tr.Stop(context.Background()) }() + select { + case err := <-done: + if err != nil { + t.Fatalf("Stop: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("Stop did not cancel the in-flight reconnect request") + } +}