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") + } +}