Skip to content

Commit 9b6973b

Browse files
authored
fix: Distinguish invalid JSON-RPC messages from JSON parse errors, and fail requests whose answer cannot be read (#401)
fix: Distinguish invalid JSON-RPC messages from JSON parse errors, and fail requests whose answer cannot be read
2 parents b88455c + c87f982 commit 9b6973b

15 files changed

Lines changed: 520 additions & 63 deletions

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,19 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha
163163
decodes a `null` id as `""`. In a JSON-RPC batch each invalid item gets its own -32600 and the
164164
other requests are still answered; a response in a batch answers the server's request it names
165165
instead of failing the batch.
166+
- The HTTP server transports and `Server` answer JSON that is not a JSON-RPC message (a scalar,
167+
an array over HTTP, an object with no `method`, `result` or `error`) with -32600 instead of
168+
-32700, which is kept for a body that is not JSON. A response whose `jsonrpc` is not `"2.0"`
169+
gets -32600 (HTTP 400) instead of 202, and is answered with `"id": null`, alone or in a batch.
170+
An error response with `"id": null` (JSON-RPC 2.0 §5) is accepted with 202 instead of 400, and
171+
gets no reply in a batch.
172+
- A server-to-client request answered with a message `Server` cannot read fails with -32603 instead
173+
of waiting forever, on every transport, alone or in a batch. Over HTTP the answer still gets
174+
400 when its `jsonrpc` is not `"2.0"`. `Client` likewise fails its request on an answer whose
175+
`method` is not a string.
176+
- A request whose `id` can be read but whose `params` cannot, such as one holding a number out of
177+
range (`1e400`), gets -32600 with its `id` instead of -32700 with `"id": null`. Over the
178+
stateful HTTP transport its POST got no answer.
166179
- A server that serves no handshake revision answers a request that names no `_meta` protocol
167180
version with -32602 (HTTP 400) and `data.supported`, not -32022 or -32601: the field is required,
168181
not unsupported. A `progressToken` that is not a string or an integer gets -32602 in every

‎Sources/MCP/Base/Transports/HTTPClientTransport.swift‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1351,6 +1351,16 @@ public actor HTTPClientTransport: Transport {
13511351
return detail == sseLineTooLong || detail == sseEventTooLong
13521352
}
13531353

1354+
/// The ID of the request a server message answers: a response, or one
1355+
/// whose `jsonrpc` is not `"2.0"`. `Client` fails the request an answer
1356+
/// it cannot read names, so the stream that carried it is done either way.
1357+
static func answeredRequestID(in data: Data) -> String? {
1358+
switch JSONRPCMessageKind(data: data) {
1359+
case .response(let id?), .invalidResponse(let id): id
1360+
default: nil
1361+
}
1362+
}
1363+
13541364
/// Reads SSE events and yields their messages. `onEventID` and
13551365
/// `onRetry` see each event's `id` (empty when the event resets it) and
13561366
/// `retry`, `onMessage` each message, `onResponse` the ID of each
@@ -1405,7 +1415,7 @@ public actor HTTPClientTransport: Transport {
14051415
onMessage()
14061416
var delivered: String?
14071417
if responseID != nil || onResponse != nil,
1408-
case .response(let id) = JSONRPCMessageKind(data: data)
1418+
let id = Self.answeredRequestID(in: data)
14091419
{
14101420
onResponse?(id)
14111421
delivered = id

‎Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,15 @@ public protocol HTTPContextProviding: Sendable {
388388
package enum JSONRPCMessageKind: Decodable {
389389
case request(id: String, method: String)
390390
case notification(method: String)
391-
case response(id: String)
391+
/// A response; `id` is `nil` for an error response whose `id` is
392+
/// `null`, which answers a request whose `id` could not be read and
393+
/// names no request (JSON-RPC 2.0 §5).
394+
case response(id: String?)
395+
/// An answer (a `result` or an `error`) whose `id` is a string or an
396+
/// integer but whose `jsonrpc` is not `"2.0"`. It is answered with
397+
/// -32600 and `"id": null`, and still given to the server, which fails
398+
/// the request it names instead of leaving it waiting.
399+
case invalidResponse(id: String)
392400
/// A message with a string `method` that is neither a valid request
393401
/// nor a valid notification: its `id` is not a string or an integer, or
394402
/// its `jsonrpc` is not `"2.0"`. It must be answered with -32600, using
@@ -408,6 +416,21 @@ package enum JSONRPCMessageKind: Decodable {
408416
self = decoded
409417
}
410418

419+
/// The error for data that could not be classified as a JSON-RPC message.
420+
static func classificationError(for data: Data) -> MCPError {
421+
// JSON-RPC 2.0 §5.1 reserves -32700 for invalid JSON. Scalars and arrays
422+
// are valid JSON, but are not single messages on the HTTP transport.
423+
// JSONDecoder, unlike JSONSerialization, reads a number out of range
424+
// such as `1e400` as valid JSON.
425+
struct AnyJSON: Decodable { init(from decoder: Decoder) {} }
426+
do {
427+
_ = try JSONDecoder().decode(AnyJSON.self, from: data)
428+
return .invalidRequest("Invalid JSON-RPC message")
429+
} catch {
430+
return .parseError("Invalid JSON-RPC message")
431+
}
432+
}
433+
411434
/// Classifies a JSON-RPC object.
412435
///
413436
/// A message with a string `method` is a request when it has an `id`
@@ -432,8 +455,19 @@ package enum JSONRPCMessageKind: Decodable {
432455
let reason = InvalidRequestReason.id(try? container.decode(Value.self, forKey: .id))
433456
self = .invalid(method: method, id: nil, reason: reason)
434457
}
435-
} else if container.contains(.result) || container.contains(.error), let id {
436-
self = .response(id: id.description)
458+
} else if container.contains(.result) || container.contains(.error),
459+
id != nil || (isNull && container.contains(.error))
460+
{
461+
// JSON-RPC 2.0 §5 requires the version on responses too.
462+
guard (try? container.decode(String.self, forKey: .jsonrpc)) == "2.0" else {
463+
guard let id else {
464+
throw DecodingError.dataCorruptedError(
465+
forKey: .jsonrpc, in: container, debugDescription: InvalidRequestReason.jsonrpc)
466+
}
467+
self = .invalidResponse(id: id.description)
468+
return
469+
}
470+
self = .response(id: id?.description)
437471
} else {
438472
throw DecodingError.dataCorrupted(
439473
DecodingError.Context(

‎Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,11 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding {
204204
}
205205

206206
switch kind {
207-
case .response(let id):
207+
case .response(nil):
208+
// The server's -32600 for an answer it could not read, whose POST
209+
// was already answered.
210+
logger.debug("Outgoing response without an id dropped")
211+
case .response(let id?):
208212
routeResponse(data, requestID: id)
209213
if id == initializeRequestID {
210214
initializeRequestID = nil
@@ -223,6 +227,8 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding {
223227
}
224228
case .invalid(let method, _, _):
225229
logger.warning("Invalid outgoing message dropped", metadata: ["method": "\(method)"])
230+
case .invalidResponse:
231+
logger.warning("Invalid outgoing response dropped")
226232
}
227233
}
228234

@@ -304,7 +310,7 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding {
304310
guard let messageKind = JSONRPCMessageKind(data: body) else {
305311
return .error(
306312
statusCode: 400,
307-
.parseError("Invalid JSON-RPC message"),
313+
JSONRPCMessageKind.classificationError(for: body),
308314
sessionID: sessionID
309315
)
310316
}
@@ -372,6 +378,13 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding {
372378
incomingContinuation.yield(body)
373379
return .accepted(headers: sessionHeaders())
374380

381+
case .invalidResponse:
382+
// Validated like any POST, then given to the server so that the
383+
// request it names fails instead of waiting.
384+
incomingContinuation.yield(body)
385+
return .error(
386+
statusCode: 400, .invalidRequest(InvalidRequestReason.jsonrpc), sessionID: sessionID)
387+
375388
case .request(let id, _):
376389
return handleJSONRPCRequest(body, requestID: id, request: request)
377390

‎Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,11 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding {
202202
}
203203

204204
switch kind {
205-
case .response(let id):
205+
case .response(nil):
206+
// The server's -32600 for an answer it could not read, whose POST
207+
// was already answered.
208+
logger.debug("Outgoing response without an id dropped")
209+
case .response(let id?):
206210
guard let exchange = exchanges.removeValue(forKey: id) else {
207211
logger.debug("No waiter for response", metadata: ["requestID": "\(id)"])
208212
return
@@ -230,6 +234,8 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding {
230234

231235
case .invalid(let method, _, _):
232236
logger.warning("Invalid outgoing message dropped", metadata: ["method": "\(method)"])
237+
case .invalidResponse:
238+
logger.warning("Invalid outgoing response dropped")
233239
}
234240
}
235241

@@ -295,7 +301,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding {
295301
let normalized = try? JSONSerialization.data(withJSONObject: json, options: [.withoutEscapingSlashes]),
296302
let messageKind = JSONRPCMessageKind(data: normalized)
297303
else {
298-
return .error(statusCode: 400, .parseError("Invalid JSON-RPC message"))
304+
return .error(statusCode: 400, JSONRPCMessageKind.classificationError(for: body))
299305
}
300306

301307
// One probe for the id and the `_meta` version.
@@ -304,7 +310,7 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding {
304310
switch messageKind {
305311
case .request: requestID = fields.id
306312
case .invalid(_, let id, _): requestID = id
307-
case .notification, .response: break
313+
case .notification, .response, .invalidResponse: break
308314
}
309315

310316
// Validators see the versions the server serves, so a version it
@@ -326,6 +332,12 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding {
326332
// answered with -32600 before the headers are checked, not 202.
327333
return .error(statusCode: 400, .invalidRequest(reason), id: requestID)
328334

335+
case .invalidResponse:
336+
// Validated like any POST, then given to the server so that the
337+
// request it names fails instead of waiting.
338+
incomingContinuation.yield(body)
339+
return .error(statusCode: 400, .invalidRequest(InvalidRequestReason.jsonrpc))
340+
329341
case .notification(let method) where method == CancelledNotification.name:
330342
if let mismatch = Self.standardHeaderError(request, fields: fields) {
331343
return .error(statusCode: 400, mismatch)

‎Sources/MCP/Client/Client.swift‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1758,22 +1758,27 @@ public actor Client {
17581758
return (try? JSONDecoder().decode(Probe.self, from: data))?.params?._meta?.progressToken
17591759
}
17601760

1761-
/// The `id` of a message without a `method` (a response, maybe one that
1762-
/// does not decode), when it is a string or an integer.
1761+
/// The `id` of an answer (a response, maybe one that does not decode),
1762+
/// when it is a string or an integer: a message without a `method`, or
1763+
/// with a `result` or an `error` and no string `method`, as
1764+
/// `HTTPClientTransport` reads answers to end their stream.
17631765
private static func responseID(of data: Data) -> ID? {
17641766
struct Probe: Decodable {
17651767
let id: ID?
1766-
let hasMethod: Bool
1767-
private enum Keys: String, CodingKey { case id, method }
1768+
let isAnswer: Bool
1769+
private enum Keys: String, CodingKey { case id, method, result, error }
17681770
init(from decoder: Decoder) throws {
17691771
let container = try decoder.container(keyedBy: Keys.self)
17701772
// `ID` reads `null` as `""`.
17711773
let isNull = (try? container.decodeNil(forKey: .id)) == true
17721774
id = isNull ? nil : try? container.decode(ID.self, forKey: .id)
1773-
hasMethod = container.contains(.method)
1775+
let hasStringMethod = (try? container.decode(String.self, forKey: .method)) != nil
1776+
isAnswer =
1777+
!container.contains(.method)
1778+
|| (!hasStringMethod && (container.contains(.result) || container.contains(.error)))
17741779
}
17751780
}
1776-
guard let probe = try? JSONDecoder().decode(Probe.self, from: data), !probe.hasMethod else { return nil }
1781+
guard let probe = try? JSONDecoder().decode(Probe.self, from: data), probe.isAnswer else { return nil }
17771782
return probe.id
17781783
}
17791784

0 commit comments

Comments
 (0)