diff --git a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs index 3808a43fa..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; @@ -118,21 +120,32 @@ 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; + // 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.", + }; } - 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; } @@ -1473,6 +1486,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 }; @@ -1484,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 db11a84de..1917032ab 100644 --- a/src/ModelContextProtocol.Core/Server/McpServerImpl.cs +++ b/src/ModelContextProtocol.Core/Server/McpServerImpl.cs @@ -230,10 +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 = - meta?[MetaKeys.ProtocolVersion] is JsonValue value && value.TryGetValue(out string? version) ? version : null; + string? metadataProtocolVersion = ReadMetadataProtocolVersion( + request, out JsonObject? meta, out bool metadataProtocolVersionUnreadable); if (transportProtocolVersion is not null && metadataProtocolVersion is not null && @@ -301,12 +300,51 @@ 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 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(JsonRpcRequest request, out JsonObject? meta, out bool unreadable) + { + meta = null; + unreadable = false; + if (request.Params is not JsonObject paramsObj) + { + return null; + } + + try + { + meta = paramsObj["_meta"] as JsonObject; + if (meta is null || !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 params or _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 914b98db0..0a7ed991f 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/HttpHeaderConformanceTests.cs @@ -519,6 +519,233 @@ 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.InvalidRequest, 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.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); + // 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] + 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()); + } + + [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() + { + 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.InvalidRequest, 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.InvalidRequest, expectedId: 2); + } + #endregion #region Client-side encoding tests (unit tests for McpHeaderEncoder) @@ -629,6 +856,49 @@ 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, 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()); + } + } + + /// + /// 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. + /// + 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)