Skip to content

Return ParseError (-32700) for malformed JSON on Streamable HTTP POST - #2046

Open
jhrabchak wants to merge 2 commits into
modelcontextprotocol:mainfrom
jhrabchak:fix/issue-1918
Open

jhrabchak wants to merge 2 commits into
modelcontextprotocol:mainfrom
jhrabchak:fix/issue-1918

Conversation

@jhrabchak

Copy link
Copy Markdown

Fixes #1918

Previously, StreamableHttpHandler.HandlePostRequestAsync caught all JsonExceptions from ReadJsonRpcMessageAsync and returned McpErrorCode.InvalidRequest (-32600), whether the failure was invalid JSON syntax or a valid JSON document that failed JSON-RPC envelope validation.

Changes

  • Parse the POST body into a JsonElement first (reusing the existing source-generated JsonTypeInfo<JsonElement> in McpJsonUtilities.ProtocolOptions), returning HTTP 400 with McpErrorCode.ParseError (-32700) and id: null when JSON parsing fails while preserving the parser error detail from Surface JSON parse detail in streamable-HTTP 400 responses #1844.
  • Deserialize JsonRpcMessage from the parsed JsonElement in a second step so invalid JSON-RPC envelopes (such as null, [], {}, wrong jsonrpc version, or explicit id: null) continue returning McpErrorCode.InvalidRequest (-32600).
  • Update the malformed and truncated JSON conformance tests to assert -32700, and add tests confirming invalid JSON-RPC envelopes still return -32600.

Fixes modelcontextprotocol#1918

In StreamableHttpHandler.HandlePostRequestAsync, parse the POST body
into a JsonElement first using the existing source-generated
JsonTypeInfo<JsonElement> contract, and deserialize JsonRpcMessage from
that element in a second step.

- Invalid JSON syntax (truncated payloads, malformed tokens, exceeded
  max depth) now returns HTTP 400 with McpErrorCode.ParseError (-32700)
  and a null id per JSON-RPC 2.0 section 5.1, while keeping the parser
  diagnostic message from modelcontextprotocol#1844.
- Valid JSON that is not a valid JSON-RPC 2.0 message (e.g., null, [],
  {}, invalid jsonrpc version, or explicit id: null) continues to return
  HTTP 400 with McpErrorCode.InvalidRequest (-32600).

@chrikrah chrikrah left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jhrabchak Broken JSON now gets -32700 and a bad envelope keeps -32600; nothing here blocks a merge.

# git archive 717fd18 (base 90476da), .NET SDK 10.0.403
$ dotnet test tests/ModelContextProtocol.AspNetCore.Tests -f net10.0
Passed!  - Failed: 0, Passed: 759, Skipped: 45, Total: 804

# StreamableHttpHandler.cs from 90476da, tests kept, same command
Failed!  - Failed: 4, Passed: 730, Skipped: 70, Total: 804
PostMalformedJson_Returns400_ParseError_WithNullId and 3 PostTruncatedJson cases: Expected -32700, Actual -32600

non-blocking: the JsonElement step doubles each POST's allocations:

# GC.GetAllocatedBytesForCurrentThread, one parse of a 1 MB tools/call body from a MemoryStream
base, DeserializeAsync<JsonRpcMessage>           1,049,256 B
this PR, JsonElement then Deserialize            2,098,264 B
using JsonDocument.ParseAsync, then Deserialize  1,049,400 B

A disposed JsonDocument gets the split for free, as long as the Content-Type check ReadFromJsonAsync does today stays. Want to fold that in here?

@jhrabchak

Copy link
Copy Markdown
Author

@chrikrah Thanks for the review and allocation breakdown! I've folded the JsonDocument.ParseAsync change into commit d40d6f7 (keeping HasJsonContentType() and s_messageTypeInfo.Options for JsonDocumentOptions, and disposing the JsonDocument right after Deserialize).

ModelContextProtocol.AspNetCore.Tests passes on net10.0 (759 passed, 0 failed, 45 skipped). Note: I also updated GetJsonRpcMessageParseErrorAsync in StreamableHttpServerConformanceTests to use JsonDocument.ParseAsync since it omits the Path: segment that JsonSerializer.DeserializeAsync adds to JsonException.Message while still reporting LineNumber and BytePositionInLine.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Streamable HTTP returns -32600 instead of -32700 for malformed JSON

2 participants