Repository navigation
Conversation
Signed-off-by: bbdu3 <ergouyang854@gmail.com>
Signed-off-by: bbdu3 <ergouyang854@gmail.com>
jeanmatthieu
left a comment
There was a problem hiding this comment.
Review summary
Risk: MEDIUM | Blocking(P0/P1): 0 | Should-fix(P2): 3 | Suggestions(P3): 8 | Good: 8
- Reviewed at
58458da: 2 commits ahead ofrel/1.0.0, 0 behind, merges cleanly. - Full review, because the diff touches crash-sensitive code.
- Findings: 1 inconsistent error attribution, 2 test gaps, 4 outdated docs or comments, 1 missing release note, 1 missing log line, 1 redundant parse and 1 test-naming issue.
- Regressions were checked two independent ways: pattern checks and an open-ended hunt.
- The secrets scan did not run, so secrets were not checked.
- 1 of 3 should-fix items has a one-click suggestion; the others say why not.
What is solid
classificationError(for:)probes with.fragmentsAllowed, so scalars get -32600 and only bytes that are not JSON get -32700, at all three call sites (HTTPServerTypes.swift:412-421).- The stateless transport classifies the raw
body, not the normalized copy, so a scalar or array that fails the[String: Any]cast still gets -32600 (StatelessHTTPServerTransport.swift:298). - Moving
var requestIDinto the fallback branch and dropping it from the catch keeps attribution as it was: on the base it was only ever set in that branch, right before the throw. - The new response version guard matches
Response.init(from:)(Messages.swift:356), so the HTTP transports stop answering 202 to a response theServerloop could never resolve. Server.Batch.Itemnow answers an unreadable response inside a batch with"id": null, andbatchInvalidResponseVersionpins that.unreadableMessagereplaces the fixed-sleep exchange withRawPeer.sync, and checks that a valid notification and a valid response sent afterwards get no reply.- Every new -32600 case fails on the base, and the -32700 rows plus
validResponseBodiespin the behavior that must not change. - Rejected stateful POSTs still carry the session header, and the parameterized tests assert it on every row.
Findings
| Sev | ID | Category | File | Line | Summary |
|---|---|---|---|---|---|
| P2 | F1 | QUALITY | Sources/MCP/Server/Server.swift |
560 | A lone malformed response is answered with its own id; the batch path answers the same input with null |
| P2 | F4 | COMMENT-ROT | docs/src/protocol.src.md |
38 | Guide still says every unreadable message gets -32700 |
| P2 | F3 | MISSING-TESTS | Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift |
449 | The new guard also changes HTTPClientTransport SSE handling, with no client test |
| P3 | F2 | OBSERVABILITY | Sources/MCP/Server/Server.swift |
570 | Unreadable messages are no longer logged |
| P3 | F7 | COMMENT-ROT | Sources/MCP/Server/Server.swift |
586 | The .parseError catch branch is now unreachable |
| P3 | F8 | COMMENT-ROT | design/stateless.md |
104 | POST pipeline step still says -32700 for every unclassifiable body |
| P3 | F9 | EFFICIENCY | Sources/MCP/Server/Server.swift |
570 | Extra full parse after the body is already known to be JSON |
| P3 | F12 | QUALITY | Tests/MCPTests/HTTPServerTransportTests.swift |
850 | Cases named by index make failures hard to map back |
| P3 | F10 | API-CONTRACT | CHANGELOG.md |
136 | Release notes do not mention the new codes or the 202 to 400 change |
| P3 | F5 | COMMENT-ROT | Sources/MCP/Server/Server.swift |
3022 | Batch comment reads as if the id is kept |
| P3 | F11 | MISSING-TESTS | Tests/MCPTests/HTTPServerTransportTests.swift |
163 | No expectation for a valid error response with "id": null |
Verdict: comment-only.
AI disclosure: this review was assisted by Opus 5.5.
| if let json = try? decoder.decode( | ||
| [String: Value].self, from: data), | ||
| let idValue = json["id"] |
There was a problem hiding this comment.
Problem
P2: on stdio, in-memory and Network transports, a single malformed response such as {"id":5,"result":{}} or {"jsonrpc":"1.0","id":5,"error":{...}} now fails the new jsonrpc guard, reaches this fallback, and is answered with {"jsonrpc":"2.0","id":5,"error":{"code":-32600}}. The same input inside a batch is answered with "id": null (Server.swift:3024). The new rows at Tests/MCPTests/RequestLifecycleTests.swift:615-616 expect id 5, while batchInvalidResponseVersion expects null.
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 Tests/MCPTests/RequestLifecycleTests.swift:615-616:
- (#"{"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),| if let json = try? decoder.decode( | |
| [String: Value].self, from: data), | |
| let idValue = json["id"] | |
| if let json = try? decoder.decode( | |
| [String: Value].self, from: data), | |
| json["result"] == nil, json["error"] == nil, | |
| let idValue = json["id"] |
| } | ||
| } else if container.contains(.result) || container.contains(.error), let id { | ||
| // JSON-RPC 2.0 §5 requires the version on responses too. | ||
| guard (try? container.decode(String.self, forKey: .jsonrpc)) == "2.0" else { |
There was a problem hiding this comment.
Problem
P2: JSONRPCMessageKind is also the client's classifier. HTTPClientTransport.processSSE uses case .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. responded stays false, so the transport keeps reading, then runs resumeResponseStream (GET with Last-Event-ID, up to maxStreamResumptions) or deliverStreamLoss for a request the Client has 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 Client drops. 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
// Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift:447-452
} else if container.contains(.result) || container.contains(.error), let id {
// JSON-RPC 2.0 §5 requires the version on responses too.
guard (try? container.decode(String.self, forKey: .jsonrpc)) == "2.0" else {
throw DecodingError.dataCorruptedError(
forKey: .jsonrpc, in: container, debugDescription: InvalidRequestReason.jsonrpc)
}Required change
Add a client test next to "Receive Server-Sent Event (SSE)" (HTTPClientTransportTests.swift:1032) that pins the intended outcome, for example:
@Test("An SSE response without jsonrpc 2.0 ends the POST stream", .httpClientTransportSetup)
func sseResponseWithoutVersion() async throws {
// Serve the POST with Content-Type: text/event-stream and one event:
// data: {"id":<awaited id>,"result":{}}
// Expect: the transport yields the event once, sends no resumption GET,
// and yields no second error for that id (or whatever outcome is chosen).
}Alternatively, give the client its own routing check (id plus result/error) and keep the version check in the server POST path. Either way, mention the client effect in the PR description.
not single-hunk: needs a new test in
Tests/MCPTests/HTTPClientTransportTests.swift
| } | ||
| } | ||
| throw MCPError.parseError("Invalid message format") | ||
| let error = JSONRPCMessageKind.classificationError(for: data) |
There was a problem hiding this comment.
Problem
P3: before this PR an unreadable message was thrown into the catch block, which logged "Error processing message". It is now answered inline and never reaches the catch, so it leaves no server log entry. A failed reply on the id path is also swallowed by try?.
Why this is needed: Server reports failed message handling through logger. An operator debugging a client that sends bad input over stdio loses the only server-side trace of it, since the -32700 or -32600 goes to the peer only.
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)"])| if let requestID { | ||
| try? await send(AnyMethod.response(id: requestID, error: mcpError)) | ||
| } else if case .parseError = mcpError { | ||
| if case .parseError = mcpError { |
There was a problem hiding this comment.
Problem
P3: the PR removed throw MCPError.parseError("Invalid message format"), the only source of .parseError in this do block. The remaining throwing call, handleMessage, catches handler errors and never throws .parseError, so this branch and its comment describe a path that is no longer reached.
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.| } | ||
| } | ||
| throw MCPError.parseError("Invalid message format") | ||
| let error = JSONRPCMessageKind.classificationError(for: data) |
There was a problem hiding this comment.
Problem
P3: on the rejection path the loop has already decoded the body as Batch, AnyResponse, AnyRequest, JSONRPCMessageKind, AnyMessage and [String: Value]. When the [String: Value] decode succeeded, the body is known to be JSON, yet classificationError(for:) parses it again with JSONSerialization. StatelessHTTPServerTransport.handlePost re-parses the same way. The valid path is unchanged.
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)|
|
||
| @Test("Invalid JSON body returns 400") | ||
| func testInvalidJSONReturns400() async throws { | ||
| @Test("Invalid bodies return the appropriate JSON-RPC error", arguments: invalidMessageBodies.indices) |
There was a problem hiding this comment.
Problem
P3: the three parameterized tests run over .indices, so cases are reported as 0 to 24 (50 for the stateless variant, which also crosses two versions). A failure has to be mapped back to the table by hand.
Why this is needed: It slows down diagnosis when one row regresses. The pattern already exists in RequestIDValidationTests, so this is a minor consistency trade-off.
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 {| // 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) |
There was a problem hiding this comment.
Problem
P3: read on its own, "An unreadable response still names this server's request" suggests the id is kept, but the next line drops it. The reason is in the type's doc comment above, not here.
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
| // 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) | |
| // A response's `id` names a request of this server, not one of | |
| // the peer: an unreadable one is answered with `"id": null`. | |
| let isResponse = container.contains(.result) || container.contains(.error) | |
| self = .invalid(id: isResponse ? nil : id, reason: format) |
| (" \n\t", -32700), | ||
| ] | ||
|
|
||
| private let validResponseBodies = [ |
There was a problem hiding this comment.
Problem
P3: no test covers a valid JSON-RPC error response with "id": null, which a client sends when it could not read a server request (JSON-RPC 2.0 §5). JSONRPCMessageKind maps a null id to nil, so the body is rejected and now gets 400 with -32600 (before: -32700).
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),|
These three findings are on files this PR does not change, so they cannot be inline comments. F4:
|
…with "id": null Follow-up to the review of modelcontextprotocol#375. - Server: a lone response that cannot be read (no `jsonrpc`, or not "2.0") is answered with `"id": null`, as inside a batch. A response's `id` names a request of this server, not one of the peer, so answering with it could fail an unrelated request of the peer. Unreadable messages are logged again, the unreachable `.parseError` catch branch is gone, and a body already decoded as an object is not parsed a second time. - HTTP server transports: an error response with `"id": null`, the answer to a request whose id could not be read (JSON-RPC 2.0 §5), is a response and gets 202 instead of 400 -32600; in a batch it gets no reply. Only an error may carry a null id: a `result` with one still gets -32600. - HTTPClientTransport: the `jsonrpc` check added to JSONRPCMessageKind no longer decides where an SSE stream ends. The transport ends the POST stream on any answer to its request, as before, because `Client` fails the request an unreadable answer names; it no longer resumes the stream and reports a second error for it. - Docs: the protocol guide, the stateless design note and CHANGELOG say which input gets -32700 and which -32600. - Tests name their parameterized cases by their arguments. Assisted-by: Claude
Summary
Valid JSON that is not a JSON-RPC message currently receives
-32700(Parse error). This change returns-32600(Invalid Request), as defined by JSON-RPC 2.0 §5.1, while retaining-32700for malformed JSON.It also aligns the server receive loop with HTTP error classification and rejects HTTP responses whose
jsonrpcfield is missing or is not"2.0".Changed
-32600.jsonrpcwhen classifying responses, in addition to the release branch’s existing request and notification validation.400, with existing session-header behavior.Test
Added or expanded regression coverage for:
jsonrpcvalues.202.git diff HEAD --checkpassed.