Repository navigation
Validate upstream JSON-RPC responses in transparent proxy - #7317
Conversation
The transparent proxy forwarded whatever a backend returned, so a broken backend's malformed answer to a JSON-RPC request reached the client as a successful 200. It now checks the 200 application/json answer to every id-bearing POST before acting on it, and replaces an invalid one with a 502 carrying a JSON-RPC error that echoes the client's request id. The check runs in tracingTransport.RoundTrip, before the response can register a proxy session or mark the server initialized, and reuses the MCP envelope rules through a new mcp.ValidateResponse that inspects the envelope only. The client's Accept-Encoding is withheld from id-bearing requests so Go's transport decodes gzip and the body can be read; a body still carrying a content coding fails closed. Bodies are buffered up to 100 MiB. This reworks the approach from #5288, which validated in ModifyResponse after session registration and rejected some spec-valid responses. Fixes #5247 Co-authored-by: Bishnu Bista <[email protected]> Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
httptest.Server.Close calls CloseIdleConnections on http.DefaultTransport, so a parallel test reusing a pooled connection can fail with "CloseIdleConnections called". The new upstream validation tests close many servers in parallel, which made this hit TestPrefixHandlers_WellKnownNamespaceCoexistence in CI. Give that test a dedicated client and the validation tests a dedicated backend transport, as #6264 did for the dial-error test. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #7317 +/- ##
==========================================
+ Coverage 81.25% 82.14% +0.89%
==========================================
Files 880 934 +54
Lines 89960 94625 +4665
==========================================
+ Hits 73099 77734 +4635
- Misses 16856 16886 +30
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
rdimitrov
left a comment
There was a problem hiding this comment.
Approving. This fixes #5247 and addresses the open points from #5288:
- It validates in
RoundTrip, before any session is registered. - It reuses the existing MCP envelope rules.
- It never emits
"id": null. - It fails closed on bodies that still carry a content coding.
The SSE gap is already tracked in #5292.
I built thv from this branch and from its base and ran thv proxy in front of a mock backend and the official Go SDK server. The PR also merges cleanly onto current main, and pkg/mcp/... and pkg/transport/proxy/... pass on the merged result.
Backend answer to tools/list (id 7) |
base | this PR |
|---|---|---|
Issue repro (no jsonrpc, wrong id) |
200, forwarded | 502, -32603, id 7 echoed, one WARN |
Empty body, or HTML labeled application/json |
200 | 502 |
| SSE with a bad frame, or 500 with a non-JSON body | passed through | passed through (out of scope, as documented) |
| Gzip-compressing backend | client sees gzip | Go negotiates and decodes; valid response forwarded |
| Empty 200 answering a notification | 200 | 200 |
Malformed initialize returning Mcp-Session-Id |
session registered | 502; a follow-up request with that session id gets 404 |
Results with the official Go SDK client:
- Connect, list and call all succeed with a JSON-response server, a gzip-middleware server and an SSE server, at 100 B, 5 MB and 60 MB.
- At 110 MB the JSON calls now fail with
Bad Gateway(body_too_large), while SSE still passes. That matches the documented behavior. - On JSON responses, validation costs about 9 ms/MiB.
Two non-blocking notes on existing users:
- Backends that serialize the unused member as
nullnow break. Examples:{"jsonrpc":"2.0","id":1,"result":{},"error":null}, or an error response that also carries"result":null. The base branch forwarded these as 200; this PR answers 502. That is strict JSON-RPC (both members present), but it is a likely way a backend that works today starts failing: serializers that don't omit nulls produce exactly this, and lenient clients accept it. Either treat an explicitnullfor the absent member as absent, or list it under user-facing changes next to null ids, so operators can recognize it from theinvalid_responseWARN. - A rejected
initializeleaves the backend's session open. The backend issued anMcp-Session-Idthat the proxy drops without sending aDELETE, so it lingers until the backend's own idle timeout. That's low impact, and the client can't reuse it (verified above). One line in the scope paragraph would make it explicit.
|
How this was tested: Setup: I built Bad replies (curl, A/B):
Real client: the official Go SDK client ran connect, Tests: the branch merges cleanly onto current |
Accept null for the unused JSON-RPC member
Upstream response validation rejected responses that carry an explicit
null for the member they do not use, such as {"result":{},"error":null}
or "result":null beside an error. Serializers that do not omit nulls
emit these, lenient clients accept them, and before #7317 the proxy
forwarded them, so a backend that worked would start getting 502s.
They are unambiguous, so treat the null member as absent.
Also document that a rejected initialize response leaves the backend
session it carried open until the backend's idle timeout, since the
proxy does not send it a DELETE.
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Summary
The transparent proxy forwards whatever the backend returns. A broken backend's malformed answer to a JSON-RPC request (missing
"jsonrpc":"2.0", invalidid, a bare array or string, an empty body) therefore reaches the client as a successful200. The client gets a protocol violation instead of a clear upstream error. This takes over #5288 by @bishnubista, who is credited as co-author. That PR identified the gap but needed rework before it could merge (see reviewer notes).tracingTransport.RoundTrip, check the backend's200 application/jsonanswer to every id-bearing POST. Replace an invalid one with502 Bad Gatewayand a JSON-RPC error that echoes the client's requestid(built withmcp.EncodeJSONRPCError,-32603, fixed message, no upstream headers). Log one WARN naming the reason, method and target.initializedoes neither.mcp.ValidateResponse, which applies the existing MCP envelope rules (BOM, string/int64 ids, id-less error responses allowed; batches, requests, notifications, null/fractional ids, duplicate or case-aliased envelope members rejected). It checks the envelope only, so case-distinct names insideresult(e.g. a schema with bothIDandid) are not rejected.Accept-Encodingfrom id-bearing requests, followingmcp.WithoutAcceptEncodingin the authz and tool filters, so Go's transport decodes gzip and the body can be checked. A body that still carries a content coding fails closed, as in the authz response filter. Bodies are buffered up to 100 MiB, matchingpkg/vmcp/client.health_check_zombiee2e mock, which answered every POST without anid.Fixes #5247
Type of change
Test plan
task test). Everything passes except 4 tests inpkg/plugins/pluginsvc, which also fail onmainin the same local environment and are unrelated.task test-e2e)task lint-fix, with CI's pinned golangci-lint v2.15.0, 0 issues)Manual and e2e checks:
test/e2e/health_check_zombie_test.gowith an isolated HOME. It fails on Validate upstream JSON-RPC responses in transparent proxy #5288 (readiness probe gets a 502 forever) and passes here.mainwith a realTransparentProxyin front of a malformed backend (200forwarded). Confirmed that Validate upstream JSON-RPC responses in transparent proxy #5288 also rejected spec-valid traffic, which this PR accepts and pins in tests:200empty body answering a notification (the official Go SDK'sConnectfailed withBad Gateway)initializebrChanges
pkg/mcp/response_validation.goValidateResponse, envelope-only response check with fixed rejection reasonspkg/transport/proxy/transparent/upstream_response.gopkg/transport/proxy/transparent/transparent_proxy.goAccept-Encodingfor id-bearing requests; validate before session registrationtest/e2e/health_check_zombie_test.godocs/arch/03-transport-architecture.md,docs/middleware.mdDoes this introduce a user-facing change?
Yes, for clients of the transparent proxy (
thv runwith streamable-http/SSE servers, remote servers,thv proxy, operator proxy runners):200 application/jsonbody that is not a valid JSON-RPC response, answering an id-bearing request, was forwarded as200. After:502 Bad Gatewaywith{"jsonrpc":"2.0","id":<request id>,"error":{"code":-32603,"message":"Invalid upstream JSON-RPC response"}}, plus a WARN log line on the proxy.Accept-Encodingwas forwarded, so the backend could compress responses end to end. After: it is withheld for id-bearing requests, so those responses (JSON and SSE) reach the client uncompressed. A backend that compresses unprompted, or uses a coding Go does not decode (br,zstd), gets its JSON answer rejected with502.200 application/jsonanswer of any size was streamed through. After: it is buffered, and an answer over 100 MiB is rejected with502."id": nullis now rejected. MCP'sRequestIdcannot be null, though plain JSON-RPC 2.0 allows it for errors.Special notes for reviewers
RoundTriprather thanModifyResponse, so session state isn't committed for a badinitialize."id": null.200statuses, other media types, notifications and client responses are not validated. That covers the gap @amirejaz noted on Validate upstream JSON-RPC responses in transparent proxy #5288: an SSE stream can't be rewritten to a 502 mid-response.reinitializeAndReplay) are not validated. Those paths register their session before returning, and folding validation in there is a larger change. I can do it as a follow-up if wanted.-32603follows the codebase precedent for backend failures (pkg/transport/proxy/streamable'supstreamErrorResponse).502rather than the authz and tool filters'500is deliberate: the fault is the upstream's.200 application/jsonanswer to an id-bearing request is now buffered (bounded at 100 MiB) instead of streamed.🤖 Generated with Claude Code