From 50b6b739b6487d0414eda6d3b8ae3252afa6e2a2 Mon Sep 17 00:00:00 2001 From: canarik Date: Sun, 29 Nov 2026 17:34:39 +0300 Subject: [PATCH 1/5] fix: Reject an HTTP request that also has a result or an error A POST whose JSON-RPC object has a string `method`, an `id` and also a `result` or an `error` was never answered. `JSONRPCMessageKind` checks `method` first and called it a request, so `StatefulHTTPServerTransport` opened an SSE stream and kept the request's `httpRequestContexts` and `openRequestIDs` entries, and `StatelessHTTPServerTransport` created an exchange and waited. `Server` tries `AnyResponse` before `AnyRequest`, and `Response` ignores `method`, so it read the body as a response to an unknown request and sent nothing. The POST hung, the stateful transport kept that state until the session ended, and an `initialize` with a `result` opened a session in which a real `initialize` was then refused. Fix: classify such a message as `.invalid` when its `id` is readable, so both transports answer HTTP 400 with -32600 and the `id`, and keep no state for it. An `id` that cannot be read keeps its own reason. A batch item of this shape on the other transports now gets -32600 as well, since `Server.Batch.Item` uses the same classifier. Adds tests to `RequestIDValidationTests` for both HTTP transports, an `initialize` with a `result`, the classifier, and a batch item. Introduced in 6112a39 ("V0.11.x (#199)"). --- .../HTTPServer/HTTPServerTypes.swift | 15 +- .../StatefulHTTPServerTransport.swift | 3 + .../StatelessHTTPServerTransport.swift | 3 + Tests/MCPTests/RequestIDValidationTests.swift | 144 +++++++++++++++++- 4 files changed, 159 insertions(+), 6 deletions(-) diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index 160a19c4..54e9b888 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -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 { @@ -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 `""`. @@ -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 { @@ -525,6 +531,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 { diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index b4ffa40a..89905b02 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -392,6 +392,9 @@ 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. return .error( statusCode: 400, .invalidRequest(reason), id: id, sessionID: sessionID) } diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index d5d75a52..7a014b00 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -330,6 +330,9 @@ 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. return .error(statusCode: 400, .invalidRequest(reason), id: requestID) case .invalidResponse: diff --git a/Tests/MCPTests/RequestIDValidationTests.swift b/Tests/MCPTests/RequestIDValidationTests.swift index f0d90a3d..ad4e17a9 100644 --- a/Tests/MCPTests/RequestIDValidationTests.swift +++ b/Tests/MCPTests/RequestIDValidationTests.swift @@ -6,7 +6,9 @@ import Testing // A request's id must be a string or an integer and not null; `""` is a // valid id. A message with a `method` and an invalid `id` or `jsonrpc` is // an invalid request, answered with -32600, never a notification -// (JSON-RPC 2.0 §5; basic/index.mdx "Requests"). +// (JSON-RPC 2.0 §5; basic/index.mdx "Requests"). So is a message with a +// `method` and an `id` that also has a `result` or an `error`; its -32600 +// carries the `id`. /// Ids a request may have, as JSON, with the id the answer echoes. private let validIDs: [(json: String, echo: Value)] = [ @@ -145,6 +147,24 @@ struct StreamRequestIDTests { #expect(items[2].objectValue?["result"] != nil) } + @Test("A batch item with a method and a result or an error gets -32600 with its id") + func batchRequestWithAnswerMember() async throws { + let batch = + #"[{"jsonrpc":"2.0","id":3,"method":"tools/list","result":{}},{"jsonrpc":"2.0","id":4,"method":"tools/list","error":{"code":-32603,"message":"x"}},{"jsonrpc":"2.0","id":2,"method":"tools/list"}]"# + let replies = try await replies(to: batch) + let items = try #require(replies.first?.arrayValue) + #expect(items.count == 3) + #expect(items[0].objectValue?["id"] == 3) + #expect(items[0].objectValue?["error"]?.objectValue?["code"] == -32600) + #expect( + items[0].objectValue?["error"]?.objectValue?["message"] + == "Invalid Request: result and error must not appear in a request") + #expect(items[1].objectValue?["id"] == 4) + #expect(items[1].objectValue?["error"]?.objectValue?["code"] == -32600) + #expect(items[2].objectValue?["id"] == 2) + #expect(items[2].objectValue?["result"] != nil) + } + @Test("A batch of responses gets no reply") func batchOfResponses() async throws { let batch = @@ -259,6 +279,15 @@ struct StreamRequestIDTests { @Suite("Request ids over the stateless HTTP transport", .timeLimit(.minutes(1))) struct StatelessHTTPRequestIDTests { private func post(_ body: String, headers extra: [String: String] = [:]) async throws -> HTTPResponse { + try #require(try await post(body, headers: extra, within: .seconds(30)), "No answer within 30 seconds") + } + + /// Like `post`, but returns `nil` when `handleRequest` has not returned + /// within `limit`: a request nothing answers waits until the transport + /// stops. + private func post( + _ body: String, headers extra: [String: String] = [:], within limit: Duration + ) async throws -> HTTPResponse? { let server = await makeServer() let transport = StatelessHTTPServerTransport() try await server.start(transport: transport) @@ -267,9 +296,12 @@ struct StatelessHTTPRequestIDTests { HTTPHeaderName.protocolVersion: "2025-11-25", ] headers.merge(extra) { $1 } - let response = await transport.handleRequest( - HTTPRequest(method: "POST", headers: headers, body: Data(body.utf8))) + let request = HTTPRequest(method: "POST", headers: headers, body: Data(body.utf8)) + let result = await outcome(within: limit) { await transport.handleRequest(request) } await server.stop() + // Ends an exchange still waiting, so a timed-out `handleRequest` returns. + await transport.disconnect() + guard case .returned(let response) = result else { return nil } return response } @@ -317,6 +349,28 @@ struct StatelessHTTPRequestIDTests { #expect(response.statusCode == 400) #expect(try decode(response.bodyData).objectValue?["error"]?.objectValue?["code"] == -32600) } + + @Test( + "A request that also has a result or an error gets 400 and -32600 with its id", + arguments: [#""result":{}"#, #""result":null"#, #""error":{"code":-32603,"message":"x"}"#], [false, true]) + func answerMember(_ member: String, stateless: Bool) async throws { + let params = + stateless + ? #","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}"# + : "" + let body = #"{"jsonrpc":"2.0","id":"x1","method":"tools/list"\#(params),\#(member)}"# + let headers = + stateless ? [HTTPHeaderName.protocolVersion: "2026-07-28", MCPRequestHeaders.method: "tools/list"] : [:] + let response = try #require( + try await post(body, headers: headers, within: .seconds(5)), "No answer within 5 seconds") + #expect(response.statusCode == 400) + let decoded = try decode(response.bodyData) + #expect(decoded.objectValue?["id"] == "x1") + #expect(decoded.objectValue?["error"]?.objectValue?["code"] == -32600) + #expect( + decoded.objectValue?["error"]?.objectValue?["message"] + == "Invalid Request: result and error must not appear in a request") + } } @Suite("Request ids over the stateful HTTP transport") @@ -381,4 +435,88 @@ struct StatefulHTTPRequestIDTests { } if case .invalid? = kind(#"{"id":1,"method":"m"}"#) {} else { Issue.record("no jsonrpc") } } + + @Test( + "A request that also has a result or an error gets 400 and -32600 with its id, and no stream", + arguments: [#""result":{}"#, #""result":null"#, #""error":{"code":-32603,"message":"x"}"#]) + func answerMember(_ member: String) async throws { + let transport = StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + try await transport.connect() + let response = await transport.handleRequest( + HTTPRequest( + method: "POST", + headers: ["Content-Type": "application/json", "Accept": "application/json, text/event-stream"], + body: Data(#"{"jsonrpc":"2.0","id":"x1","method":"tools/list",\#(member)}"#.utf8))) + // Read before disconnecting, which drops every request's context. + let context = await transport.httpRequestContext(for: .string("x1")) + await transport.disconnect() + #expect(response.statusCode == 400) + #expect(context == nil) + let body = try decode(response.bodyData) + #expect(body.objectValue?["id"] == "x1") + #expect(body.objectValue?["error"]?.objectValue?["code"] == -32600) + } + + @Test("An initialize that also has a result opens no session", arguments: [false, true]) + func initializeWithAnswerMember(defaultValidators: Bool) async throws { + let transport = + defaultValidators + ? StatefulHTTPServerTransport() + : StatefulHTTPServerTransport(validationPipeline: StandardValidationPipeline(validators: [])) + try await transport.connect() + func post(_ body: String) async -> HTTPResponse { + await transport.handleRequest( + HTTPRequest( + method: "POST", + headers: ["Content-Type": "application/json", "Accept": "application/json, text/event-stream"], + body: Data(body.utf8))) + } + let mixed = await post(#"{"jsonrpc":"2.0","id":1,"method":"initialize","result":{}}"#) + // With the default validators the session validator answers first, + // so only the status and the missing session are the same for both. + #expect(mixed.statusCode == 400) + #expect(mixed.headers[HTTPHeaderName.sessionID] == nil) + let initialize = await post( + #"{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"c","version":"1"}}}"# + ) + #expect(initialize.statusCode == 200) + #expect(initialize.headers[HTTPHeaderName.sessionID] != nil) + await transport.disconnect() + } + + @Test("A method with an id and a result or an error is invalid, not a request") + func classificationOfAnswerMembers() { + func kind(_ json: String) -> JSONRPCMessageKind? { JSONRPCMessageKind(data: Data(json.utf8)) } + let members = [ + #""result":{}"#, #""result":null"#, #""error":{"code":-32603,"message":"x"}"#, #""error":5"#, + #""result":{},"error":{"code":-32603,"message":"x"}"#, + ] + for member in members { + for (json, id) in [(#""x1""#, ID.string("x1")), ("7", ID.number(7))] { + if case .invalid(let method, let read, let reason)? = kind( + #"{"jsonrpc":"2.0","id":\#(json),"method":"m",\#(member)}"#) + { + #expect(method == "m") + #expect(read == id) + #expect(reason == InvalidRequestReason.resultOrError) + } else { + Issue.record("id \(json) with \(member)") + } + } + // An id that cannot be read keeps its own reason. + for (json, value) in [("null", Value.null), ("true", Value.bool(true))] { + if case .invalid(_, .none, let reason)? = kind( + #"{"jsonrpc":"2.0","id":\#(json),"method":"m",\#(member)}"#) + { + #expect(reason == InvalidRequestReason.id(value)) + } else { + Issue.record("id \(json) with \(member)") + } + } + // Without an id the message stays a notification. + if case .notification? = kind(#"{"jsonrpc":"2.0","method":"m",\#(member)}"#) {} else { + Issue.record("no id with \(member)") + } + } + } } From cc9b3379d8a1049500d72a97b7ad196bc2d7e7f4 Mon Sep 17 00:00:00 2001 From: canarik Date: Sun, 29 Nov 2026 18:36:29 +0300 Subject: [PATCH 2/5] docs: Add a CHANGELOG entry for a request that also has a result or an error - Add a CHANGELOG entry under Fixes: a request with a string or integer `id` that also has a `result` or an `error` gets -32600 with its `id` (HTTP 400, or per item in a batch), an answer that carries a `method` is refused over HTTP, and a single such message on the other transports is still read as a response. --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b91d540..72376c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -157,6 +157,13 @@ 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` is + refused the same way over HTTP; before, `Server` took it as the answer while its POST was never + answered. 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 still read as a response. - 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 From 19d405635b876f5da212fc76c1d50f0de840277f Mon Sep 17 00:00:00 2001 From: canarik Date: Sun, 29 Nov 2026 20:25:13 +0300 Subject: [PATCH 3/5] fix: Give the server a request with a result it reads as an answer A client may answer a server-to-client request with a message that also carries a `method`. The HTTP server transports answer such a message with -32600, but they did not give it to `Server`, so the server's request was never resolved and waited forever. Fix: when `Server` reads a request that also has a `result` or an `error` as a response (`AnyResponse` decodes the bytes the transport has), both transports still give it to the server after the -32600, as they do for an answer whose `jsonrpc` is wrong. One `Server` would read as a request is not given to it, since the transport has refused it, and neither is a request whose `id` cannot be read. Adds tests: a pending `roots/list` answered this way completes, and only the message `Server` reads as a response reaches it, on both transports. --- CHANGELOG.md | 9 +-- .../HTTPServer/HTTPServerTypes.swift | 10 +++ .../StatefulHTTPServerTransport.swift | 7 ++- .../StatelessHTTPServerTransport.swift | 7 ++- Tests/MCPTests/HTTPServerTransportTests.swift | 62 +++++++++++++++++++ Tests/MCPTests/RequestIDValidationTests.swift | 27 ++++++++ 6 files changed, 116 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72376c89..d42499d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -160,10 +160,11 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha - 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` is - refused the same way over HTTP; before, `Server` took it as the answer while its POST was never - answered. 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 still read as a response. + 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, the stateful transport + gave it to `Server` but never answered the POST, and the stateless one did neither. 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 diff --git a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift index 54e9b888..bc442418 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/HTTPServerTypes.swift @@ -495,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? { diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift index 89905b02..d7788bff 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatefulHTTPServerTransport.swift @@ -394,7 +394,12 @@ public actor StatefulHTTPServerTransport: Transport, HTTPContextProviding { // notification. // // A request that also has a `result` or an `error` gets -32600 - // with its `id`, and no stream is opened for it. + // 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) } diff --git a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift index 7a014b00..b5164b68 100644 --- a/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift +++ b/Sources/MCP/Base/Transports/HTTPServer/StatelessHTTPServerTransport.swift @@ -332,7 +332,12 @@ public actor StatelessHTTPServerTransport: Transport, HTTPContextProviding { // 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. + // 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: diff --git a/Tests/MCPTests/HTTPServerTransportTests.swift b/Tests/MCPTests/HTTPServerTransportTests.swift index 408b2c44..0a1d71ad 100644 --- a/Tests/MCPTests/HTTPServerTransportTests.swift +++ b/Tests/MCPTests/HTTPServerTransportTests.swift @@ -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") } diff --git a/Tests/MCPTests/RequestIDValidationTests.swift b/Tests/MCPTests/RequestIDValidationTests.swift index ad4e17a9..a0394c95 100644 --- a/Tests/MCPTests/RequestIDValidationTests.swift +++ b/Tests/MCPTests/RequestIDValidationTests.swift @@ -371,6 +371,33 @@ struct StatelessHTTPRequestIDTests { decoded.objectValue?["error"]?.objectValue?["message"] == "Invalid Request: result and error must not appear in a request") } + + @Test("A request with a result or an error reaches the server only when the server reads it as a response") + func answerMemberReachesServer() async throws { + let transport = StatelessHTTPServerTransport() + try await transport.connect() + let headers = [ + "Content-Type": "application/json", "Accept": "application/json", + HTTPHeaderName.protocolVersion: "2025-11-25", + ] + // 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) + for body in [answer, request, nullID] { + let response = await transport.handleRequest(HTTPRequest(method: "POST", headers: headers, body: body)) + #expect(response.statusCode == 400) + } + await transport.disconnect() + var received: [Data] = [] + do { + for try await data in await transport.receive() { received.append(data) } + } catch {} + #expect(received == [answer]) + } } @Suite("Request ids over the stateful HTTP transport") From 29aea3464ac4b551e046140b9992c83ca098ddb5 Mon Sep 17 00:00:00 2001 From: canarik Date: Sun, 29 Nov 2026 20:45:56 +0300 Subject: [PATCH 4/5] docs: Correct the CHANGELOG note on the stateless transport The entry said that, before this change, the stateless HTTP transport neither gave an answer carrying a `method` to `Server` nor answered the POST. It did give it to `Server`, under the internal `id` it puts in place of the client's, so the answer never matched the pending request. Neither transport answered the POST. --- CHANGELOG.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d42499d0..6efad545 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -161,10 +161,11 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha 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, the stateful transport - gave it to `Server` but never answered the POST, and the stateless one did neither. 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. + 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 From 67ceb82c83d4b37523d253507738176d4b30051e Mon Sep 17 00:00:00 2001 From: canarik Date: Sun, 29 Nov 2026 21:08:55 +0300 Subject: [PATCH 5/5] test: Answer a server request with a method over the stateless transport The stateless transport had no end-to-end test for an answer that also carries a `method`; only the hand-off to its receive stream was tested. The new test answers the round-trip bridge's `elicitation/create` at 2025-11-25 with an extra `method`, and checks that the POST gets 400 and -32600 with the `id` and that the tool call still completes. Without the hand-off to `Server` it times out. --- Tests/MCPTests/RequestLifecycleTests.swift | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/Tests/MCPTests/RequestLifecycleTests.swift b/Tests/MCPTests/RequestLifecycleTests.swift index 805a5a13..f9701109 100644 --- a/Tests/MCPTests/RequestLifecycleTests.swift +++ b/Tests/MCPTests/RequestLifecycleTests.swift @@ -885,6 +885,52 @@ struct ServerReplyTests { #expect(content?.first?.objectValue?["text"] == "confirmed") } + @Test("Behind the stateless HTTP transport an answer with a method completes the server's request") + @available(*, deprecated, message: "Uses the deprecated sampling and logging APIs (SEP-2577)") + func sessionlessAnswerWithMethod() async throws { + let server = await makeServer() + let transport = StatelessHTTPServerTransport() + try await server.start(transport: transport) + defer { Task { await server.stop() } } + + let response = await sessionlessPost( + transport, #"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"confirm"}}"#, + accept: "application/json, text/event-stream") + guard case .stream(let events, _) = response else { + Issue.record("expected an SSE stream, got \(response.statusCode)") + return + } + // Without the answer the tool call waits until the transport stops. + let exchange = await outcome(within: .seconds(10)) { + var iterator = events.makeAsyncIterator() + let elicitation = try message(try #require(await iterator.next())) + let id = try #require(elicitation.objectValue?["id"]) + // The transport refuses the POST, and the server takes it as the answer. + let answer: Value = [ + "jsonrpc": "2.0", "id": id, "method": "elicitation/create", + "result": ["action": "accept", "content": [:]], + ] + let refused = await sessionlessPost( + transport, String(decoding: try JSONEncoder().encode(answer), as: UTF8.self)) + // Skips `: keep-alive` comments. + while let event = try await iterator.next() { + guard let result = try? message(event) else { continue } + return (id, refused.statusCode, refused.bodyData, result) + } + throw MCPError.internalError("The stream ended without the result") + } + guard case .returned(let (id, status, body, result)) = exchange else { + Issue.record("The tool call never completed: \(exchange)") + return + } + #expect(status == 400) + let error = try JSONDecoder().decode(Value.self, from: try #require(body)) + expectWire(error, matches: ["jsonrpc": "2.0", "id": id, "error": ["code": -32600]]) + #expect(result.objectValue?["id"] == 1) + let content = result.objectValue?["result"]?.objectValue?["content"]?.arrayValue + #expect(content?.first?.objectValue?["text"] == "confirmed") + } + @Test("Behind the stateless HTTP transport the hooks gate handshake requests") @available(*, deprecated, message: "Uses the deprecated sampling and logging APIs (SEP-2577)") func sessionlessHooks() async throws {