fix: return HTTP 400 PARSE_ERROR for non-UTF-8 POST bodies#3182
Open
tirthfx wants to merge 1 commit into
Open
Conversation
The Streamable HTTP POST handler parsed the request body with json.loads() under `except json.JSONDecodeError`. When the body bytes are not valid UTF-8, json.loads() raises UnicodeDecodeError from its internal decode step, which is not a JSONDecodeError, so it bypassed the parse-error branch and reached the generic exception handler. The client got an unexplained HTTP 500 INTERNAL_ERROR and the server logged a traceback at ERROR plus a second ERROR record from the forwarded exception, while a merely malformed UTF-8 body got a clean HTTP 400. Widen the catch to ValueError. Both json.JSONDecodeError and UnicodeDecodeError subclass it, so a body that cannot be parsed for either reason is now answered as the client error it is, with no ERROR-level server logging. Fixes modelcontextprotocol#3150 Github-Issue: modelcontextprotocol#3150 Reported-by: Aleksandr Filippov
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #3150
A POST body that is syntactically valid JSON but encoded in something other than UTF-8 is answered with HTTP 500
INTERNAL_ERROR(-32603) instead of HTTP 400PARSE_ERROR(-32700), and logs two ERROR-level records including a full traceback. This widens the parse-error catch by one line so such a body is treated as the client error it is.Motivation and Context
The common trigger is Windows-1252 punctuation — an em dash (
0x97) or curly quotes — inside a string value of otherwise well-formed JSON, produced by a client serializing with a legacy default codepage. A body that is merely malformed but valid UTF-8 already gets a clean HTTP 400 with an actionable message, so today the more understandable encoding mistake gets the worse experience: an unexplained 500 plus a server-side ERROR cascade that reads as a server defect to operators.Root cause:
_handle_post_requestinsrc/mcp/server/streamable_http.pyparsed the body withjson.loads(body)underexcept json.JSONDecodeError. For non-UTF-8 bytes,json.loads()fails in its internal decode step and raisesUnicodeDecodeError, which is not aJSONDecodeError— so it bypassed the parse-error branch and reached the genericexcept Exceptionhandler, which returns the 500, logs the traceback, and forwards the exception into the session's incoming stream (producing the second ERROR record, frommcp.server.lowlevel.server).The change widens the catch to
except ValueError. Bothjson.JSONDecodeErrorandUnicodeDecodeErrorsubclassValueError, so a body that cannot be parsed for either reason now takes the same client-error path.Why this rather than cherry-picking #1912, which the issue proposes as its headline ask: #1912 swaps the parser to
pydantic_core.from_jsonand was motivated by performance, not this behavior. On a branch that takes only non-breaking bug and security fixes, widening the existing catch reaches the identical behavioral outcome with a smaller surface and no new import or parser swap — this is the "minimal alternative" the issue itself describes. The visible trade-off is that theParse error:message text for a bad-encoding body now differs betweenv1.x(CPython'sUnicodeDecodeErrorwording) andmain(pydantic-core's wording); the HTTP status and JSON-RPC error code match. Happy to switch to the cherry-pick if you would rather keep the branches aligned on the parser itself.The issue also asks for a v1.x patch release containing this. That is a maintainer action and is not part of this PR.
How Has This Been Tested?
test_non_utf8_body_returns_parse_errorintests/server/test_streamable_http_manager.py: POSTs a Windows-1252 body and asserts HTTP 400, JSON-RPC code-32700, and zero ERROR-level log records. Verified it fails on the currentv1.xtip (assert <HTTPStatus.INTERNAL_SERVER_ERROR: 500> == 400, plus the captured ERROR traceback) and passes with the fix.test_json_validationintests/shared/test_streamable_http.pybecause that file's server fixture runs in a separate process, wherecaplogcannot observe the server-side records this fix is meant to eliminate. Happy to add an HTTP-level test there too if you'd prefer it alongside the existing parse tests.uv run --frozen pytest— 1152 passed, 95 skipped, 1 xfailed.uv run --frozen ruff check .clean;ruff format .reports no changes;uv run --frozen pyright0 errors.-32700, with zero ERROR records.Breaking Changes
None. A request that previously produced HTTP 500
INTERNAL_ERRORnow produces HTTP 400PARSE_ERROR; no successful request changes behavior.Types of changes
Checklist
Additional context
Targets
v1.xrather thanmainper the CONTRIBUTING branch table (non-breaking bug fixes for v1), and becausemainand the 2.0.0 pre-releases already have the corrected behavior via #1912.Scope is deliberately limited to the Streamable HTTP POST path in #3150. #3142 tracks a related report in the same ERROR-cascade family and is not addressed here.