diff --git a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs index 3808a43fa..0640fe4d0 100644 --- a/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs +++ b/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs @@ -80,19 +80,45 @@ await WriteJsonRpcErrorAsync(context, return; } + if (!context.Request.HasJsonContentType()) + { + throw new InvalidOperationException( + $"Unable to read the request as JSON because the request content type '{context.Request.ContentType}' is not a known JSON content type."); + } + JsonRpcMessage? message; try { - message = await ReadJsonRpcMessageAsync(context); + var documentOptions = new JsonDocumentOptions + { + AllowTrailingCommas = s_messageTypeInfo.Options.AllowTrailingCommas, + CommentHandling = s_messageTypeInfo.Options.ReadCommentHandling, + MaxDepth = s_messageTypeInfo.Options.MaxDepth, + }; + + using var document = await JsonDocument.ParseAsync(context.Request.Body, documentOptions, context.RequestAborted); + try + { + message = document.RootElement.Deserialize(s_messageTypeInfo); + } + catch (JsonException ex) + { + // The POST body was valid JSON, but not a valid JSON-RPC message (for example, missing + // the jsonrpc version or a request whose id was explicitly null, which MCP forbids). + // Per JSON-RPC 2.0 §5.1, invalid request objects map to -32600 (Invalid Request) with a null id. + await WriteJsonRpcErrorAsync(context, + $"Bad Request: The POST body did not contain a valid JSON-RPC message: {ex.Message}", + StatusCodes.Status400BadRequest, (int)McpErrorCode.InvalidRequest); + return; + } } catch (JsonException ex) { - // The POST body was not a well-formed JSON-RPC message (malformed JSON, or a request whose - // id was explicitly null, which MCP forbids). Surface a conformant JSON-RPC error response - // with a null id rather than letting the exception bubble up as an opaque 500. + // The POST body was not valid JSON (syntax error, truncation, max depth exceeded, etc.). + // Per JSON-RPC 2.0 §5.1, invalid JSON maps to -32700 (Parse error) with a null id. await WriteJsonRpcErrorAsync(context, $"Bad Request: The POST body did not contain a valid JSON-RPC message: {ex.Message}", - StatusCodes.Status400BadRequest, (int)McpErrorCode.InvalidRequest); + StatusCodes.Status400BadRequest, (int)McpErrorCode.ParseError); return; } @@ -104,6 +130,8 @@ await WriteJsonRpcErrorAsync(context, return; } + PopulateMessageContext(context, message); + // Once the body has been parsed into a request with a readable id, every JSON-RPC error response // for this request MUST echo that id (base protocol responses section; SEP-2243 error format). // Notifications carry no id, so this stays default (null), which is correct. @@ -712,26 +740,31 @@ internal static string MakeNewSessionId() if (message is not null) { - var protocolVersion = context.Request.Headers[McpProtocolVersionHeaderName].ToString(); - var isAuthenticated = context.User.Identities.Any(static identity => identity.IsAuthenticated); + PopulateMessageContext(context, message); + } - if (isAuthenticated || !string.IsNullOrEmpty(protocolVersion)) - { - message.Context ??= new(); + return message; + } - if (isAuthenticated) - { - message.Context.User = context.User; - } + private static void PopulateMessageContext(HttpContext context, JsonRpcMessage message) + { + var protocolVersion = context.Request.Headers[McpProtocolVersionHeaderName].ToString(); + var isAuthenticated = context.User.Identities.Any(static identity => identity.IsAuthenticated); - if (!string.IsNullOrEmpty(protocolVersion)) - { - message.Context.ProtocolVersion = protocolVersion; - } + if (isAuthenticated || !string.IsNullOrEmpty(protocolVersion)) + { + message.Context ??= new(); + + if (isAuthenticated) + { + message.Context.User = context.User; } - } - return message; + if (!string.IsNullOrEmpty(protocolVersion)) + { + message.Context.ProtocolVersion = protocolVersion; + } + } } internal static Task RunSessionAsync(HttpContext httpContext, McpServer session, CancellationToken requestAborted) diff --git a/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs b/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs index 8fbaa91b8..87534dd2f 100644 --- a/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs +++ b/tests/ModelContextProtocol.AspNetCore.Tests/StreamableHttpServerConformanceTests.cs @@ -303,7 +303,7 @@ public async Task StatelessPostWithSessionId_Returns400_EchoesRequestId() } [Fact] - public async Task PostMalformedJson_Returns400_InvalidRequest_WithNullId() + public async Task PostMalformedJson_Returns400_ParseError_WithNullId() { await StartAsync(); @@ -311,12 +311,12 @@ public async Task PostMalformedJson_Returns400_InvalidRequest_WithNullId() using var response = await HttpClient.PostAsync("", JsonContent(body), TestContext.Current.CancellationToken); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); - // The server must emit a conformant JSON-RPC error envelope (not a raw 500). Because the request - // id could not be read, the error carries id=null per JSON-RPC 2.0 §5.1 — and crucially it must - // serialize as JSON null, not "" (regression guard for the RequestId write path). + // The server must emit a conformant JSON-RPC error envelope (not a raw 500). Per JSON-RPC 2.0 §5.1, + // invalid JSON returns -32700 (Parse error) with id=null — and crucially it must serialize as JSON null, + // not "" (regression guard for the RequestId write path). using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); Assert.Equal(JsonValueKind.Null, doc.RootElement.GetProperty("id").ValueKind); - Assert.Equal((int)McpErrorCode.InvalidRequest, doc.RootElement.GetProperty("error").GetProperty("code").GetInt32()); + Assert.Equal((int)McpErrorCode.ParseError, doc.RootElement.GetProperty("error").GetProperty("code").GetInt32()); // The parse failure itself must be diagnosable from the response alone: the message carries the // JsonException message (which already includes the parser's position) instead of an opaque one-liner (#1842). @@ -326,20 +326,22 @@ public async Task PostMalformedJson_Returns400_InvalidRequest_WithNullId() } [Theory] + [InlineData("""{"jsonrpc":""")] [InlineData("""{"jsonrpc":"2.0","id":1,"method":"tools/list","para""")] [InlineData("""{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"a":1""")] - public async Task PostTruncatedJson_Returns400_WithParserDetail(string body) + public async Task PostTruncatedJson_Returns400_ParseError_WithParserDetail(string body) { await StartAsync(); // A body cut in half by an intermediary (proxy, gateway, or the transport itself) is the exact - // shape reported in #1842. The 400 response must carry the parser's message (including where - // parsing stopped) so the truncation is identifiable from the response without server-side logs. + // shape reported in #1842. The 400 response must return -32700 (Parse error) and carry the parser's + // message (including where parsing stopped) so the truncation is identifiable without server logs. using var response = await HttpClient.PostAsync("", JsonContent(body), TestContext.Current.CancellationToken); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); - Assert.Equal((int)McpErrorCode.InvalidRequest, doc.RootElement.GetProperty("error").GetProperty("code").GetInt32()); + Assert.Equal(JsonValueKind.Null, doc.RootElement.GetProperty("id").ValueKind); + Assert.Equal((int)McpErrorCode.ParseError, doc.RootElement.GetProperty("error").GetProperty("code").GetInt32()); var message = doc.RootElement.GetProperty("error").GetProperty("message").GetString(); Assert.Contains("did not contain a valid JSON-RPC message", message); @@ -349,12 +351,11 @@ public async Task PostTruncatedJson_Returns400_WithParserDetail(string body) private static async Task GetJsonRpcMessageParseErrorAsync(string body) { using var stream = new MemoryStream(Encoding.UTF8.GetBytes(body)); - var exception = await Assert.ThrowsAsync(async () => + var exception = await Assert.ThrowsAnyAsync(async () => { - await JsonSerializer.DeserializeAsync( + using var _ = await JsonDocument.ParseAsync( stream, - McpJsonUtilities.DefaultOptions.GetTypeInfo(), - TestContext.Current.CancellationToken); + cancellationToken: TestContext.Current.CancellationToken); }); return exception.Message; @@ -376,6 +377,25 @@ public async Task PostRequestWithExplicitNullId_Returns400_InvalidRequest_WithNu Assert.Equal((int)McpErrorCode.InvalidRequest, doc.RootElement.GetProperty("error").GetProperty("code").GetInt32()); } + [Theory] + [InlineData("{}")] + [InlineData("[]")] + [InlineData("null")] + [InlineData("""{"jsonrpc":"1.0","id":1,"method":"ping"}""")] + public async Task PostInvalidJsonRpcEnvelope_Returns400_InvalidRequest_WithNullId(string body) + { + await StartAsync(); + + // Valid JSON that is not a valid JSON-RPC 2.0 message must return -32600 (Invalid Request), + // distinct from -32700 (Parse error) for invalid JSON syntax. + using var response = await HttpClient.PostAsync("", JsonContent(body), TestContext.Current.CancellationToken); + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + + using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)); + Assert.Equal(JsonValueKind.Null, doc.RootElement.GetProperty("id").ValueKind); + Assert.Equal((int)McpErrorCode.InvalidRequest, doc.RootElement.GetProperty("error").GetProperty("code").GetInt32()); + } + [Fact] public async Task GetWithoutSessionId_Returns400_WithStatelessGuidance() {