Repository navigation
Conversation
The JSON reader does not validate UTF-8 inside string tokens. That only happens when a token is converted to a .NET string, which throws InvalidOperationException. Converting a non-string value to a string throws the same exception. HandlePostRequestAsync only catches JsonException, so these requests returned 500. Read these values with a helper that returns false instead of throwing, and reject them with the error each check already uses: - initialize params.protocolVersion: 400, HeaderMismatch (-32020) - _meta protocolVersion: treated as missing, 400, InvalidParams (-32602) - Mcp-Name body value (invalid UTF-8 or not a string): 400, HeaderMismatch - x-mcp-header argument values: 400, HeaderMismatch All responses echo the request id. Fixes modelcontextprotocol#1984
|
Hi @tarekgh, a gentle reminder about this PR when you have time. It is ready for review. Because this is my first contribution, the CI workflows are waiting for a maintainer to approve them, so they have not run yet. I am happy to make any changes. Thank you! |
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues remain for the change to reject unreadable Streamable HTTP POST string values with HTTP 400.
No open issues 🎉
What changed in this PR
This PR addresses #1984 by making Streamable HTTP POST validation return HTTP 400 instead of 500 for unreadable string values, without changing public APIs.
Changes:
- Adds safe string-reading helpers for protocol-version metadata, routing names, and custom header arguments.
- Preserves field-specific error codes and echoed request IDs.
- Adds five regression tests covering invalid UTF-8 and non-string routing names.
| File | Description |
|---|---|
| tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs | Adds regression tests asserting HTTP 400, error codes, and echoed request IDs. |
| src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs | Safely rejects unreadable strings during protocol-version and header validation. |
Review effort: Balanced
There was a problem hiding this comment.
Thanks for working on this. The fix handles invalid UTF-8 in string values, but some closely related inputs still produce a 500, and the same bug class exists outside this file. Summary:
1. Invalid UTF-8 in a property name still returns 500. Utf8JsonReader does not validate UTF-8 in property names, so the body parses and params stays a lazy JsonNode. The first indexer or TryGetPropertyValue call on a JsonObject runs JsonObject.InitializeDictionary(), which transcodes every key in that object. One bad sibling key, for example {"\xFF":1,"_meta":{...}}, throws InvalidOperationException even though the looked up name is valid. I confirmed 500 responses with a bad key in params, in _meta, in arguments, and in initialize params. Stack trace:
JsonDocument.GetString
JsonObject.InitializeDictionary()
JsonObject.GetItem(String propertyName)
StreamableHttpHandler.TryGetProtocolVersionMeta
StreamableHttpHandler.ValidateProtocolVersionEnvelope
StreamableHttpHandler.HandlePostRequestAsync
Suggestion: catch InvalidOperationException once around the validation block in HandlePostRequestAsync (the ValidateProtocolVersionEnvelope, ValidateMcpHeaders and ValidateRequiredPerRequestMeta calls) and map it to 400 / -32600. That covers keys and values at every current and future lookup site, and most of the per-value helpers would no longer be needed.
2. The same issue exists in core. McpServerImpl.ReadRequestMetadata uses JsonValue.TryGetValue(out string), which throws for invalid UTF-8 instead of returning false. With no MCP-Protocol-Version header and an invalid UTF-8 _meta protocolVersion, the client gets -32603 "An error occurred.", although the comment there says an unreadable value should be treated as missing. Other GetValue<string> uses in core (McpSessionHandler, McpServerImpl, McpTasksBuilderExtensions, McpHeaderEncoder) may need the same review.
3. Legacy header path. With a legacy protocol version header, ValidateMcpHeaders is skipped, and an invalid UTF-8 tool name reaches tool lookup with the bad bytes replaced by U+FFFD (Unknown tool: 'header_test\uFFFD'). It doesn't crash, but it is handled differently from the modern header path.
| paramsObj["_meta"] is JsonObject metaObj && | ||
| metaObj[MetaKeys.ProtocolVersion] is JsonValue protocolVersionValue && | ||
| protocolVersionValue.TryGetValue(out value) && | ||
| TryGetStringValue(metaObj[MetaKeys.ProtocolVersion], out value) && |
There was a problem hiding this comment.
paramsObj["_meta"] on the line above, and metaObj[...] here, can still throw InvalidOperationException when any key in params or _meta contains invalid UTF-8, because the indexer materializes and transcodes all keys of the object. I confirmed this returns 500.
Also, when TryGetStringValue returns false here because the value is unreadable, the caller reports that requests must include '_meta/io.modelcontextprotocol/protocolVersion'. That is misleading when the field is present but not valid UTF-8. Consider a separate message for that case.
| $"Bad Request: The {McpProtocolVersionHeaderName} header value '{protocolVersionHeader}' does not match body params.protocolVersion value '{initializeProtocolVersion}'."); | ||
| return false; | ||
| // A string that is not valid UTF-8 cannot equal any header value, so it is a mismatch too. | ||
| if (!TryGetStringValue(initializeProtocolVersionValue, out var initializeProtocolVersion)) |
There was a problem hiding this comment.
This path is only reached when initializeParams["protocolVersion"] succeeds. If any other key in the initialize params has invalid UTF-8, that indexer throws InvalidOperationException first and the request still returns 500. I confirmed this.
| /// </summary> | ||
| private static bool TryGetJsonNodeStringProperty(JsonNode? node, string propertyName, out string? value) | ||
| { | ||
| if (node is JsonObject obj && obj.TryGetPropertyValue(propertyName, out var propertyValue) && propertyValue is not null) |
There was a problem hiding this comment.
obj.TryGetPropertyValue can itself throw InvalidOperationException when any key in the object contains invalid UTF-8, so this helper is not fully non-throwing. The same applies to paramsObj.TryGetPropertyValue("arguments", ...) in ValidateCustomParamHeaders and argsObj.TryGetPropertyValue(property.Name, ...) in ValidateCustomParamHeadersFromProperties. A bad key inside arguments returns 500. One catch around the validation calls in HandlePostRequestAsync would cover all of these.
| var mcpNameInBody = GetJsonNodeStringProperty(bodyParams, routingNameParameter); | ||
| if (!TryGetJsonNodeStringProperty(bodyParams, routingNameParameter, out var mcpNameInBody)) | ||
| { | ||
| errorMessage = $"Header mismatch: body value '{routingNameParameter}' is not a valid string, so it cannot match the Mcp-Name header value '{mcpNameInHeader}'."; |
There was a problem hiding this comment.
Nit: a body name that is not a string, or not readable, is a malformed request rather than a header/body disagreement. InvalidParams (-32602) or InvalidRequest (-32600) may fit better than HeaderMismatch (-32020) here.
| } | ||
|
|
||
| [Fact] | ||
| public async Task Server_RejectsInvalidUtf8InProtocolVersionMeta_WithBadRequest() |
There was a problem hiding this comment.
Suggested additional tests:
- An escaped lone surrogate (
"\uD800") inname. It is handled through the same catch, but nothing covers it. - Invalid UTF-8 in a property name inside
params,_meta,argumentsandinitializeparams. These currently return 500. - Invalid UTF-8 in an extension routing parameter such as
itemId. - Invalid UTF-8
_metaprotocolVersion without the protocol version header, which goes throughMcpServerImpl.ReadRequestMetadata.
Address review feedback on modelcontextprotocol#2014: - Run the protocol version envelope, Mcp-* header and per-request _meta checks through one helper, and map an InvalidOperationException from it to 400 / -32600 with the request id. This covers invalid UTF-8 in property names as well as in values, at every lookup in those checks, so the per-value helpers are removed and the original lookups restored. - Treat an unreadable _meta protocol version as missing in McpServerImpl.ReadRequestMetadata, as its comment says, instead of failing with -32603. - Add tests for invalid UTF-8 property names in params, _meta, arguments and initialize params, an escaped lone surrogate in name, invalid UTF-8 in a custom handler routing value, and an unreadable _meta protocol version without the protocol version header. Remove the non-string name test, which modelcontextprotocol#1932 covers.
|
Thanks for the detailed review, @tarekgh. I pushed 7def5fd with these changes:
New tests cover the cases from your list: an escaped lone surrogate in Two more notes:
Note I used an AI assistant (Claude Code) to help make these changes. The build and tests were run locally. |
Fixes #1984
Problem
The body of a Streamable HTTP POST is parsed into a JSON-RPC message, but
paramsstays a lazyJsonNode. WhileHandlePostRequestAsyncvalidates the headers against the body, reading values from it can throwInvalidOperationException, which the handler did not catch (it only catchesJsonException), so the request returned 500:Utf8JsonReaderaccepts the bytes inside a string token and only validates them when the token is converted to a .NET string.JsonObjectconverts all of its property names, so one bad key makes the lookup of any other key in that object throw.JsonValue.GetValue<string>()rejects.The core server had the same problem: without an
MCP-Protocol-Versionheader, an invalid UTF-8_metaprotocol version failed inMcpServerImpl.ReadRequestMetadatawith -32603.Change
HandlePostRequestAsyncruns the protocol version envelope,Mcp-*header and per-request_metachecks through one helper,ValidateRequestEnvelopeAndHeaders. AnInvalidOperationExceptionfrom it becomes a 400 withInvalidRequest(-32600) and the request id. The error response is written after thetryblock. Errors that the checks already return are unchanged.McpServerImpl.ReadRequestMetadatatreats an unreadable_metaprotocol version as missing, as its comment says, and logs the existing "ignored unreadable protocol version" warning.Tests
In
HttpHeaderConformanceTests, each of these failed before the change (500, -32603, or a different error code):_metaprotocol version,initializeparams.protocolVersion, the body value compared withMcp-Name, anx-mcp-headerargument, and theitemIdrouting value of a custom handlerparams,_meta,argumentsandinitializeparams"\uD800") inname_metaprotocol version without the protocol version header (core path): the request is now servedLocal results (Release):
ModelContextProtocol.AspNetCore.Tests: net10.0 and net8.0, each 765 passed, 0 failed, 45 skippedModelContextProtocol.Tests: net10.0 and net8.0, each 3671 passed, 0 failed; net472, 3299 passed, 0 failedModelContextProtocol.AotCompatibility.TestApp: no IL warnings, app prints "Success!"Note
This PR was written with help from an AI coding assistant (Claude Code). The bug was reproduced and the build and tests were run locally.