From d126a53a287d7bd5eeb1eee3534b359e213228bc Mon Sep 17 00:00:00 2001 From: Sayali Kulkarni <144113494+sk-20231@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:57:19 +0530 Subject: [PATCH 1/3] Return 400 for unreadable strings in Streamable HTTP POST validation 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 #1984 --- .../StreamableHttpHandler.cs | 81 +++++++++--- .../HttpHeaderConformanceTests.cs | 119 ++++++++++++++++++ 2 files changed, 185 insertions(+), 15 deletions(-) diff --git a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs index 3808a43fa..958f074a9 100644 --- a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs +++ b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs @@ -895,13 +895,23 @@ private static bool ValidateProtocolVersionEnvelope( if (message is JsonRpcRequest { Method: RequestMethods.Initialize, Params: JsonObject initializeParams } && initializeParams["protocolVersion"] is JsonValue initializeProtocolVersionValue && - initializeProtocolVersionValue.TryGetValue(out string? initializeProtocolVersion) && - !string.IsNullOrEmpty(protocolVersionHeader) && - !string.Equals(protocolVersionHeader, initializeProtocolVersion, StringComparison.Ordinal)) + initializeProtocolVersionValue.GetValueKind() == JsonValueKind.String && + !string.IsNullOrEmpty(protocolVersionHeader)) { - errorDetail = CreateHeaderMismatchError( - $"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)) + { + errorDetail = CreateHeaderMismatchError( + $"Bad Request: The body params.protocolVersion value is not valid UTF-8, so it does not match the {McpProtocolVersionHeaderName} header value '{protocolVersionHeader}'."); + return false; + } + + if (!string.Equals(protocolVersionHeader, initializeProtocolVersion, StringComparison.Ordinal)) + { + errorDetail = CreateHeaderMismatchError( + $"Bad Request: The {McpProtocolVersionHeaderName} header value '{protocolVersionHeader}' does not match body params.protocolVersion value '{initializeProtocolVersion}'."); + return false; + } } // Legacy headers leave reserved metadata opaque. Without a header, let the core server resolve @@ -965,8 +975,7 @@ private static bool TryGetProtocolVersionMeta(JsonRpcMessage message, [NotNullWh string? value = null; if (parameters is JsonObject paramsObj && paramsObj["_meta"] is JsonObject metaObj && - metaObj[MetaKeys.ProtocolVersion] is JsonValue protocolVersionValue && - protocolVersionValue.TryGetValue(out value) && + TryGetStringValue(metaObj[MetaKeys.ProtocolVersion], out value) && !string.IsNullOrEmpty(value)) { protocolVersion = value; @@ -1097,7 +1106,11 @@ internal static bool ValidateMcpHeaders(HttpContext context, JsonRpcMessage mess JsonRpcNotification notification => notification.Params, _ => null, }; - 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}'."; + return false; + } // Check that the header value matches the body value if the body value is present. if (!string.Equals(decodedMcpNameInHeader, mcpNameInBody, StringComparison.Ordinal)) @@ -1167,8 +1180,9 @@ private static bool ValidateCustomParamHeaders( } // Look up the tool to check for x-mcp-header annotations in the schema - var toolName = GetJsonNodeStringProperty(bodyParams, "name"); - if (toolName is null || toolCollection is null || !toolCollection.TryGetPrimitive(toolName, out var tool)) + // An unreadable name was already rejected by the Mcp-Name check, so it can be skipped here. + if (!TryGetJsonNodeStringProperty(bodyParams, "name", out var toolName) || + toolName is null || toolCollection is null || !toolCollection.TryGetPrimitive(toolName, out var tool)) { errorMessage = null; return true; @@ -1281,6 +1295,13 @@ argForMissing is not null && argsObj.TryGetPropertyValue(property.Name, out var argNode) && argNode is not null) { + // ConvertToHeaderValue converts string arguments to .NET strings, which throws for invalid UTF-8. + if (argNode.GetValueKind() == JsonValueKind.String && !TryGetStringValue(argNode, out _)) + { + errorMessage = $"Header mismatch: body argument '{property.Name}' is not valid UTF-8, so it cannot match the {fullHeaderName} header."; + return false; + } + var expectedHeaderValue = McpHeaderEncoder.ConvertToHeaderValue(argNode); if (expectedHeaderValue is not null) { @@ -1302,14 +1323,44 @@ argForMissing is not null && return true; } - private static string? GetJsonNodeStringProperty(System.Text.Json.Nodes.JsonNode? node, string propertyName) + /// + /// Reads an optional string property of a JSON object without throwing. Returns with a + /// value when the node is not an object, or when the property is absent or JSON null. + /// Returns when the property is present but is not a readable string. + /// + 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) + { + return TryGetStringValue(propertyValue, out value); + } + + value = null; + return true; + } + + /// + /// Reads a JSON string value without throwing. Returns when the node is not a JSON string, + /// or when the string is not valid UTF-8. System.Text.Json validates the UTF-8 inside a string token only when it + /// converts the token to a .NET string, and it throws at that point. + /// + private static bool TryGetStringValue(JsonNode? node, [NotNullWhen(true)] out string? value) { - if (node is System.Text.Json.Nodes.JsonObject obj && obj.TryGetPropertyValue(propertyName, out var value)) + if (node is JsonValue jsonValue && jsonValue.GetValueKind() == JsonValueKind.String) { - return value?.GetValue(); + try + { + value = jsonValue.GetValue(); + return true; + } + catch (InvalidOperationException) + { + // The string is not valid UTF-8. Treat it the same as a value that is not a string. + } } - return null; + value = null; + return false; } // Valid HTTP header field-value characters per RFC 9110: horizontal tab (0x09), diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs index 914b98db0..40fb57dd0 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs @@ -519,6 +519,102 @@ public async Task Server_RejectsInvalidUtf8EncodedHeaderValue() Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); } + [Fact] + public async Task Server_RejectsInvalidUtf8InProtocolVersionMeta_WithBadRequest() + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // The 0xFF byte can never appear in valid UTF-8. The JSON reader accepts it inside a string token, + // and the failure only surfaces when the server converts the _meta protocol version to a string. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28", + "\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}"); + request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); + request.Headers.Add("Mcp-Method", "tools/list"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidParams, expectedId: 2); + } + + [Fact] + public async Task Server_RejectsInvalidUtf8InInitializeProtocolVersion_WithBadRequest() + { + await StartAsync(); + + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25", + "\",\"capabilities\":{},\"clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"}}}"); + request.Headers.Add("MCP-Protocol-Version", "2025-11-25"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 1); + } + + [Fact] + public async Task Server_RejectsInvalidUtf8InMcpNameBodyValue_WithBadRequest() + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // The Mcp-Name header is compared with params.name, which is converted to a string first. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"header_test", + "\",\"arguments\":{},\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}"); + request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); + request.Headers.Add("Mcp-Method", "tools/call"); + request.Headers.Add("Mcp-Name", "header_test"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 2); + } + + [Fact] + public async Task Server_RejectsInvalidUtf8InCustomParamHeaderArgument_WithBadRequest() + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // The region argument is annotated with x-mcp-header, so it is converted to a string and compared + // with the Mcp-Param-Region header. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"header_test\",\"arguments\":{\"region\":\"us-west1", + "\",\"priority\":42,\"verbose\":false,\"emptyVal\":\"\"},\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}"); + request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); + request.Headers.Add("Mcp-Method", "tools/call"); + request.Headers.Add("Mcp-Name", "header_test"); + request.Headers.Add("Mcp-Param-Region", "us-west1"); + request.Headers.Add("Mcp-Param-Priority", "42"); + request.Headers.Add("Mcp-Param-Verbose", "false"); + request.Headers.Add("Mcp-Param-EmptyVal", ""); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 2); + } + + [Fact] + public async Task Server_RejectsNonStringMcpNameBodyValue_WithBadRequest() + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // params.name is a number, so converting it to a string for the Mcp-Name comparison fails. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContent(""" + {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":5,"arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"TestClient","version":"1.0"},"io.modelcontextprotocol/clientCapabilities":{}}}} + """); + request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); + request.Headers.Add("Mcp-Method", "tools/call"); + request.Headers.Add("Mcp-Name", "5"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 2); + } + #endregion #region Client-side encoding tests (unit tests for McpHeaderEncoder) @@ -629,6 +725,29 @@ private async Task InitializeWithInitializeHandshakeVersionAsync() private static StringContent JsonContent(string json) => new(json, Encoding.UTF8, "application/json"); + /// + /// Asserts a 400 response whose JSON-RPC error has the expected code and echoes the request id. + /// + private static async Task AssertJsonRpcErrorAsync(HttpResponseMessage response, McpErrorCode expectedCode, long expectedId) + { + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + var json = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken))!; + Assert.Equal((int)expectedCode, json["error"]!["code"]!.GetValue()); + Assert.Equal(expectedId, json["id"]!.GetValue()); + } + + /// + /// Builds a JSON body that is + a single 0xFF byte + , + /// so the body contains a string value that is not valid UTF-8. + /// + private static ByteArrayContent JsonContentWithInvalidUtf8(string before, string after) + { + byte[] body = [.. Encoding.UTF8.GetBytes(before), 0xFF, .. Encoding.UTF8.GetBytes(after)]; + var content = new ByteArrayContent(body); + content.Headers.ContentType = new("application/json") { CharSet = "utf-8" }; + return content; + } + private long _lastRequestId = 1; private string CallTool(string toolName, string arguments = "{}", bool includePerRequestMetadata = true) From 7def5fd5e9f19c39eef151d1552607da6369a18f Mon Sep 17 00:00:00 2001 From: Sayali Kulkarni <144113494+sk-20231@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:21:13 +0530 Subject: [PATCH 2/3] Catch unreadable request values once around Streamable HTTP validation Address review feedback on #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 #1932 covers. --- .../StreamableHttpHandler.cs | 132 +++++++------- .../Server/McpServerImpl.cs | 40 ++++- .../HttpHeaderConformanceTests.cs | 161 +++++++++++++++--- 3 files changed, 232 insertions(+), 101 deletions(-) diff --git a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs index 958f074a9..dbb0930c3 100644 --- a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs +++ b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs @@ -118,21 +118,29 @@ await WriteJsonRpcErrorAsync(context, return; } - if (!ValidateProtocolVersionEnvelope(context, message, out var protocolVersionEnvelopeError)) + // The body parsed successfully, but reading its values can still throw InvalidOperationException: + // System.Text.Json checks the UTF-8 in a string only when it converts the string to a .NET string, + // the first lookup in a JsonObject converts all of that object's property names, and reading a + // non-string value as a string throws too. These are malformed requests, not server errors, so + // they get a 400 that echoes the request id instead of an HTTP 500. The error is written after + // the try block, so an exception from writing the response is never caught here. + JsonRpcErrorDetail? requestValidationError; + try { - await WriteJsonRpcErrorDetailAsync(context, protocolVersionEnvelopeError, StatusCodes.Status400BadRequest, requestId); - return; + requestValidationError = ValidateRequestEnvelopeAndHeaders(context, message, mcpServerOptionsSnapshot.Value); } - - if (!ValidateMcpHeaders(context, message, mcpServerOptionsSnapshot.Value, out var errorMessage)) + catch (InvalidOperationException ex) { - await WriteJsonRpcErrorAsync(context, errorMessage, StatusCodes.Status400BadRequest, (int)McpErrorCode.HeaderMismatch, requestId); - return; + requestValidationError = new() + { + Code = (int)McpErrorCode.InvalidRequest, + Message = $"Bad Request: The request contains a value that could not be read: {ex.Message}", + }; } - if (!ValidateRequiredPerRequestMeta(context, message, out var requiredMetaError)) + if (requestValidationError is not null) { - await WriteJsonRpcErrorDetailAsync(context, requiredMetaError, StatusCodes.Status400BadRequest, requestId); + await WriteJsonRpcErrorDetailAsync(context, requestValidationError, StatusCodes.Status400BadRequest, requestId); return; } @@ -895,23 +903,13 @@ private static bool ValidateProtocolVersionEnvelope( if (message is JsonRpcRequest { Method: RequestMethods.Initialize, Params: JsonObject initializeParams } && initializeParams["protocolVersion"] is JsonValue initializeProtocolVersionValue && - initializeProtocolVersionValue.GetValueKind() == JsonValueKind.String && - !string.IsNullOrEmpty(protocolVersionHeader)) + initializeProtocolVersionValue.TryGetValue(out string? initializeProtocolVersion) && + !string.IsNullOrEmpty(protocolVersionHeader) && + !string.Equals(protocolVersionHeader, initializeProtocolVersion, StringComparison.Ordinal)) { - // 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)) - { - errorDetail = CreateHeaderMismatchError( - $"Bad Request: The body params.protocolVersion value is not valid UTF-8, so it does not match the {McpProtocolVersionHeaderName} header value '{protocolVersionHeader}'."); - return false; - } - - if (!string.Equals(protocolVersionHeader, initializeProtocolVersion, StringComparison.Ordinal)) - { - errorDetail = CreateHeaderMismatchError( - $"Bad Request: The {McpProtocolVersionHeaderName} header value '{protocolVersionHeader}' does not match body params.protocolVersion value '{initializeProtocolVersion}'."); - return false; - } + errorDetail = CreateHeaderMismatchError( + $"Bad Request: The {McpProtocolVersionHeaderName} header value '{protocolVersionHeader}' does not match body params.protocolVersion value '{initializeProtocolVersion}'."); + return false; } // Legacy headers leave reserved metadata opaque. Without a header, let the core server resolve @@ -975,7 +973,8 @@ private static bool TryGetProtocolVersionMeta(JsonRpcMessage message, [NotNullWh string? value = null; if (parameters is JsonObject paramsObj && paramsObj["_meta"] is JsonObject metaObj && - TryGetStringValue(metaObj[MetaKeys.ProtocolVersion], out value) && + metaObj[MetaKeys.ProtocolVersion] is JsonValue protocolVersionValue && + protocolVersionValue.TryGetValue(out value) && !string.IsNullOrEmpty(value)) { protocolVersion = value; @@ -1106,11 +1105,7 @@ internal static bool ValidateMcpHeaders(HttpContext context, JsonRpcMessage mess JsonRpcNotification notification => notification.Params, _ => null, }; - 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}'."; - return false; - } + var mcpNameInBody = GetJsonNodeStringProperty(bodyParams, routingNameParameter); // Check that the header value matches the body value if the body value is present. if (!string.Equals(decodedMcpNameInHeader, mcpNameInBody, StringComparison.Ordinal)) @@ -1180,9 +1175,8 @@ private static bool ValidateCustomParamHeaders( } // Look up the tool to check for x-mcp-header annotations in the schema - // An unreadable name was already rejected by the Mcp-Name check, so it can be skipped here. - if (!TryGetJsonNodeStringProperty(bodyParams, "name", out var toolName) || - toolName is null || toolCollection is null || !toolCollection.TryGetPrimitive(toolName, out var tool)) + var toolName = GetJsonNodeStringProperty(bodyParams, "name"); + if (toolName is null || toolCollection is null || !toolCollection.TryGetPrimitive(toolName, out var tool)) { errorMessage = null; return true; @@ -1295,13 +1289,6 @@ argForMissing is not null && argsObj.TryGetPropertyValue(property.Name, out var argNode) && argNode is not null) { - // ConvertToHeaderValue converts string arguments to .NET strings, which throws for invalid UTF-8. - if (argNode.GetValueKind() == JsonValueKind.String && !TryGetStringValue(argNode, out _)) - { - errorMessage = $"Header mismatch: body argument '{property.Name}' is not valid UTF-8, so it cannot match the {fullHeaderName} header."; - return false; - } - var expectedHeaderValue = McpHeaderEncoder.ConvertToHeaderValue(argNode); if (expectedHeaderValue is not null) { @@ -1323,44 +1310,14 @@ argForMissing is not null && return true; } - /// - /// Reads an optional string property of a JSON object without throwing. Returns with a - /// value when the node is not an object, or when the property is absent or JSON null. - /// Returns when the property is present but is not a readable string. - /// - private static bool TryGetJsonNodeStringProperty(JsonNode? node, string propertyName, out string? value) + private static string? GetJsonNodeStringProperty(System.Text.Json.Nodes.JsonNode? node, string propertyName) { - if (node is JsonObject obj && obj.TryGetPropertyValue(propertyName, out var propertyValue) && propertyValue is not null) + if (node is System.Text.Json.Nodes.JsonObject obj && obj.TryGetPropertyValue(propertyName, out var value)) { - return TryGetStringValue(propertyValue, out value); + return value?.GetValue(); } - value = null; - return true; - } - - /// - /// Reads a JSON string value without throwing. Returns when the node is not a JSON string, - /// or when the string is not valid UTF-8. System.Text.Json validates the UTF-8 inside a string token only when it - /// converts the token to a .NET string, and it throws at that point. - /// - private static bool TryGetStringValue(JsonNode? node, [NotNullWhen(true)] out string? value) - { - if (node is JsonValue jsonValue && jsonValue.GetValueKind() == JsonValueKind.String) - { - try - { - value = jsonValue.GetValue(); - return true; - } - catch (InvalidOperationException) - { - // The string is not valid UTF-8. Treat it the same as a value that is not a string. - } - } - - value = null; - return false; + return null; } // Valid HTTP header field-value characters per RFC 9110: horizontal tab (0x09), @@ -1524,6 +1481,31 @@ private static SafeIntegerParse ParseSafeInteger(string text, out long value) return SafeIntegerParse.NotNumeric; } + /// + /// Runs the body checks that compare the JSON-RPC message with the request headers. Returns the first error, + /// or when the request passes. Can throw when + /// the body contains a value or property name that cannot be read; the caller maps that to a 400. + /// + private static JsonRpcErrorDetail? ValidateRequestEnvelopeAndHeaders(HttpContext context, JsonRpcMessage message, McpServerOptions serverOptions) + { + if (!ValidateProtocolVersionEnvelope(context, message, out var protocolVersionEnvelopeError)) + { + return protocolVersionEnvelopeError; + } + + if (!ValidateMcpHeaders(context, message, serverOptions, out var errorMessage)) + { + return new() { Code = (int)McpErrorCode.HeaderMismatch, Message = errorMessage }; + } + + if (!ValidateRequiredPerRequestMeta(context, message, out var requiredMetaError)) + { + return requiredMetaError; + } + + return null; + } + private static Task WriteJsonRpcErrorDetailAsync(HttpContext context, JsonRpcErrorDetail detail, int statusCode, RequestId requestId = default) { var jsonRpcError = new JsonRpcError { Id = requestId, Error = detail }; diff --git a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs index db11a84de..7d9ec824d 100644 --- a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs +++ b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs @@ -232,8 +232,7 @@ private void ReadRequestMetadata(JsonRpcRequest request) JsonObject? meta = request.Params is JsonObject paramsObj ? paramsObj["_meta"] as JsonObject : null; // An unreadable value cannot select a protocol; only the modern path requires a usable version. - string? metadataProtocolVersion = - meta?[MetaKeys.ProtocolVersion] is JsonValue value && value.TryGetValue(out string? version) ? version : null; + string? metadataProtocolVersion = ReadMetadataProtocolVersion(meta, out bool metadataProtocolVersionUnreadable); if (transportProtocolVersion is not null && metadataProtocolVersion is not null && @@ -301,12 +300,47 @@ transportProtocolVersion is not null || } // With no established era, warn in case a modern peer accidentally fell back to legacy handling. - if (metadataProtocolVersion is null && meta?.ContainsKey(MetaKeys.ProtocolVersion) is true) + if (metadataProtocolVersionUnreadable) { LogIgnoredUnreadableProtocolVersionMetadata(_endpointName, request.Method); } } + /// + /// Reads the protocol version from the request's _meta without throwing. Returns + /// when it is absent or cannot be read, and sets when it is present but not a + /// readable string. System.Text.Json throws when it converts a string + /// that is not valid UTF-8, and when a lookup meets a property name of the object that is not valid UTF-8. + /// + private static string? ReadMetadataProtocolVersion(JsonObject? meta, out bool unreadable) + { + unreadable = false; + if (meta is null) + { + return null; + } + + try + { + if (!meta.TryGetPropertyValue(MetaKeys.ProtocolVersion, out JsonNode? node)) + { + return null; + } + + if (node is JsonValue value && value.TryGetValue(out string? version)) + { + return version; + } + } + catch (InvalidOperationException) + { + // Not valid UTF-8 in the value or in a property name of _meta: handled below as unreadable. + } + + unreadable = true; + return null; + } + private static void ProjectModernMetadata(JsonRpcRequest request, JsonObject meta, string protocolVersion) { if (!meta.ContainsKey(MetaKeys.ClientCapabilities)) diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs index 40fb57dd0..152dbcef1 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs @@ -535,7 +535,7 @@ public async Task Server_RejectsInvalidUtf8InProtocolVersionMeta_WithBadRequest( request.Headers.Add("Mcp-Method", "tools/list"); using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); - await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidParams, expectedId: 2); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); } [Fact] @@ -550,7 +550,125 @@ public async Task Server_RejectsInvalidUtf8InInitializeProtocolVersion_WithBadRe request.Headers.Add("MCP-Protocol-Version", "2025-11-25"); using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); - await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 1); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 1); + } + + [Fact] + public async Task Server_RejectsInvalidUtf8PropertyNameInInitializeParams_WithBadRequest() + { + await StartAsync(); + + // Reading any property of a JSON object converts all of its property names to strings, + // so one unreadable name breaks the lookup of params.protocolVersion. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{},\"clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"x", + "\":1}}"); + request.Headers.Add("MCP-Protocol-Version", "2025-11-25"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 1); + } + + [Theory] + [InlineData("params")] + [InlineData("_meta")] + [InlineData("arguments")] + public async Task Server_RejectsInvalidUtf8PropertyName_WithBadRequest(string location) + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // Each body has one property name that is "x" followed by a 0xFF byte, placed in the named object. + // The other property names in that object are valid, but they cannot be read either. + const string Arguments = "\"region\":\"us-west1\",\"priority\":42,\"verbose\":false,\"emptyVal\":\"\""; + const string MetaEntries = "\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}"; + const string Start = "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{"; + (string before, string after) = location switch + { + "params" => ( + $"{Start}\"name\":\"header_test\",\"arguments\":{{{Arguments}}},\"_meta\":{{{MetaEntries}}},\"x", + "\":1}}"), + "_meta" => ( + $"{Start}\"name\":\"header_test\",\"arguments\":{{{Arguments}}},\"_meta\":{{{MetaEntries},\"x", + "\":1}}}"), + "arguments" => ( + $"{Start}\"name\":\"header_test\",\"arguments\":{{{Arguments},\"x", + $"\":1}},\"_meta\":{{{MetaEntries}}}}}}}"), + _ => throw new ArgumentOutOfRangeException(nameof(location)), + }; + + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8(before, after); + request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); + request.Headers.Add("Mcp-Method", "tools/call"); + request.Headers.Add("Mcp-Name", "header_test"); + request.Headers.Add("Mcp-Param-Region", "us-west1"); + request.Headers.Add("Mcp-Param-Priority", "42"); + request.Headers.Add("Mcp-Param-Verbose", "false"); + request.Headers.Add("Mcp-Param-EmptyVal", ""); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); + } + + [Fact] + public async Task Server_RejectsLoneSurrogateInMcpNameBodyValue_WithBadRequest() + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // An escaped lone surrogate is valid JSON text, but it cannot be converted to a valid string. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContent(""" + {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"\uD800","arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"TestClient","version":"1.0"},"io.modelcontextprotocol/clientCapabilities":{}}}} + """); + request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); + request.Headers.Add("Mcp-Method", "tools/call"); + request.Headers.Add("Mcp-Name", "header_test"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); + } + + [Fact] + public async Task Server_RejectsInvalidUtf8InCustomHandlerRoutingValue_WithBadRequest() + { + await StartAsync(); + await ProbeWithJuly2026ProtocolVersionAsync(); + + // The extension/get handler routes on params.itemId, which is compared with the Mcp-Name header. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"extension/get\",\"params\":{\"itemId\":\"item-42", + "\",\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}"); + request.Headers.Add(McpHttpHeaders.ProtocolVersion, "2026-07-28"); + request.Headers.Add(McpHttpHeaders.Method, "extension/get"); + request.Headers.Add(McpHttpHeaders.Name, "item-42"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); + } + + [Fact] + public async Task Server_TreatsInvalidUtf8ProtocolVersionMetaAsMissing_WithoutProtocolVersionHeader() + { + await StartAsync(); + + // Without the MCP-Protocol-Version header the core server reads the _meta protocol version. + // An unreadable value is treated as missing, so the request is served without per-request + // metadata instead of failing with an internal error. + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8( + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{\"_meta\":{\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28", + "\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}}}}"); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var rpcResponse = await ReadSseJsonRpcMessageAsync(response); + Assert.Null(rpcResponse["error"]); + Assert.NotNull(rpcResponse["result"]?["tools"]); + Assert.Equal(2, rpcResponse["id"]!.GetValue()); } [Fact] @@ -569,7 +687,7 @@ public async Task Server_RejectsInvalidUtf8InMcpNameBodyValue_WithBadRequest() request.Headers.Add("Mcp-Name", "header_test"); using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); - await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 2); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); } [Fact] @@ -593,26 +711,7 @@ public async Task Server_RejectsInvalidUtf8InCustomParamHeaderArgument_WithBadRe request.Headers.Add("Mcp-Param-EmptyVal", ""); using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); - await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 2); - } - - [Fact] - public async Task Server_RejectsNonStringMcpNameBodyValue_WithBadRequest() - { - await StartAsync(); - await ProbeWithJuly2026ProtocolVersionAsync(); - - // params.name is a number, so converting it to a string for the Mcp-Name comparison fails. - using var request = new HttpRequestMessage(HttpMethod.Post, ""); - request.Content = JsonContent(""" - {"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":5,"arguments":{},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientInfo":{"name":"TestClient","version":"1.0"},"io.modelcontextprotocol/clientCapabilities":{}}}} - """); - request.Headers.Add("MCP-Protocol-Version", "2026-07-28"); - request.Headers.Add("Mcp-Method", "tools/call"); - request.Headers.Add("Mcp-Name", "5"); - - using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); - await AssertJsonRpcErrorAsync(response, McpErrorCode.HeaderMismatch, expectedId: 2); + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); } #endregion @@ -736,6 +835,22 @@ private static async Task AssertJsonRpcErrorAsync(HttpResponseMessage response, Assert.Equal(expectedId, json["id"]!.GetValue()); } + /// + /// Reads the single JSON-RPC message from an SSE response. + /// + private static async Task ReadSseJsonRpcMessageAsync(HttpResponseMessage response) + { + var responseStream = await response.Content.ReadAsStreamAsync(TestContext.Current.CancellationToken); + List messages = []; + await foreach (var sseItem in SseParser.Create(responseStream).EnumerateAsync(TestContext.Current.CancellationToken)) + { + Assert.Equal("message", sseItem.EventType); + messages.Add(sseItem.Data); + } + + return JsonNode.Parse(Assert.Single(messages))!; + } + /// /// Builds a JSON body that is + a single 0xFF byte + , /// so the body contains a string value that is not valid UTF-8. From 675a3a72dcf25cc52ba06bfe86a9cdb99f503a72 Mon Sep 17 00:00:00 2001 From: Sayali Kulkarni <144113494+sk-20231@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:23:47 +0530 Subject: [PATCH 3/3] Treat unreadable params property names as missing metadata and return a fixed 400 message The _meta lookup in params now runs inside ReadMetadataProtocolVersion, so a property name in params that is not valid UTF-8 is handled like an unreadable _meta protocol version instead of failing with -32603. The catch in HandlePostRequestAsync logs the exception at Debug level and returns a fixed message, so text from an InvalidOperationException thrown by server-side code is never sent to the client. --- .../StreamableHttpHandler.cs | 12 +++++- .../Server/McpServerImpl.cs | 24 ++++++----- .../HttpHeaderConformanceTests.cs | 40 ++++++++++++++++++- 3 files changed, 62 insertions(+), 14 deletions(-) diff --git a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs index dbb0930c3..3fe06680a 100644 --- a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs +++ b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs @@ -18,7 +18,7 @@ namespace ModelContextProtocol.AspNetCore; -internal sealed class StreamableHttpHandler( +internal sealed partial class StreamableHttpHandler( IOptions mcpServerOptionsSnapshot, IOptionsFactory mcpServerOptionsFactory, IOptions httpServerTransportOptions, @@ -27,6 +27,8 @@ internal sealed class StreamableHttpHandler( IServiceProvider applicationServices, ILoggerFactory loggerFactory) { + private readonly ILogger _logger = loggerFactory.CreateLogger(); + private const string McpSessionIdHeaderName = McpHttpHeaders.SessionId; private const string McpProtocolVersionHeaderName = McpHttpHeaders.ProtocolVersion; private const string LastEventIdHeaderName = McpHttpHeaders.LastEventId; @@ -131,10 +133,13 @@ await WriteJsonRpcErrorAsync(context, } catch (InvalidOperationException ex) { + // Server-side code that runs during validation can throw this exception type too, so the cause + // is logged and the client gets a fixed message that reveals nothing about the server. + LogRequestValueCouldNotBeRead(ex); requestValidationError = new() { Code = (int)McpErrorCode.InvalidRequest, - Message = $"Bad Request: The request contains a value that could not be read: {ex.Message}", + Message = "Bad Request: The request contains a value that could not be read.", }; } @@ -1517,4 +1522,7 @@ private static bool MatchesApplicationJsonMediaType(MediaTypeHeaderValue acceptH private static bool MatchesTextEventStreamMediaType(MediaTypeHeaderValue acceptHeaderValue) => acceptHeaderValue.MatchesMediaType("text/event-stream"); + + [LoggerMessage(Level = LogLevel.Debug, Message = "Rejected a POST request with 400 Bad Request because a value in the request could not be read.")] + private partial void LogRequestValueCouldNotBeRead(Exception exception); } diff --git a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs index 7d9ec824d..1917032ab 100644 --- a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs +++ b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs @@ -230,9 +230,9 @@ private void ReadRequestMetadata(JsonRpcRequest request) return; } - JsonObject? meta = request.Params is JsonObject paramsObj ? paramsObj["_meta"] as JsonObject : null; // An unreadable value cannot select a protocol; only the modern path requires a usable version. - string? metadataProtocolVersion = ReadMetadataProtocolVersion(meta, out bool metadataProtocolVersionUnreadable); + string? metadataProtocolVersion = ReadMetadataProtocolVersion( + request, out JsonObject? meta, out bool metadataProtocolVersionUnreadable); if (transportProtocolVersion is not null && metadataProtocolVersion is not null && @@ -307,22 +307,26 @@ transportProtocolVersion is not null || } /// - /// Reads the protocol version from the request's _meta without throwing. Returns - /// when it is absent or cannot be read, and sets when it is present but not a - /// readable string. System.Text.Json throws when it converts a string - /// that is not valid UTF-8, and when a lookup meets a property name of the object that is not valid UTF-8. + /// Reads the request's _meta object and its protocol version without throwing. Returns + /// when the version is absent or cannot be read, and sets + /// when it cannot be read: the value is not a readable string, or params or _meta has a property + /// name that is not valid UTF-8. System.Text.Json throws when it + /// converts a string that is not valid UTF-8, and the first lookup in an object converts all of that object's + /// property names, so the _meta lookup in params must be inside the same try block. /// - private static string? ReadMetadataProtocolVersion(JsonObject? meta, out bool unreadable) + private static string? ReadMetadataProtocolVersion(JsonRpcRequest request, out JsonObject? meta, out bool unreadable) { + meta = null; unreadable = false; - if (meta is null) + if (request.Params is not JsonObject paramsObj) { return null; } try { - if (!meta.TryGetPropertyValue(MetaKeys.ProtocolVersion, out JsonNode? node)) + meta = paramsObj["_meta"] as JsonObject; + if (meta is null || !meta.TryGetPropertyValue(MetaKeys.ProtocolVersion, out JsonNode? node)) { return null; } @@ -334,7 +338,7 @@ transportProtocolVersion is not null || } catch (InvalidOperationException) { - // Not valid UTF-8 in the value or in a property name of _meta: handled below as unreadable. + // Not valid UTF-8 in the value, or in a property name of params or _meta: handled below as unreadable. } unreadable = true; diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs index 152dbcef1..0a7ed991f 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs @@ -609,7 +609,9 @@ public async Task Server_RejectsInvalidUtf8PropertyName_WithBadRequest(string lo request.Headers.Add("Mcp-Param-EmptyVal", ""); using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); - await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2); + // The message is fixed: it must not repeat the exception text, which can describe server internals. + await AssertJsonRpcErrorAsync(response, McpErrorCode.InvalidRequest, expectedId: 2, + expectedMessage: "Bad Request: The request contains a value that could not be read."); } [Fact] @@ -671,6 +673,36 @@ public async Task Server_TreatsInvalidUtf8ProtocolVersionMetaAsMissing_WithoutPr Assert.Equal(2, rpcResponse["id"]!.GetValue()); } + [Theory] + [InlineData("params")] + [InlineData("_meta")] + public async Task Server_TreatsInvalidUtf8PropertyNameAsMissingMetadata_WithoutProtocolVersionHeader(string location) + { + await StartAsync(); + + // Without the MCP-Protocol-Version header the core server looks up _meta in params and the protocol + // version in _meta. One property name that is "x" followed by a 0xFF byte makes every lookup in + // that object fail, so the metadata is treated as missing instead of failing with an internal error. + const string MetaEntries = "\"io.modelcontextprotocol/protocolVersion\":\"2026-07-28\",\"io.modelcontextprotocol/clientInfo\":{\"name\":\"TestClient\",\"version\":\"1.0\"},\"io.modelcontextprotocol/clientCapabilities\":{}"; + const string Start = "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{"; + (string before, string after) = location switch + { + "params" => ($"{Start}\"_meta\":{{{MetaEntries}}},\"x", "\":1}}"), + "_meta" => ($"{Start}\"_meta\":{{{MetaEntries},\"x", "\":1}}}"), + _ => throw new ArgumentOutOfRangeException(nameof(location)), + }; + + using var request = new HttpRequestMessage(HttpMethod.Post, ""); + request.Content = JsonContentWithInvalidUtf8(before, after); + + using var response = await HttpClient.SendAsync(request, TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + var rpcResponse = await ReadSseJsonRpcMessageAsync(response); + Assert.Null(rpcResponse["error"]); + Assert.NotNull(rpcResponse["result"]?["tools"]); + Assert.Equal(2, rpcResponse["id"]!.GetValue()); + } + [Fact] public async Task Server_RejectsInvalidUtf8InMcpNameBodyValue_WithBadRequest() { @@ -827,12 +859,16 @@ private async Task InitializeWithInitializeHandshakeVersionAsync() /// /// Asserts a 400 response whose JSON-RPC error has the expected code and echoes the request id. /// - private static async Task AssertJsonRpcErrorAsync(HttpResponseMessage response, McpErrorCode expectedCode, long expectedId) + private static async Task AssertJsonRpcErrorAsync(HttpResponseMessage response, McpErrorCode expectedCode, long expectedId, string? expectedMessage = null) { Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var json = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken))!; Assert.Equal((int)expectedCode, json["error"]!["code"]!.GetValue()); Assert.Equal(expectedId, json["id"]!.GetValue()); + if (expectedMessage is not null) + { + Assert.Equal(expectedMessage, json["error"]!["message"]!.GetValue()); + } } ///