Repository navigation
fix: Distinguish invalid JSON-RPC messages from JSON parse errors #375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: rel/1.0.0
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -505,7 +505,6 @@ public actor Server { | |||||||||||||||||
| for try await data in stream { | ||||||||||||||||||
| if Task.isCancelled { break } // Check cancellation inside loop | ||||||||||||||||||
|
|
||||||||||||||||||
| var requestID: ID? | ||||||||||||||||||
| do { | ||||||||||||||||||
| // Attempt to decode as batch first, then as individual response, request, or notification | ||||||||||||||||||
| if let batch = try? decoder.decode(Server.Batch.self, from: data) { | ||||||||||||||||||
|
|
@@ -557,6 +556,7 @@ public actor Server { | |||||||||||||||||
| try await handleMessage(message) | ||||||||||||||||||
| } else { | ||||||||||||||||||
| // Try to extract request ID from raw JSON if possible | ||||||||||||||||||
| var requestID: ID? | ||||||||||||||||||
| if let json = try? decoder.decode( | ||||||||||||||||||
| [String: Value].self, from: data), | ||||||||||||||||||
| let idValue = json["id"] | ||||||||||||||||||
|
Comment on lines
560
to
562
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: The id of a response names one of this server's own requests, which is the reason the batch path nulls it. The peer matches replies by id, so it can read this -32600 as the answer to its own request 5 and fail an unrelated call; peers that number requests 0, 1, 2 are the ones exposed. The attribution existed before (with -32700), but this PR rewrites the branch and its tests now lock in the variant the batch comment calls wrong. Evidence // Sources/MCP/Server/Server.swift:560-572
if let json = try? decoder.decode(
[String: Value].self, from: data),
let idValue = json["id"]
{ ... }
let error = JSONRPCMessageKind.classificationError(for: data)
if let requestID {
try? await send(AnyMethod.response(id: requestID, error: error))Required change if let json = try? decoder.decode(
[String: Value].self, from: data),
+ json["result"] == nil, json["error"] == nil,
let idValue = json["id"]and in - (#"{"id":5,"result":{}}"#, -32600, 5),
- (#"{"jsonrpc":"1.0","id":5,"error":{"code":-32603,"message":"failed"}}"#, -32600, 5),
+ (#"{"id":5,"result":{}}"#, -32600, .null),
+ (#"{"jsonrpc":"1.0","id":5,"error":{"code":-32603,"message":"failed"}}"#, -32600, .null),
Suggested change
|
||||||||||||||||||
|
|
@@ -567,7 +567,12 @@ public actor Server { | |||||||||||||||||
| requestID = .number(intValue) | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| throw MCPError.parseError("Invalid message format") | ||||||||||||||||||
| let error = JSONRPCMessageKind.classificationError(for: data) | ||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: Evidence // Sources/MCP/Server/Server.swift:570-575
let error = JSONRPCMessageKind.classificationError(for: data)
if let requestID {
try? await send(AnyMethod.response(id: requestID, error: error))
} else {
await sendUnattributedError(error)
}Required change let error = JSONRPCMessageKind.classificationError(for: data)
await logger?.warning("Invalid message", metadata: ["error": "\(error)"])
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: The cost is linear and only on rejected input, but a peer can trigger it at will on a path that already parses each rejected message six times. Evidence // Sources/MCP/Server/Server.swift:570
let error = JSONRPCMessageKind.classificationError(for: data)Required change let object = try? decoder.decode([String: Value].self, from: data)
// ... extract requestID from `object` as today ...
let error: MCPError = object != nil
? .invalidRequest("Invalid JSON-RPC message")
: JSONRPCMessageKind.classificationError(for: data) |
||||||||||||||||||
| if let requestID { | ||||||||||||||||||
| try? await send(AnyMethod.response(id: requestID, error: error)) | ||||||||||||||||||
| } else { | ||||||||||||||||||
| await sendUnattributedError(error) | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| } catch let error where MCPError.isResourceTemporarilyUnavailable(error) { | ||||||||||||||||||
| // Resource temporarily unavailable, retry after a short delay | ||||||||||||||||||
|
|
@@ -578,9 +583,7 @@ public actor Server { | |||||||||||||||||
| "Error processing message", metadata: ["error": "\(error)"]) | ||||||||||||||||||
| let mcpError = | ||||||||||||||||||
| error as? MCPError ?? MCPError.internalError(error.localizedDescription) | ||||||||||||||||||
| if let requestID { | ||||||||||||||||||
| try? await send(AnyMethod.response(id: requestID, error: mcpError)) | ||||||||||||||||||
| } else if case .parseError = mcpError { | ||||||||||||||||||
| if case .parseError = mcpError { | ||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: A reader looking for where unreadable messages are answered lands here instead of at line 570, and code that looks live but is not invites wrong edits later. Evidence // Sources/MCP/Server/Server.swift:586-590
if case .parseError = mcpError {
// A message that could not be read: `"id": null`.
await sendUnattributedError(mcpError)
}
// Notifications are never answered.Required change - let mcpError =
- error as? MCPError ?? MCPError.internalError(error.localizedDescription)
- if case .parseError = mcpError {
- // A message that could not be read: `"id": null`.
- await sendUnattributedError(mcpError)
- }
- // Notifications are never answered.
+ // Unreadable messages are answered above; errors from
+ // notification handling are only logged. |
||||||||||||||||||
| // A message that could not be read: `"id": null`. | ||||||||||||||||||
| await sendUnattributedError(mcpError) | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
@@ -2976,7 +2979,7 @@ extension Server.Batch: Decodable { | |||||||||||||||||
|
|
||||||||||||||||||
| extension Server.Batch.Item: Decodable { | ||||||||||||||||||
| private enum CodingKeys: String, CodingKey { | ||||||||||||||||||
| case id | ||||||||||||||||||
| case id, result, error | ||||||||||||||||||
| } | ||||||||||||||||||
|
|
||||||||||||||||||
| /// Classifies an item as ``JSONRPCMessageKind`` does for a single | ||||||||||||||||||
|
|
@@ -3016,9 +3019,10 @@ extension Server.Batch.Item: Decodable { | |||||||||||||||||
| self = .invalid(id: nil, reason: format) | ||||||||||||||||||
| } | ||||||||||||||||||
| case nil: | ||||||||||||||||||
| // No string `method`, and no `result` or `error` with a valid | ||||||||||||||||||
| // `id`, such as `{"jsonrpc": "2.0", "id": 7}`. | ||||||||||||||||||
| self = .invalid(id: id, reason: format) | ||||||||||||||||||
| // An unreadable response still names this server's request, | ||||||||||||||||||
| // even when its version prevents classification as a response. | ||||||||||||||||||
| let isResponse = container.contains(.result) || container.contains(.error) | ||||||||||||||||||
| self = .invalid(id: isResponse ? nil : id, reason: format) | ||||||||||||||||||
|
Comment on lines
+3022
to
+3025
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: A maintainer reading only this branch may "fix" it to keep the id, which would reintroduce the attribution this change removes. Evidence // Sources/MCP/Server/Server.swift:3022-3025
// An unreadable response still names this server's request,
// even when its version prevents classification as a response.
let isResponse = container.contains(.result) || container.contains(.error)
self = .invalid(id: isResponse ? nil : id, reason: format)Required change
Suggested change
|
||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| } | ||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -132,6 +132,39 @@ private func makeStatelessTransport() -> StatelessHTTPServerTransport { | |
| ) | ||
| } | ||
|
|
||
| private let invalidMessageBodies: [(String, Int)] = [ | ||
| (#"{"not_a_valid_request":true}"#, -32600), | ||
| (#"{"jsonrpc":"2.0","id":7}"#, -32600), | ||
| (#"{"jsonrpc":"2.0","id":"request"}"#, -32600), | ||
| (#"{"jsonrpc":"2.0","method":42}"#, -32600), | ||
| (#"{"id":1,"result":{}}"#, -32600), | ||
| (#"{"jsonrpc":"1.0","id":1,"result":{}}"#, -32600), | ||
| (#"{"jsonrpc":null,"id":1,"result":{}}"#, -32600), | ||
| (#"{"jsonrpc":2.0,"id":1,"result":{}}"#, -32600), | ||
| (#"{"id":"r","error":{"code":-32603,"message":"failed"}}"#, -32600), | ||
| (#"{"jsonrpc":"1.0","id":"r","error":{"code":-32603,"message":"failed"}}"#, -32600), | ||
| ("{}", -32600), | ||
| ("[]", -32600), | ||
| ("[1,2,3]", -32600), | ||
| (#"[{"jsonrpc":"2.0","id":1,"method":"ping"}]"#, -32600), | ||
| ("null", -32600), | ||
| ("true", -32600), | ||
| ("false", -32600), | ||
| ("42", -32600), | ||
| ("1.5", -32600), | ||
| (#""text""#, -32600), | ||
| ("not valid json{", -32700), | ||
| (#"{"jsonrpc":"2.0","id":7"#, -32700), | ||
| ("[1,", -32700), | ||
| ("true false", -32700), | ||
| (" \n\t", -32700), | ||
| ] | ||
|
|
||
| private let validResponseBodies = [ | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: This is the boundary input most likely to be misclassified, and today neither table records whether it should be accepted (202) or rejected. A change in either direction would pass the suite. Evidence // Tests/MCPTests/HTTPServerTransportTests.swift:163-166
private let validResponseBodies = [
#"{"jsonrpc":"2.0","id":1,"result":{}}"#,
#"{"jsonrpc":"2.0","id":"r","error":{"code":-32603,"message":"failed"}}"#,
]Required change // Add to invalidMessageBodies if rejection is intended (with a comment),
// or to validResponseBodies if it should be accepted with 202:
(#"{"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":"x"}}"#, -32600), |
||
| #"{"jsonrpc":"2.0","id":1,"result":{}}"#, | ||
| #"{"jsonrpc":"2.0","id":"r","error":{"code":-32603,"message":"failed"}}"#, | ||
| ] | ||
|
|
||
| /// Drains an SSE stream, collecting raw SSE chunks. | ||
| private actor ChunkCollector { | ||
| var chunks: [Data] = [] | ||
|
|
@@ -814,17 +847,36 @@ struct StatefulHTTPServerTransportTests { | |
| await transport.disconnect() | ||
| } | ||
|
|
||
| @Test("Invalid JSON body returns 400") | ||
| func testInvalidJSONReturns400() async throws { | ||
| @Test("Invalid bodies return the appropriate JSON-RPC error", arguments: invalidMessageBodies.indices) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Problem Why this is needed: It slows down diagnosis when one row regresses. The pattern already exists in Evidence // Tests/MCPTests/HTTPServerTransportTests.swift:850
@Test("Invalid bodies return the appropriate JSON-RPC error", arguments: invalidMessageBodies.indices)Required change @Test("Invalid bodies return the appropriate JSON-RPC error", arguments: invalidMessageBodies)
func testInvalidBodyErrorCode(_ body: String, _ expectedCode: Int) async throws { |
||
| func testInvalidBodyErrorCode(_ index: Int) async throws { | ||
| let (body, expectedCode) = invalidMessageBodies[index] | ||
| let transport = makeStatefulTransport() | ||
| let sessionID = try await initializeSession(transport: transport) | ||
|
|
||
| let response = await transport.handleRequest( | ||
| makeStatefulPOSTRequest(body: Data("not json".utf8), sessionID: sessionID) | ||
| makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID) | ||
| ) | ||
| await transport.disconnect() | ||
|
|
||
| #expect(response.statusCode == 400) | ||
| #expect(response.headers[HTTPHeaderName.sessionID] == sessionID) | ||
| #expect(response.headers[HTTPHeaderName.contentType] == "application/json") | ||
| let data = try #require(response.bodyData) | ||
| let json = try JSONDecoder().decode(Value.self, from: data) | ||
| expectWire(json, matches: ["jsonrpc": "2.0", "id": .null, "error": ["code": .int(expectedCode)]]) | ||
| } | ||
|
|
||
| @Test("Valid JSON-RPC responses are still accepted", arguments: validResponseBodies) | ||
| func testValidResponseAccepted(_ body: String) async throws { | ||
| let transport = makeStatefulTransport() | ||
| let sessionID = try await initializeSession(transport: transport) | ||
| let response = await transport.handleRequest( | ||
| makeStatefulPOSTRequest(body: Data(body.utf8), sessionID: sessionID)) | ||
| await transport.disconnect() | ||
|
|
||
| #expect(response.statusCode == 202) | ||
| #expect(response.bodyData == nil) | ||
| #expect(response.headers[HTTPHeaderName.sessionID] == sessionID) | ||
| } | ||
|
|
||
| // MARK: - OAuth Bearer Validation | ||
|
|
@@ -1409,17 +1461,45 @@ struct StatelessHTTPServerTransportTests { | |
| await transport.disconnect() | ||
| } | ||
|
|
||
| @Test("Invalid JSON body returns 400") | ||
| func testInvalidJSONReturns400() async throws { | ||
| @Test( | ||
| "Invalid bodies return the appropriate JSON-RPC error in both protocol eras", | ||
| arguments: invalidMessageBodies.indices, [Version.v2025_11_25, Version.v2026_07_28] | ||
| ) | ||
| func testInvalidBodyErrorCode(_ index: Int, protocolVersion: String) async throws { | ||
| let (body, expectedCode) = invalidMessageBodies[index] | ||
| let transport = makeStatelessTransport() | ||
| try await transport.connect() | ||
|
|
||
| let response = await transport.handleRequest( | ||
| makeStatelessPOSTRequest(body: Data("not json".utf8)) | ||
| HTTPRequest( | ||
| method: "POST", | ||
| headers: [ | ||
| HTTPHeaderName.contentType: "application/json", | ||
| HTTPHeaderName.accept: "application/json", | ||
| HTTPHeaderName.protocolVersion: protocolVersion, | ||
| ], | ||
| body: Data(body.utf8)) | ||
| ) | ||
| await transport.disconnect() | ||
|
|
||
| #expect(response.statusCode == 400) | ||
| #expect(response.headers[HTTPHeaderName.sessionID] == nil) | ||
| #expect(response.headers[HTTPHeaderName.contentType] == "application/json") | ||
| let data = try #require(response.bodyData) | ||
| let json = try JSONDecoder().decode(Value.self, from: data) | ||
| expectWire(json, matches: ["jsonrpc": "2.0", "id": .null, "error": ["code": .int(expectedCode)]]) | ||
| } | ||
|
|
||
| @Test("Valid JSON-RPC responses are still accepted", arguments: validResponseBodies) | ||
| func testValidResponseAccepted(_ body: String) async throws { | ||
| let transport = makeStatelessTransport() | ||
| try await transport.connect() | ||
| let response = await transport.handleRequest( | ||
| makeStatelessPOSTRequest(body: Data(body.utf8))) | ||
| await transport.disconnect() | ||
|
|
||
| #expect(response.statusCode == 202) | ||
| #expect(response.bodyData == nil) | ||
| } | ||
|
|
||
| // MARK: - Terminated State | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Problem
P2:
JSONRPCMessageKindis also the client's classifier.HTTPClientTransport.processSSEusescase .response(let id) = JSONRPCMessageKind(data: data)(HTTPClientTransport.swift:1407-1411) to detect the awaited response and cancel the POST stream. With this guard, an SSE response without"jsonrpc": "2.0"is no longer recognized.respondedstays false, so the transport keeps reading, then runsresumeResponseStream(GET withLast-Event-ID, up tomaxStreamResumptions) ordeliverStreamLossfor a request theClienthas already failed. The PR describes the change as server-side and adds no client test.Why this is needed: Against a non-conforming server the client now holds the POST stream open and can make several reconnect requests after the caller already has its error, then yields a second error that
Clientdrops. The caller does not hang, so the impact is limited, but the client behavior changed without a test or a note in the PR description, and a later edit to the shared classifier can change it again unnoticed.Evidence
Required change
Add a client test next to "Receive Server-Sent Event (SSE)" (
HTTPClientTransportTests.swift:1032) that pins the intended outcome, for example:Alternatively, give the client its own routing check (
idplusresult/error) and keep the version check in the server POST path. Either way, mention the client effect in the PR description.