Repository navigation
Description
Summary
The AuthBridge forward-proxy fully buffers outbound response bodies via io.ReadAll whenever any plugin in the outbound pipeline declares ReadsBody or WritesBody. For MCP servers using the Streamable HTTP transport, tools/call responses can be returned as Content-Type: text/event-stream (chunked-transfer body with SSE-framed JSON-RPC messages) and stay open for the full duration of slow tool execution. Buffering converts that streaming response into a blocking Client.Do read, which is then bounded by the hard-coded 30s http.Client.Timeout and produces 502 bad gateway (or appears to the agent as a hang followed by retry).
This affects every realistic outbound pipeline because mcp-parser, inference-parser, and ibac all declare ReadsBody: true.
Reproduction
Deploy any agent + MCP server pair where MCP tool calls take longer than ~30s of upstream work, with an outbound pipeline containing mcp-parser (and/or ibac/inference-parser). Observed with the exgentic tau2 benchmark, where tool calls invoke a user-simulator LLM:
./deploy-and-evaluate.sh --benchmark tau2 --agent tool_calling \
--plugin-preset ibac-only --model openai/azure/gpt-5.5
AuthBridge logs show the request being admitted by the pipeline and then the body read failing:
17:51:21.467 mcp-parser: request method=tools/call isAction=true
17:51:35.619 forward-proxy: response body read error
host=exgentic-mcp-tau2-mcp:8000
error="context deadline exceeded ... while reading body"
17:51:56.416 forward-proxy: response body read error context canceled
The agent sees the tool call as never-returning and stalls.
Root cause
authlib/listener/forwardproxy/server.go:
-
Lines 277–291 — when
OutboundPipeline.NeedsBody()is true, the entire response body is read withio.ReadAll(io.LimitReader(resp.Body, maxBodySize+1))before any plugin runs and before any byte is forwarded downstream:if s.OutboundPipeline.NeedsBody() && resp.Body != nil { respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxBodySize+1)) ... pctx.ResponseBody = respBody resp.Body = io.NopCloser(bytes.NewReader(respBody)) }
-
Line 89 — the outbound HTTP client has
Timeout: 30 * time.Second, which Go applies to the entire request lifecycle including body read. With buffering on, this caps the lifetime of any streaming MCPtools/callto 30s regardless of whether it's actually making progress. -
Line 25 —
maxBodySize = 1 << 20(1 MiB). Even if the timeout were raised, large streaming responses (long tau2 simulator turns, large MCP results) would still hit502 response body too large. -
Line 344 — the downstream
io.Copy(w, resp.Body)is a no-op stream becauseresp.Bodyis already a fully-bufferedbytes.Readerby then.
Plugins declaring ReadsBody: true (all on the outbound path):
authlib/plugins/mcpparser/plugin.go:91authlib/plugins/ibac/plugin.go:301authlib/plugins/inferenceparser/plugin.go:30
Why a bigger timeout / bigger buffer is not the right fix
Raising http.Client.Timeout and maxBodySize masks the symptom for short tool calls but:
- Buffered tool-call responses block the agent until the upstream call fully completes, defeating the streaming-HTTP transport the agent and MCP server already negotiate.
- IBAC's verdict on
tools/callis decided at request time (before the upstream call goes out); response-side body inspection in IBAC is auxiliary (audit/event recording), so there is no semantic reason to gate the downstream wire on a fully-buffered response. - mcp-parser's response-side parsing operates per JSON-RPC message, which composes naturally with frame-by-frame streaming.
Proposed fix
Special-case streaming responses in the forward-proxy response handler:
- Detect
Content-Type: text/event-stream(or any chunked, non-application/jsonresponse) and switch from the buffered branch to a streaming pass-through. - For each completed JSON-RPC message in the SSE-framed body, run the existing response-phase plugin inspectors (mcp-parser, ibac, inference-parser) over that message, then immediately write the frame to the downstream
ResponseWriterandFlush(). - Keep the existing buffered path for
application/jsonone-shot responses — they're small, plugins want the full envelope, and latency cost is negligible. - Once the streaming path exists, the 30s
http.Client.Timeoutbecomes a connect/header ceiling only (which is fine; tau2 servers return headers immediately), andmaxBodySizeno longer applies to the wire response, only to whatever slice a plugin actually inspects.
The Streamable HTTP transport is already in use end-to-end:
- Agent:
mcp.client.streamable_http.streamable_http_client(in theexgenticagent'smcp_wrapper.py). - MCP server: FastMCP's
streamable_http_app().
So no agent or MCP-server changes are needed — only the proxy needs to stop converting streaming responses into buffered ones.
IBAC compatibility
The proposed fix does not affect IBAC's decision-making. IBAC's body inspection is request-side only:
describeAction()atauthlib/plugins/ibac/plugin.go:598builds the judge prompt frompctx.Method/Scheme/Host/Path,pctx.Body(request body excerpt),pctx.Extensions.MCP(parsed MCP method/tool/args from mcp-parser), andpctx.Extensions.Inference(whenJudgeInference=true). All four are populated during the request phase, before forwarding upstream.OnRequest()atplugin.go:333is the only place the judge is called and the only place IBAC can emit aReject. The verdict is final before the upstream MCP server starts producing a response.OnResponse()atplugin.go:564is a literal no-op (return pipeline.Action{Type: pipeline.Continue}) — IBAC does not inspect the response body today.
IBAC's ReadsBody: true capability covers its use of pctx.Body (the request body). The fact that the same flag also triggers response-side io.ReadAll is a coincidence of the current proxy implementation, not something IBAC requires. Request-side buffering remains unchanged under the proposed fix.
If a future IBAC feature wanted to inspect tool-call results, the streaming path would compose better than the current buffered one — each JSON-RPC result arrives as a discrete frame instead of being demultiplexed from a buffered SSE blob.
Severity
High for any deployment running ibac or mcp-parser against MCP servers whose tool calls do meaningful upstream work. Currently makes the tau2 benchmark unusable through the AuthBridge sidecar.
Metadata
Metadata
Assignees
Type
Projects
- StatusShow more project fieldsDone
Activity
huang195 commentedon Jun 3, 2026
Traced the code end-to-end — confirming the bug and the streaming direction, with a few refinements. Scope note up front: this plans the fix without mid-stream response denial. Response-phase plugins here are observability-only today (IBAC decides at request time,
OnResponseis a no-op), so the goal is "stream gracefully without breaking observability," and per-message response enforcement is a clean follow-up the design leaves room for.1. Diagnosis confirmed
forwardproxy/server.gobuffers viaio.ReadAll(LimitReader(resp.Body, maxBodySize+1))whenNeedsBody(), runsRunResponseonce over the buffer, thenio.Copys an already-buffered reader. WithClient.Timeout=30scovering the body read andmaxBodySize=1<<20, a slow/largetools/callSSE response 502s. ✔2. Streaming is the right fix (not bigger buffers)
Raising the timeout/cap risks OOM on large results and still blocks the transport. Streaming bounds memory to one frame and removes the dependence on a total deadline. Enforcement is unaffected: IBAC gates the call at request time, before any response streams.
3. The timeout must be changed explicitly
http.Client.Timeoutcovers reading the body, so it does not become a "header-only ceiling" just by switching toio.Copy. Replace it withTransport.ResponseHeaderTimeout(time-to-headers) + a read/idle deadline to kill hung streams. Without this, streaming still dies at 30s.4. Branch on
Content-Type, per responsePer the Streamable HTTP spec the server chooses
application/jsonvstext/event-streamper response (clientAccepts both), so the same tool may return JSON on one call and SSE on the next. Decide at header time offContent-Type— reliable, no heuristics. Useful framing: a response is always a stream of ≥1 complete JSON-RPC messages;application/jsonis just the one-message case.5. The plugins split two ways — this is the real work
ibacOnResponseno-op (gates at request)mcp-parsertools/callresult is one complete frameinference-parserdeltas;usageonly in the final chunka2a-parsermessage/streameventsSo 2 of 4 aggregate. Running their current
OnResponseper-frame yields fragmented/overwritten output and N noisy events. They need to fold each frame into running state and finalize at end-of-stream — a real (if contained) rework, not a drop-in.6. Interface: a frame hook as an optional interface — no core-interface growth
The codebase already uses optional, type-asserted interfaces (
Configurable/Initializer/Readier/Shutdowner/Finisher). Add streaming the same way; existing plugins are untouched. Model the response uniformly as frames:mcp-parserimplements only this (per-message).inference-parser/a2a-parserfold each frame and finalize whenlast.OnRequeststays — MCP requests are one-shot JSON and that hook feeds IBAC; it's not the streaming problem.application/jsonis delivered as a singlelast=trueframe, so stream-native plugins need one response code path, not two. (A later, larger cleanup could slim the corePlugininterface so plugins implement only the hooks their protocol needs — out of scope here.)7. Scope for this PR
In: stream
text/event-streamframe-by-frame (http.Flusher, noContent-Length); header-only timeout; frame-native plugin handling (mcp-parserper-message,inference/a2afold+finalize); keep the buffered path forapplication/json.Out (for now): mid-stream response denial. Since nothing rejects on the response, the proxy can forward+flush each frame and feed plugins for recording — no inspect-before-forward gating needed. The
OnResponseFramehook leaves the door open to add per-message enforcement later without rework.8. Also applies inbound
The same buffering exists in
reverseproxy.modifyResponsefor A2Amessage/stream→a2a-parser, so the streaming path/contract should be shared across both listeners.WritesBody/SetResponseBodyis incompatible with streaming (no plugin does it today — guard it).kellyaa commentedon Jun 4, 2026
Implementation plan
Picking up @huang195's refinements (thanks — these change the shape of the work). Posting the plan before I start so the design calls are reviewable.
Scope
In: stream
text/event-streamresponses frame-by-frame in both forward and reverse proxies; replace the outboundhttp.Client.Timeoutwith a header-only ceiling + idle deadline; add an optionalStreamingResponderplugin interface; convert the aggregating plugins to fold-and-finalize.Out: mid-stream response enforcement (no plugin rejects on the response today — the new hook leaves the door open for it later).
Steps
Branch & worktree
mainofkagenti-extensions, branchfix/477-streaming-mcp-responses. DCO + signed commits (-s -S).Outbound HTTP client (
authlib/listener/forwardproxy/server.go:65-95)Client.Timeout(covers body read; incompatible with streaming).Transport.ResponseHeaderTimeout(~30s — preserves the existing time-to-headers guard).Optional plugin interface in
authlib/pipeline/:Type-asserted opt-in (same pattern as
Configurable/Initializer/Readier/Shutdowner/Finisher). No core-interface churn; non-streaming plugins are untouched. Plumb aRunResponseFramehelper throughpipeline.Holder.Response handler — branch on
Content-Typeper responsetext/event-stream: streaming path. Read SSE frames; for each complete JSON-RPC message callOnResponseFrame(..., last=false)then write+Flush downstream. On EOF, call once more withlast=true(empty frame) so aggregating plugins can finalize.RunResponseis NOT invoked after the streaming path completes — aggregating plugins move their finalization logic intoOnResponseFrame(last=true). (Decision: avoids confusing legacy plugins that don't migrate; clean contract.)application/json: existing buffered path preserved as today. Additionally, for plugins implementingStreamingResponder, deliver the single buffered body as onelast=trueframe so streaming-aware plugins use a single code path (the "stream of ≥1 messages" framing).WritesBody=trueguard: if any plugin in the outbound pipeline declaresWritesBody, refuse the streaming path (semantically incompatible — we can't rewrite a body we've already started forwarding) and fall back to the existing buffered path with a warning log. No current plugin setsWritesBody; this is the guard @huang195 called out.maxBodySizereshapeConvert aggregating plugins
inference-parser: implementOnResponseFramethat decodes eachdata:chunk'schoices[].delta, accumulates content, and collectsusagefrom the final chunk. Onlast=true, populatepctx.Extensions.Inferenceexactly as today'sOnResponsewould. ExistingOnResponsebecomes a no-op whenOnResponseFrameran. Because the JSON path delivers a singlelast=trueframe, the same code works for both shapes.a2a-parser: implementOnResponseFramethat parses eachmessage/streamevent and folds artifact + terminal status into running state; finalize onlast=true.mcp-parser: implementOnResponseFramefor per-message recording (one JSON-RPC result == one frame). Drop the bufferedOnResponsebody parse in favor of the framed one.ibac: unchanged —OnResponsealready a no-op.Mirror in
authlib/listener/reverseproxy/message/streamresponses use the same buffering today (reverseproxy.modifyResponse). Apply the sameContent-Typebranch and reuse theOnResponseFrameplumbing + SSE frame reader. The streaming contract is shared across forward and reverse proxies.Tests
OnResponseFrame(per-message formcp-parser; fold-and-finalize forinference-parser/a2a-parser).forwardproxy/server_test.go: mock upstream that emits SSE over >30s with idle gaps — verify downstream sees frames as they arrive, plugins receive each frame with correctlastflag, no 30s timeout fires, andWritesBody=truein pipeline forces the buffered fallback.reverseproxy/.go test ./...underauthlib/.PR
main, references AuthBridge forward-proxy buffers entire response body, breaking streaming MCP tool calls #477. DCO sign-off;Assisted-Bytrailer.Design calls flagged for review
RunResponseafter streaming completes — aggregating plugins finalize viaOnResponseFrame(last=true). Cleaner contract; legacy plugins that don't migrate aren't called on streaming responses.maxBodySize=1 MiBon the streaming path; no total cap — bounds memory per message while not defeating streaming.WritesBody=trueforces buffered fallback rather than failing the request — preserves correctness; logs visibility.Will follow up with the PR.
fix(authbridge): Address PR #480 review feedback
fix(authbridge): Stream text/event-stream responses frame-by-frame