Skip to content

Commit 0d80a17

Browse files
authored
Merge pull request #406 from canarik/oss/http-client-json-body-limit
fix: limit JSON response bodies to 16 MiB in the HTTP client
2 parents afb87cb + f92e0cf commit 0d80a17

5 files changed

Lines changed: 213 additions & 11 deletions

File tree

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

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@ import Logging
3737
/// stream with `internalError`. On a POST's stream the request fails and the
3838
/// stream is not resumed; the GET stream reconnects after its backoff,
3939
/// without `Last-Event-ID`, since a replay would repeat the event, which is
40-
/// lost.
40+
/// lost. An `application/json` response body longer than 16 MiB fails its
41+
/// request with `internalError`, and is not read further.
4142
///
4243
/// ## Example Usage
4344
///
@@ -706,7 +707,18 @@ public actor HTTPClientTransport: Transport {
706707
after: lastEventID, retry: retry, awaiting: awaited, request: message)
707708
}
708709
} else if contentType.contains(ContentType.json) {
709-
let buffer = try await body.collect()
710+
// As on the SSE path, a body over the limit is not read whole:
711+
// the read stops past the limit, the request fails, and its
712+
// download is cancelled.
713+
guard httpResponse.expectedContentLength <= Int64(Self.maxJSONBodyLength) else {
714+
body.cancel()
715+
throw MCPError.internalError(Self.jsonBodyTooLong)
716+
}
717+
let buffer = try await body.collect(limit: Self.maxJSONBodyLength + 1)
718+
guard buffer.count <= Self.maxJSONBodyLength else {
719+
body.cancel()
720+
throw MCPError.internalError(Self.jsonBodyTooLong)
721+
}
710722
logger.trace("Received JSON response", metadata: ["size": "\(buffer.count)"])
711723
messageContinuation.yield(buffer)
712724
} else if httpResponse.statusCode != 202 || message.requestID != nil {
@@ -1344,6 +1356,14 @@ public actor HTTPClientTransport: Transport {
13441356
static let sseLineTooLong = "SSE line longer than 16 MiB"
13451357
static let sseEventTooLong = "SSE event data longer than 16 MiB"
13461358

1359+
/// The most bytes an `application/json` response body may hold: the
1360+
/// limit of the data of one SSE event.
1361+
static let maxJSONBodyLength = ServerSentEventParser.maxEventLength
1362+
1363+
/// The error of an `application/json` response body over
1364+
/// ``maxJSONBodyLength``.
1365+
static let jsonBodyTooLong = "JSON response body longer than 16 MiB"
1366+
13471367
/// Whether `error` is an SSE line or event over the parser's limits: a
13481368
/// resumed stream would replay it and fail the same way.
13491369
static func isOversizedEvent(_ error: Swift.Error) -> Bool {

‎Tests/MCPTests/HTTPClientTransportTests.swift‎

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2571,6 +2571,111 @@ import Testing
25712571
override func stopLoading() {}
25722572
}
25732573

2574+
/// Answers each request with an `application/json` body in chunks of at
2575+
/// most 1 MiB, as the script of its session says, and records the bytes
2576+
/// delivered.
2577+
private final class LongJSONBodyURLProtocol: URLProtocol {
2578+
struct Script: Sendable {
2579+
var length: Int
2580+
var contentLength: Int? = nil
2581+
/// Once more bytes than this went out (-1: before the first
2582+
/// chunk), the body waits up to 30 s for the loading to stop
2583+
/// before it sends the rest or ends.
2584+
var pauseAfter: Int? = nil
2585+
}
2586+
2587+
/// `@unchecked Sendable`: `lock` guards its state.
2588+
final class Log: @unchecked Sendable {
2589+
private let lock = NSLock()
2590+
private var bytes = 0
2591+
private var stopped = false
2592+
2593+
func delivered(_ count: Int) { lock.withLock { bytes += count } }
2594+
func stop() { lock.withLock { stopped = true } }
2595+
2596+
/// The bytes delivered, once the loading stopped or all chunks went out.
2597+
func deliveredWhenStopped() async throws -> Int {
2598+
let deadline = ContinuousClock.now + .seconds(30)
2599+
while !lock.withLock({ stopped }) && ContinuousClock.now < deadline {
2600+
try await Task.sleep(for: .milliseconds(5))
2601+
}
2602+
return lock.withLock { bytes }
2603+
}
2604+
}
2605+
2606+
static let chunk = 1 << 20
2607+
private static let keyHeader = "X-Long-Body-Key"
2608+
private static let lock = NSLock()
2609+
/// `nonisolated(unsafe)`: `lock` guards it.
2610+
nonisolated(unsafe) private static var scripts: [String: (Script, Log)] = [:]
2611+
2612+
/// A configuration whose requests get `script`, and the log of their bodies.
2613+
static func configuration(_ script: Script) -> (URLSessionConfiguration, Log) {
2614+
let key = UUID().uuidString
2615+
let log = Log()
2616+
lock.withLock { scripts[key] = (script, log) }
2617+
let configuration = URLSessionConfiguration.ephemeral
2618+
configuration.protocolClasses = [LongJSONBodyURLProtocol.self]
2619+
configuration.httpAdditionalHeaders = [keyHeader: key]
2620+
return (configuration, log)
2621+
}
2622+
2623+
override class func canInit(with request: URLRequest) -> Bool { true }
2624+
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
2625+
2626+
/// swift-corelibs-foundation traps on a callback after `stopLoading()`.
2627+
private let stateLock = NSLock()
2628+
private var stopped = false
2629+
private var log: Log?
2630+
private var isStopped: Bool { stateLock.withLock { stopped } }
2631+
2632+
override func startLoading() {
2633+
let key = request.value(forHTTPHeaderField: Self.keyHeader) ?? ""
2634+
guard let url = request.url, let (script, log) = Self.lock.withLock({ Self.scripts[key] }) else {
2635+
client?.urlProtocol(self, didFailWithError: URLError(.unsupportedURL))
2636+
return
2637+
}
2638+
stateLock.withLock { self.log = log }
2639+
var headers = ["Content-Type": "application/json"]
2640+
if let contentLength = script.contentLength { headers["Content-Length"] = String(contentLength) }
2641+
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: headers)!
2642+
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
2643+
let loader = SendableURLProtocol(self)
2644+
DispatchQueue.global().async { loader.value.stream(script) }
2645+
}
2646+
2647+
private func stream(_ script: Script) {
2648+
var sent = 0
2649+
var paused = false
2650+
while true {
2651+
guard !isStopped else { return }
2652+
if let pauseAfter = script.pauseAfter, sent > pauseAfter, !paused {
2653+
paused = true
2654+
let deadline = Date().addingTimeInterval(30)
2655+
while !isStopped && Date() < deadline { Thread.sleep(forTimeInterval: 0.005) }
2656+
guard !isStopped else { return }
2657+
}
2658+
guard sent < script.length else { break }
2659+
let count = min(Self.chunk, script.length - sent)
2660+
// Counted first, so the count is in place once the client has the bytes.
2661+
stateLock.withLock { log }?.delivered(count)
2662+
sent += count
2663+
client?.urlProtocol(self, didLoad: Data(repeating: 0x20, count: count))
2664+
}
2665+
guard !isStopped else { return }
2666+
stateLock.withLock { log }?.stop()
2667+
client?.urlProtocolDidFinishLoading(self)
2668+
}
2669+
2670+
override func stopLoading() {
2671+
let log = stateLock.withLock { () -> Log? in
2672+
stopped = true
2673+
return self.log
2674+
}
2675+
log?.stop()
2676+
}
2677+
}
2678+
25742679
@Suite("HTTP client transport sessions")
25752680
struct HTTPClientTransportSessionTests {
25762681
let endpoint = URL(string: "http://127.0.0.1:9/mcp")!
@@ -2695,6 +2800,82 @@ import Testing
26952800
#expect(delivered.isEmpty)
26962801
}
26972802

2803+
@Test("A JSON response body over 16 MiB fails the request and is not read further", .timeLimit(.minutes(1)))
2804+
func oversizedJSONBody() async throws {
2805+
let limit = ServerSentEventParser.maxEventLength
2806+
let chunk = LongJSONBodyURLProtocol.chunk
2807+
// The body pauses past the limit until the client stops it, so the
2808+
// bytes delivered show where the client stopped reading.
2809+
let (configuration, log) = LongJSONBodyURLProtocol.configuration(.init(length: 40 * chunk, pauseAfter: limit))
2810+
let transport = HTTPClientTransport(endpoint: endpoint, configuration: configuration, streaming: false)
2811+
try await transport.connect()
2812+
await #expect {
2813+
try await transport.send(request)
2814+
} throws: { error in
2815+
(error as? MCPError) == .internalError("JSON response body longer than 16 MiB")
2816+
}
2817+
let delivered = try await log.deliveredWhenStopped()
2818+
#expect(delivered == limit + chunk, "\(delivered) bytes were delivered")
2819+
await transport.disconnect()
2820+
var messages = 0
2821+
for try await _ in await transport.receive() { messages += 1 }
2822+
#expect(messages == 0)
2823+
}
2824+
2825+
@Test("A JSON response with a Content-Length over 16 MiB fails before its body is read", .timeLimit(.minutes(1)))
2826+
func oversizedJSONContentLength() async throws {
2827+
let chunk = LongJSONBodyURLProtocol.chunk
2828+
// The body waits before its first chunk until the client stops it.
2829+
let (configuration, log) = LongJSONBodyURLProtocol.configuration(
2830+
.init(length: 40 * chunk, contentLength: 40 * chunk, pauseAfter: -1))
2831+
let transport = HTTPClientTransport(endpoint: endpoint, configuration: configuration, streaming: false)
2832+
try await transport.connect()
2833+
await #expect {
2834+
try await transport.send(request)
2835+
} throws: { error in
2836+
(error as? MCPError) == .internalError("JSON response body longer than 16 MiB")
2837+
}
2838+
let delivered = try await log.deliveredWhenStopped()
2839+
#expect(delivered == 0, "\(delivered) bytes were delivered")
2840+
await transport.disconnect()
2841+
}
2842+
2843+
@Test("A JSON response body one byte over 16 MiB fails the request", .timeLimit(.minutes(1)))
2844+
func jsonBodyOneByteOverLimit() async throws {
2845+
let limit = ServerSentEventParser.maxEventLength
2846+
// The body stays open after its last byte until the client stops it.
2847+
let (configuration, log) = LongJSONBodyURLProtocol.configuration(.init(length: limit + 1, pauseAfter: limit))
2848+
let transport = HTTPClientTransport(endpoint: endpoint, configuration: configuration, streaming: false)
2849+
try await transport.connect()
2850+
await #expect {
2851+
try await transport.send(request)
2852+
} throws: { error in
2853+
(error as? MCPError) == .internalError("JSON response body longer than 16 MiB")
2854+
}
2855+
let delivered = try await log.deliveredWhenStopped()
2856+
#expect(delivered == limit + 1, "\(delivered) bytes were delivered")
2857+
await transport.disconnect()
2858+
var messages = 0
2859+
for try await _ in await transport.receive() { messages += 1 }
2860+
#expect(messages == 0)
2861+
}
2862+
2863+
@Test("A JSON response body of 16 MiB is delivered whole", .timeLimit(.minutes(1)))
2864+
func jsonBodyAtLimit() async throws {
2865+
let limit = ServerSentEventParser.maxEventLength
2866+
let (configuration, _) = LongJSONBodyURLProtocol.configuration(.init(length: limit, contentLength: limit))
2867+
let transport = HTTPClientTransport(endpoint: endpoint, configuration: configuration, streaming: false)
2868+
try await transport.connect()
2869+
try await transport.send(request)
2870+
var delivered: [Data] = []
2871+
for try await data in await transport.receive() {
2872+
delivered.append(data)
2873+
break
2874+
}
2875+
#expect(delivered == [Data(repeating: 0x20, count: limit)])
2876+
await transport.disconnect()
2877+
}
2878+
26982879
#if canImport(FoundationNetworking)
26992880
@Test("A second response for one request fails it instead of joining the bodies")
27002881
func secondResponse() async throws {

‎design/threat_model.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,10 @@ are queued; the rest, a duplicate in-flight id, and any such request at 2026-07-
8787
**Multi round-trip.** At most `maxRounds` (10) rounds and `maxInputRequests` (16) input requests per
8888
round. Cancelling the call cancels the round in progress.
8989

90-
**HTTP responses.** An SSE line longer than 16 MiB fails the stream. A server's `retry:` is clamped
91-
to 10 ms ... 60 s and reconnects back off to 60 s. A handshake POST stream is resumed at most 10
92-
times. A non-2xx reply is delivered as a JSON-RPC error only when its id matches the request; a
90+
**HTTP responses.** An SSE line longer than 16 MiB fails the stream, and an `application/json`
91+
response body longer than 16 MiB fails its request. A server's `retry:` is clamped to 10 ms ... 60 s
92+
and reconnects back off to 60 s. A handshake POST stream is resumed at most 10 times. A non-2xx
93+
reply is delivered as a JSON-RPC error only when its id matches the request; a
9394
`result` in a non-2xx reply is never delivered. `discoveryTimeout` (10 s) bounds `server/discover`.
9495
Other requests have no default timeout; cancel the awaiting task.
9596

‎docs/migration.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -761,9 +761,9 @@ session ended.
761761
Apple platforms. The previous release read each response only once the
762762
server ended it, dropped SSE bodies and opened no GET stream, so streamed
763763
results, server-to-client requests and notifications did not arrive.
764-
- An SSE line, or the data of one event, longer than 16 MiB fails the request
765-
with `internalError`. An event that the body ends before its closing blank
766-
line is discarded.
764+
- An SSE line, the data of one event, or an `application/json` response body
765+
longer than 16 MiB fails the request with `internalError`. An event that the
766+
body ends before its closing blank line is discarded.
767767
- A 404 to the GET stream of a session stops the stream, which is not
768768
reopened; the previous release kept reopening it with the expired session
769769
ID. The session ID is kept, so the next request carries it, receives the

‎docs/src/migration.src.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -647,9 +647,9 @@ session ended.
647647
Apple platforms. The previous release read each response only once the
648648
server ended it, dropped SSE bodies and opened no GET stream, so streamed
649649
results, server-to-client requests and notifications did not arrive.
650-
- An SSE line, or the data of one event, longer than 16 MiB fails the request
651-
with `internalError`. An event that the body ends before its closing blank
652-
line is discarded.
650+
- An SSE line, the data of one event, or an `application/json` response body
651+
longer than 16 MiB fails the request with `internalError`. An event that the
652+
body ends before its closing blank line is discarded.
653653
- A 404 to the GET stream of a session stops the stream, which is not
654654
reopened; the previous release kept reopening it with the expired session
655655
ID. The session ID is kept, so the next request carries it, receives the

0 commit comments

Comments
 (0)