Skip to content

fix: Distinguish invalid JSON-RPC messages from JSON parse errors - #375

Open
bbdu3 wants to merge 2 commits into
modelcontextprotocol:rel/1.0.0from
bbdu3:fix/http-invalid-jsonrpc-message
Open

bbdu3 wants to merge 2 commits into
modelcontextprotocol:rel/1.0.0from
bbdu3:fix/http-invalid-jsonrpc-message

Conversation

@bbdu3

@bbdu3 bbdu3 commented Nov 26, 2026

Copy link
Copy Markdown

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 -32700 for malformed JSON.

It also aligns the server receive loop with HTTP error classification and rejects HTTP responses whose jsonrpc field is missing or is not "2.0".

Changed

  • Share error classification between both HTTP server transports and the server receive loop used by stdio and in-memory transports.
  • Reject invalid JSON objects, scalars, and HTTP batch arrays with -32600.
  • Validate jsonrpc when classifying responses, in addition to the release branch’s existing request and notification validation.
  • Preserve valid response acceptance, notification handling, and existing stream batch behavior.
  • Preserve null error IDs for malformed responses inside batches, avoiding incorrect attribution to a peer’s request.
  • Keep HTTP classification errors at status 400, with existing session-header behavior.
  • No public API signatures or package dependencies changed. The behavior change also affects Linux.

Test

Added or expanded regression coverage for:

  • Valid JSON versus malformed JSON across both HTTP transports.
  • Stateless HTTP classification with both supported protocol eras.
  • Responses with missing, incorrect, null, or numeric jsonrpc values.
  • Valid success and error responses continuing to receive HTTP 202.
  • Server receive-loop error classification, with synchronization instead of fixed sleeps.
  • Invalid response versions inside batches preserving error IDs and valid request processing.
  • git diff HEAD --check passed.

Signed-off-by: bbdu3 <ergouyang854@gmail.com>
Signed-off-by: bbdu3 <ergouyang854@gmail.com>
@bbdu3
bbdu3 requested a review from a team as a code owner November 26, 2026 08:50
@bbdu3
bbdu3 changed the base branch from main to rel/1.0.0 November 26, 2026 08:58

@jeanmatthieu jeanmatthieu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review summary

Risk: MEDIUM | Blocking(P0/P1): 0 | Should-fix(P2): 3 | Suggestions(P3): 8 | Good: 8

  • Reviewed at 58458da: 2 commits ahead of rel/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

  1. 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).
  2. 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).
  3. Moving var requestID into 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.
  4. The new response version guard matches Response.init(from:) (Messages.swift:356), so the HTTP transports stop answering 202 to a response the Server loop could never resolve.
  5. Server.Batch.Item now answers an unreadable response inside a batch with "id": null, and batchInvalidResponseVersion pins that.
  6. unreadableMessage replaces the fixed-sleep exchange with RawPeer.sync, and checks that a valid notification and a valid response sent afterwards get no reply.
  7. Every new -32600 case fails on the base, and the -32700 rows plus validResponseBodies pin the behavior that must not change.
  8. 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.

Comment on lines 560 to 562
if let json = try? decoder.decode(
[String: Value].self, from: data),
let idValue = json["id"]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),
Suggested change
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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Comment on lines +3022 to +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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Suggested 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 = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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),

@jeanmatthieu

Copy link
Copy Markdown
Contributor

These three findings are on files this PR does not change, so they cannot be inline comments.

F4: docs/src/protocol.src.md:38

Problem
P2: the guide still says "A message it cannot read gets a parse error (-32700) with "id": null", and the error table at line 667 still lists "not a JSON-RPC message" as a parseError(_:) cause. After this PR, valid JSON that is not a message gets -32600, and on the stream transports the error carries the message's id when one can be read. The generated docs/protocol.md (lines 53 and 1092) has the same text.

Why this is needed: This page is where integrators and other SDK authors look up the codes the server sends. It now contradicts the behavior this PR exists to change, so anyone who builds against it will expect -32700 where the server sends -32600. docs/protocol.md is generated from this file, so the old text survives until the source is edited and regenerated.

Evidence

<!-- docs/src/protocol.src.md:38 -->
A server never answers a notification. A message it cannot read gets a parse error (-32700) with `"id": null`, and an empty batch gets -32600 with `"id": null`.

<!-- docs/src/protocol.src.md:667 -->
| `parseError(_:)` | -32700 | `{"detail"}` | Body is not JSON or not a JSON-RPC message. |

Required change

-A server never answers a notification. A message it cannot read gets a parse error (-32700) with `"id": null`, and an empty batch gets -32600 with `"id": null`.
+A server never answers a notification. A message that is not valid JSON gets a parse error (-32700) with `"id": null`. Valid JSON that is not a JSON-RPC message gets -32600, carrying the message's `id` when it is a string or an integer and `"id": null` otherwise. An empty batch gets -32600 with `"id": null`.
-| `parseError(_:)` | -32700 | `{"detail"}` | Body is not JSON or not a JSON-RPC message. |
-| `invalidRequest(_:)` | -32600 | `{"detail"}` | Request before `initialize` (strict); ...
+| `parseError(_:)` | -32700 | `{"detail"}` | Body is not valid JSON. |
+| `invalidRequest(_:)` | -32600 | `{"detail"}` | Valid JSON that is not a JSON-RPC message; request before `initialize` (strict); ...

Then regenerate docs/protocol.md with swift scripts/weave.swift. If F1 is applied, drop "carrying the message's id" for responses.

not single-hunk: two non-contiguous lines in docs/src/protocol.src.md plus the regenerated docs/protocol.md

F8: design/stateless.md:104

Problem
P3: step 1 of the stateless POST pipeline still says every unclassifiable body gets 400 -32700. handlePost now returns classificationError(for: body), which is -32600 for valid JSON that is not a single message; only an empty body or invalid JSON still gets -32700.

Why this is needed: This design note is what later transport changes are checked against. A stale step invites someone to restore -32700 to match it.

Evidence

<!-- design/stateless.md:104 -->
1. Empty body or unclassifiable JSON-RPC: 400 -32700.

Required change

1. Empty body or invalid JSON: 400 -32700. Valid JSON that is not a single JSON-RPC message
   (an array, a scalar, a response whose `jsonrpc` is not `"2.0"`): 400 -32600.

F10: CHANGELOG.md:136

Problem
P3: the unreleased 1.0.0 notes do not mention the wire changes in this PR: valid JSON that is not a message now gets -32600 instead of -32700, and a POSTed response whose jsonrpc is not "2.0" now gets HTTP 400 instead of 202. VERSIONING.md asks for wire-behavior fixes to be called out in the release notes, and recent commits on this branch update CHANGELOG.md in the same change.

Why this is needed: An HTTP client that sent responses without the version used to get 202 and now gets 400. The change is a fix, but release notes are where integrators learn about it.

Evidence

<!-- CHANGELOG.md:136-137 -->
- A request whose `id` is not a string or an integer (`null`, `1.5`, `[]`, `true`, `1e20`), or
  whose `jsonrpc` is not `"2.0"`, gets -32600 (HTTP 400) instead of being taken for a notification

Required change

- The HTTP server transports and `Server` answer JSON that is not a JSON-RPC message (a scalar,
  an array over HTTP, an object with no `method`, `result` or `error`) with -32600 instead of
  -32700, which is kept for a body that is not JSON. A response whose `jsonrpc` is not `"2.0"`
  gets -32600 (HTTP 400) instead of 202, and in a batch it is answered with `"id": null`.

@jeanmatthieu

Copy link
Copy Markdown
Contributor

Hi @bbdu3, we took your changes in #401. This PR can be closed at your convenience. Thanks

canarik pushed a commit to canarik/swift-sdk that referenced this pull request Nov 29, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants