From af1a64aaa35773326b685041d18a1f328a7ef22a Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Fri, 27 Nov 2026 10:46:22 +0000 Subject: [PATCH] fix(passthrough): send event-stream headers before the first event (#19) The passthrough proxy wrote the status line but flushed only on the first body write. An MCP server-to-client stream (GET with text/event-stream) can stay silent for a long time, so the client did not get the response headers. Traefik in front of the standalone gateway waited for its 20m responseHeaderTimeout and then returned 504. The proxy now flushes the headers at once when the upstream answers with text/event-stream. --- idle_streams_test.go | 30 ++++++++++++++++++++++++++++++ routes_passthrough.go | 5 +++++ 2 files changed, 35 insertions(+) diff --git a/idle_streams_test.go b/idle_streams_test.go index b52887e..21b5415 100644 --- a/idle_streams_test.go +++ b/idle_streams_test.go @@ -133,3 +133,33 @@ func TestIdleStreamSetNilSafe(t *testing.T) { s.remove(1) s.drain() } + +func TestTargetProxy_EventStreamHeadersBeforeFirstEvent(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + w.(http.Flusher).Flush() + <-r.Context().Done() + })) + t.Cleanup(upstream.Close) + front := httptest.NewServer(newIdleStreamGateway(t, upstream.URL)) + t.Cleanup(front.Close) + + req, err := http.NewRequest(http.MethodGet, front.URL+"/mcp/notes", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer sk-alice") + req.Header.Set("Accept", "text/event-stream") + // A proxy in front gives up when headers do not arrive, so a silent + // stream must still send them at once. + client := &http.Client{Transport: &http.Transport{ResponseHeaderTimeout: 2 * time.Second}} + resp, err := client.Do(req) + if err != nil { + t.Fatalf("no response headers from an idle event stream: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK || !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { + t.Errorf("status %d content-type %q, want 200 text/event-stream", resp.StatusCode, resp.Header.Get("Content-Type")) + } +} diff --git a/routes_passthrough.go b/routes_passthrough.go index f2d6d59..3630443 100644 --- a/routes_passthrough.go +++ b/routes_passthrough.go @@ -1811,6 +1811,11 @@ func (g *Gateway) proxyUpstream(w http.ResponseWriter, r *http.Request, upstream restoreRateLimitHeaders(w.Header(), gwRateHeaders) w.WriteHeader(resp.StatusCode) fw := newFlushWriter(w) + // An event stream can stay silent for a long time, and a proxy in front + // gives up when no response headers arrive. + if fw.f != nil && isEventStreamResponse(resp) { + fw.f.Flush() + } // A non-streaming JSON response, or an SSE stream (isSSE — finding 2 // fix, review-routes.md: previously only isJSON was teed at all, so a