Repository navigation
Conversation
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
left a comment
There was a problem hiding this comment.
@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?
|
@chrikrah Thanks for the review and allocation breakdown! I've folded the
|
Fixes #1918
Previously,
StreamableHttpHandler.HandlePostRequestAsynccaught allJsonExceptions fromReadJsonRpcMessageAsyncand returnedMcpErrorCode.InvalidRequest(-32600), whether the failure was invalid JSON syntax or a valid JSON document that failed JSON-RPC envelope validation.Changes
JsonElementfirst (reusing the existing source-generatedJsonTypeInfo<JsonElement>inMcpJsonUtilities.ProtocolOptions), returning HTTP 400 withMcpErrorCode.ParseError(-32700) andid: nullwhen JSON parsing fails while preserving the parser error detail from Surface JSON parse detail in streamable-HTTP 400 responses #1844.JsonRpcMessagefrom the parsedJsonElementin a second step so invalid JSON-RPC envelopes (such asnull,[],{}, wrongjsonrpcversion, or explicitid: null) continue returningMcpErrorCode.InvalidRequest(-32600).-32700, and add tests confirming invalid JSON-RPC envelopes still return-32600.