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.
This commit is contained in:
2026-11-27 10:46:22 +00:00
committed by GitHub
parent 9f2690b9bf
commit af1a64aaa3
2 changed files with 35 additions and 0 deletions
+30
View File
@@ -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"))
}
}
+5
View File
@@ -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