Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,15 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha
`Process` on iOS, tvOS, watchOS or visionOS. CI builds every target for the iOS device SDK and
runs the tests on an iOS simulator; `scripts/ci/apple-platform.sh` also takes tvOS, watchOS,
visionOS and Mac Catalyst, which CI does not check.
- A request with a string or integer `id` that also has a `result` or an `error` gets -32600
with its `id` (HTTP 400) instead of an SSE stream or an exchange that nothing answered; the
stateful HTTP transport kept that request's state until the session ended, and an `initialize`
with a `result` opened a session. An answer to a server request that also carries a `method`
gets the same 400 over HTTP, and `Server` takes it as the answer; before, neither transport
answered the POST, and the stateless one gave the answer to `Server` under another `id`, so its
request was never completed. On stdio, Network and in-memory transports such an item in a
JSON-RPC batch gets its own -32600 instead of being served as a request, while a single one is
handled by `Server` as before.
- 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
and left unanswered. `""` is a valid id: the HTTP transports serve it, and `Request` no longer
Expand Down
25 changes: 22 additions & 3 deletions Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -398,9 +398,10 @@ package enum JSONRPCMessageKind: Decodable {
/// the request it names instead of leaving it waiting.
case invalidResponse(id: String)
/// A message with a string `method` that is neither a valid request
/// nor a valid notification: its `id` is not a string or an integer, or
/// its `jsonrpc` is not `"2.0"`. It must be answered with -32600, using
/// `id` when it is a string or an integer and `null` otherwise.
/// nor a valid notification: its `id` is not a string or an integer,
/// its `jsonrpc` is not `"2.0"`, or it has an `id` and also a `result`
/// or an `error`. It must be answered with -32600, using `id` when it
/// is a string or an integer and `null` otherwise.
case invalid(method: String, id: ID?, reason: String)

private enum CodingKeys: String, CodingKey {
Expand Down Expand Up @@ -437,6 +438,9 @@ package enum JSONRPCMessageKind: Decodable {
/// member and a notification when it has none, whatever the type of
/// the `id`: an `id` that is not a string or an integer makes it
/// ``invalid(method:id:reason:)``, not a notification (JSON-RPC 2.0 §5).
/// A `result` or an `error` beside a readable `id` makes it invalid too:
/// the message would be both a request and a response. `Server` reads a
/// single such message as a response, so nothing would answer it.
package init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// `ID` reads `null` as `""`.
Expand All @@ -448,6 +452,8 @@ package enum JSONRPCMessageKind: Decodable {
self = .invalid(method: method, id: id, reason: InvalidRequestReason.jsonrpc)
} else if !container.contains(.id) {
self = .notification(method: method)
} else if id != nil, container.contains(.result) || container.contains(.error) {
self = .invalid(method: method, id: id, reason: InvalidRequestReason.resultOrError)
} else if let id {
self = .request(id: id.description, method: method)
} else {
Expand Down Expand Up @@ -489,6 +495,16 @@ package enum JSONRPCMessageKind: Decodable {
return false
}

/// Whether `data`, classified as this message, is a request with a
/// `result` or an `error` that `Server` reads as a response. The HTTP
/// transports answer it with -32600 and still give it to the server, so
/// that it can answer one of the server's own requests; one `Server`
/// would read as a request is not given to it, since it was refused.
func readsAsAnswer(_ data: Data) -> Bool {
guard case .invalid(_, _, InvalidRequestReason.resultOrError) = self else { return false }
return (try? JSONDecoder().decode(AnyResponse.self, from: data)) != nil
}

/// A message's `id`, rendered as a string; `nil` when absent or not a
/// string or an integer that fits `Int`.
package static func extractID(from json: [String: Any]) -> String? {
Expand Down Expand Up @@ -525,6 +541,9 @@ enum InvalidRequestReason {
/// `jsonrpc` is missing or not `"2.0"`.
static let jsonrpc = "jsonrpc must be \"2.0\""

/// A request with a readable `id` also has a `result` or an `error`.
static let resultOrError = "result and error must not appear in a request"

/// The problem with an `id` that is not a string or an integer, as
/// decoded into a ``Value``; `nil` is a number too large to decode.
static func id(_ value: Value?) -> String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,14 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding {
// JSON-RPC 2.0 §5: a request whose `id` cannot be read is
// answered with -32600 and `"id": null`, not treated as a
// notification.
//
// A request that also has a `result` or an `error` gets -32600
// with its `id`, and no stream is opened for it. One the server
// reads as a response is still given to it, so that a server
// request it answers does not wait forever.
if messageKind.readsAsAnswer(body) {
incomingContinuation.yield(body)
}
return .error(
statusCode: 400, .invalidRequest(reason), id: id, sessionID: sessionID)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,14 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding {
case .invalid(_, _, let reason):
// JSON-RPC 2.0 §5: a request whose `id` or `jsonrpc` is invalid is
// answered with -32600 before the headers are checked, not 202.
//
// A request that also has a `result` or an `error` gets -32600
// too, instead of an exchange that `Server` never answers. One the
// server reads as a response is still given to it, so that a
// server request it answers does not wait forever.
if messageKind.readsAsAnswer(body) {
incomingContinuation.yield(body)
}
return .error(statusCode: 400, .invalidRequest(reason), id: requestID)

case .invalidResponse:
Expand Down
62 changes: 62 additions & 0 deletions Tests/MCPTests/HTTPServerTransportTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,68 @@ struct StatefulHTTPServerTransportTests {
await server.stop()
}

@Test("A server request answered with a method beside the result is resolved, and the POST gets 400")
@available(*, deprecated, message: "listRoots is deprecated by SEP-2577")
func testAnswerWithMethodResolvesServerRequest() async throws {
let transport = makeStatefulTransport()
let server = Server(name: "s", version: "1")
try await server.start(transport: transport)

let initialize =
#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{"roots":{}},"clientInfo":{"name":"c","version":"1"}}}"#
let initResponse = await transport.handleRequest(makeStatefulPOSTRequest(body: Data(initialize.utf8)))
let sessionID = try #require(initResponse.headers[HTTPHeaderName.sessionID])
_ = try await firstMessage(of: initResponse) { $0.objectValue?["result"] != nil }
_ = await transport.handleRequest(
makeStatefulPOSTRequest(
body: Data(#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#.utf8), sessionID: sessionID))

let get = await transport.handleRequest(makeGETRequest(sessionID: sessionID))
let roots = Task { try await server.listRoots() }
let request = try await firstMessage(of: get) { $0.objectValue?["method"] == .string(ListRoots.name) }
let id = try #require(request.objectValue?["id"])

let answer = try JSONEncoder().encode(
Value.object([
"jsonrpc": "2.0", "id": id, "method": .string(ListRoots.name), "result": ["roots": []],
]))
let response = await transport.handleRequest(makeStatefulPOSTRequest(body: answer, sessionID: sessionID))
#expect(response.statusCode == 400)
let json = try JSONDecoder().decode(Value.self, from: try #require(response.bodyData))
expectWire(json, matches: ["jsonrpc": "2.0", "id": id, "error": ["code": -32600]])

let result = await outcome(within: .seconds(5)) { try await roots.value }
#expect(!result.didTimeOut, "listRoots never completed")
#expect(result.error == nil)
await server.stop()
}

@Test("A request with a result or an error reaches the server only when the server reads it as a response")
func testRequestWithAnswerReachesServerAsResponseOnly() async throws {
let transport = makeStatefulTransport()
let sessionID = try await initializeSession(transport: transport)
// The server reads the first as a response and the second as a
// request, which the transport has already refused. The third, a
// request whose `id` cannot be read, is refused for its `id` and
// is not given to the server either.
let answer = Data(#"{"jsonrpc":"2.0","id":"r1","method":"m","result":{}}"#.utf8)
let request = Data(#"{"jsonrpc":"2.0","id":"r2","method":"m","error":5}"#.utf8)
let nullID = Data(#"{"jsonrpc":"2.0","id":null,"method":"m","result":{}}"#.utf8)
var statuses: [Int] = []
for body in [answer, request, nullID] {
statuses.append(
await transport.handleRequest(makeStatefulPOSTRequest(body: body, sessionID: sessionID)).statusCode)
}
await transport.disconnect()

#expect(statuses == [400, 400, 400])
var received: [Data] = []
do {
for try await data in await transport.receive() { received.append(data) }
} catch {}
#expect(received == [answer])
}

/// The first JSON-RPC message of an SSE response that matches `predicate`.
private func firstMessage(of response: HTTPResponse, where predicate: (Value) -> Bool) async throws -> Value {
guard case .stream(let stream, _) = response else { throw MCPError.internalError("Not an SSE response") }
Expand Down
Loading
Loading