Skip to content

Return 400 for unreadable strings in Streamable HTTP POST validation - #2014

Open
sk-20231 wants to merge 2 commits into
modelcontextprotocol:mainfrom
sk-20231:fix-invalid-utf8-500
Open

sk-20231 wants to merge 2 commits into
modelcontextprotocol:mainfrom
sk-20231:fix-invalid-utf8-500

Conversation

@sk-20231

@sk-20231 sk-20231 commented Nov 10, 2026 •

Copy link
Copy Markdown

Fixes #1984

Problem

The body of a Streamable HTTP POST is parsed into a JSON-RPC message, but params stays a lazy JsonNode. While HandlePostRequestAsync validates the headers against the body, reading values from it can throw InvalidOperationException, which the handler did not catch (it only catches JsonException), so the request returned 500:

  • Invalid UTF-8 in a string value. Utf8JsonReader accepts the bytes inside a string token and only validates them when the token is converted to a .NET string.
  • Invalid UTF-8 in a property name. The first lookup in a JsonObject converts all of its property names, so one bad key makes the lookup of any other key in that object throw.
  • A value that is not a string where a string is read, which JsonValue.GetValue<string>() rejects.

The core server had the same problem: without an MCP-Protocol-Version header, an invalid UTF-8 _meta protocol version failed in McpServerImpl.ReadRequestMetadata with -32603.

Change

  • HandlePostRequestAsync runs the protocol version envelope, Mcp-* header and per-request _meta checks through one helper, ValidateRequestEnvelopeAndHeaders. An InvalidOperationException from it becomes a 400 with InvalidRequest (-32600) and the request id. The error response is written after the try block. Errors that the checks already return are unchanged.
  • McpServerImpl.ReadRequestMetadata treats an unreadable _meta protocol version as missing, as its comment says, and logs the existing "ignored unreadable protocol version" warning.
  • No public API changes.

Tests

In HttpHeaderConformanceTests, each of these failed before the change (500, -32603, or a different error code):

  • Invalid UTF-8 values: _meta protocol version, initialize params.protocolVersion, the body value compared with Mcp-Name, an x-mcp-header argument, and the itemId routing value of a custom handler
  • Invalid UTF-8 property names in params, _meta, arguments and initialize params
  • An escaped lone surrogate ("\uD800") in name
  • An invalid UTF-8 _meta protocol version without the protocol version header (core path): the request is now served

Local results (Release):

  • Full solution build, Debug and Release: 0 errors, no new warnings
  • ModelContextProtocol.AspNetCore.Tests: net10.0 and net8.0, each 765 passed, 0 failed, 45 skipped
  • ModelContextProtocol.Tests: net10.0 and net8.0, each 3671 passed, 0 failed; net472, 3299 passed, 0 failed
  • Native AOT publish of ModelContextProtocol.AotCompatibility.TestApp: no IL warnings, app prints "Success!"
  • net9.0 was not run locally (runtime not installed)

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.

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
@halter73
halter73 requested a review from tarekgh November 11, 2026 21:34
@sk-20231

Copy link
Copy Markdown
Author

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!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 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

@tarekgh tarekgh left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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) &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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}'.";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested additional tests:

  • An escaped lone surrogate ("\uD800") in name. It is handled through the same catch, but nothing covers it.
  • Invalid UTF-8 in a property name inside params, _meta, arguments and initialize params. These currently return 500.
  • Invalid UTF-8 in an extension routing parameter such as itemId.
  • Invalid UTF-8 _meta protocolVersion without the protocol version header, which goes through McpServerImpl.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.
@sk-20231

Copy link
Copy Markdown
Author

Thanks for the detailed review, @tarekgh. I pushed 7def5fd with these changes:

  1. One catch around the validation block. HandlePostRequestAsync now runs ValidateProtocolVersionEnvelope, ValidateMcpHeaders and ValidateRequiredPerRequestMeta through one helper and maps an InvalidOperationException to 400 / -32600 with the request id. The error response is written after the try block, so an exception from writing the response is not caught there. I removed the per-value helpers and restored the original lookups. This also resolves the misleading "must include" message for an unreadable _meta protocol version and the -32020 code for a body name that cannot be read: both now get the -32600 error.
  2. Core. McpServerImpl.ReadRequestMetadata now treats an unreadable _meta protocol version as missing, as its comment says, and the existing "ignored unreadable protocol version" warning still logs it. Without the protocol version header, the request from your example is now served instead of returning -32603. I did not change the other GetValue<string> uses in core (McpSessionHandler, McpServerImpl, McpTasksBuilderExtensions, McpHeaderEncoder). On that path, an invalid UTF-8 property name in params also still returns -32603. Would you like those in this PR or in a follow-up? I am happy to do either.
  3. Legacy header path. No change yet. Should the legacy path also reject a tool name that is not valid UTF-8, or is the lookup with U+FFFD acceptable there?

New tests cover the cases from your list: an escaped lone surrogate in name; invalid UTF-8 property names in params, _meta, arguments and initialize params; invalid UTF-8 in the itemId routing value of a custom handler; and an invalid UTF-8 _meta protocol version without the protocol version header. Each one failed before the change (500, -32603, or the old error code).

Two more notes:

Note

I used an AI assistant (Claude Code) to help make these changes. The build and tests were run locally.

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.

Invalid UTF-8 in a request string returns 500 instead of 400 (Streamable HTTP)

3 participants