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
50 changes: 41 additions & 9 deletions Sources/MCP/Base/Transports/ResponseBody.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,25 @@ struct ResponseBody: AsyncSequence, Sendable {
var index = 0

mutating func next() async throws -> UInt8? {
// `fill()` only once the chunk is used up, so reading a byte
// costs one comparison.
if index >= chunk.endIndex {
guard try await fill() else { return nil }
}
defer { index += 1 }
return chunk[index]
}

/// The bytes of the current chunk not read yet, or of the next one.
mutating func nextChunk() async throws -> Data? {
guard try await fill() else { return nil }
defer { index = chunk.endIndex }
return chunk[index...]
}
Comment on lines +54 to +58

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.

Nit: Clearing chunk in defer releases the consumed chunk's backing storage immediately instead of retaining it across the next fill() suspension:

mutating func nextChunk() async throws -> Data? {
    guard try await fill() else { return nil }
    defer {
        chunk = Data()
        index = 0
    }
    return chunk[index...]
}


/// Makes `chunk` hold a byte not read yet. Returns `false` at the
/// end of the body.
private mutating func fill() async throws -> Bool {
while index >= chunk.endIndex {
let next: Data?
do {
Expand All @@ -55,13 +74,12 @@ struct ResponseBody: AsyncSequence, Sendable {
// A cut body must not pass for a whole one; this
// throws where `URLSession.AsyncBytes` would.
if cancellation.isCancelled { throw CancellationError() }
return nil
return false
}
chunk = next
index = chunk.startIndex
}
defer { index += 1 }
return chunk[index]
return true
}
}

Expand All @@ -84,12 +102,26 @@ struct ResponseBody: AsyncSequence, Sendable {

/// The whole body, up to `limit` bytes.
func collect(limit: Int = .max) async throws -> Data {
var body = Data()
for try await byte in self {
body.append(byte)
if body.count >= limit { break }
}
return body
// Appending a byte at a time to `Data` costs about 9 ns a byte, so a
// 16 MiB body took about 150 ms.
#if canImport(FoundationNetworking)
// A chunk at a time.
var body = Data()
var iterator = makeAsyncIterator()
while body.count < limit, let chunk = try await iterator.nextChunk() {
body.append(chunk.prefix(limit - body.count))
}
return body
#else
// `URLSession.AsyncBytes` has no chunks to hand out, so into
// `[UInt8]` first.
var bytes: [UInt8] = []
var iterator = makeAsyncIterator()
while bytes.count < limit, let byte = try await iterator.next() {
bytes.append(byte)
}
return Data(bytes)
#endif
}
}

Expand Down
150 changes: 150 additions & 0 deletions Tests/MCPTests/ResponseBodyTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import Foundation
import Testing

@testable import MCP

#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

@Suite("Response body")
struct ResponseBodyTests {
/// Serves a 200 body in the chunks its script lists, then ends it or
/// fails it.
private final class ChunkScriptURLProtocol: URLProtocol {
struct Script: Sendable {
var chunks: [Int]
var failAtEnd = false
}

private static let lock = NSLock()
/// `nonisolated(unsafe)`: `lock` guards it.
nonisolated(unsafe) private static var scripts: [String: Script] = [:]

static func url(_ script: Script) -> URL {
let key = UUID().uuidString
lock.withLock { scripts[key] = script }
Comment on lines +20 to +26

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.

Nit: Synchronization.Mutex<[String: Script]>([:]) avoids NSLock + nonisolated(unsafe) (matching ResponseBody.swift), and removeValue(forKey:) in startLoading() avoids retaining scripts for the lifetime of the test process.

return URL(string: "http://localhost/\(key)")!
}

/// The bytes of the body from `offset`: a pattern, so a byte read
/// twice or out of order shows.
static func bytes(_ offset: Int, _ count: Int) -> Data {
Data((offset..<(offset + count)).map { UInt8(truncatingIfNeeded: $0 % 251) })
}
Comment on lines +32 to +34

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.

Nit: collectLimits() calls bytes(_:_:) with 1 << 20 on 12 sub-cases (both in startLoading() and when building expected), which maps ~22M bytes in debug swift test runs. Precomputing a single static pattern buffer of (1 << 20) + 4 bytes and slicing it makes this much faster on slower CI runners.


override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
let url = request.url!
let script = Self.lock.withLock { Self.scripts[url.lastPathComponent] }!
let response = HTTPURLResponse(
url: url, statusCode: 200, httpVersion: "HTTP/1.1",
headerFields: ["Content-Type": "application/json"])!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
var offset = 0
for count in script.chunks {
client?.urlProtocol(self, didLoad: Self.bytes(offset, count))
offset += count
}
if script.failAtEnd {
client?.urlProtocol(self, didFailWithError: URLError(.networkConnectionLost))
} else {
client?.urlProtocolDidFinishLoading(self)
}
}
override func stopLoading() {}
}

private func withScriptedBody<T>(
_ script: ChunkScriptURLProtocol.Script, _ body: (ResponseBody) async throws -> T
) async throws -> T {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [ChunkScriptURLProtocol.self]
let session = URLSession(configuration: configuration)
let streaming = StreamingSession(configuration: configuration)
defer { streaming.invalidate(along: session) }
let (responseBody, _) = try await session.responseBody(
for: URLRequest(url: ChunkScriptURLProtocol.url(script)), streaming: streaming)
return try await body(responseBody)
}

@Test("collect(limit:) returns the first min(length, limit) bytes in order")
func collectLimits() async throws {
let mib = 1 << 20
let cases: [([Int], [Int])] = [
([5, 5, 5], Array(0...16) + [.max]),
([mib], [1, 10, mib - 1, mib, mib + 1, .max]),
([mib, 3], [mib - 1, mib, mib + 1, mib + 2, mib + 3, mib + 4]),
([], [0, 1, .max]),
([1, 1, 1, 1], [1, 2, 3, 4, 5]),
]
Comment on lines +74 to +81

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.

Nit: Consider adding a case with an empty chunk between non-empty ones (e.g. ([5, 0, 5], [0, 5, 6, 10, 11]) and in byteIteration) to directly cover fill()'s while index >= chunk.endIndex loop.

for (chunks, limits) in cases {
let length = chunks.reduce(0, +)
for limit in limits {
let data = try await withScriptedBody(.init(chunks: chunks)) { try await $0.collect(limit: limit) }
let expected = ChunkScriptURLProtocol.bytes(0, min(length, limit))
#expect(
data == expected,
"chunks \(chunks) limit \(limit): got \(data.count) bytes, want \(expected.count)")
}
}
}

@Test("collect(limit:) throws when the body fails before the limit")
func collectFailure() async throws {
await #expect(throws: (any Error).self) {
_ = try await withScriptedBody(.init(chunks: [5, 5], failAtEnd: true)) { try await $0.collect() }
}
await #expect(throws: (any Error).self) {
_ = try await withScriptedBody(.init(chunks: [5, 5], failAtEnd: true)) {
try await $0.collect(limit: 11)
}
}
#if canImport(FoundationNetworking)
// `URLSession.AsyncBytes` can throw the task's error before it
// hands out bytes that arrived ahead of it, so only here does a
// limit reached first return.
for limit in [7, 10] {
let data = try await withScriptedBody(.init(chunks: [5, 5], failAtEnd: true)) {
try await $0.collect(limit: limit)
}
#expect(data == ChunkScriptURLProtocol.bytes(0, limit))
}
#endif
}

@Test("Bytes read one at a time match the body")
func byteIteration() async throws {
let data = try await withScriptedBody(.init(chunks: [3, 4, 1])) { body in
var out = Data()
for try await byte in body { out.append(byte) }
return out
}
#expect(data == ChunkScriptURLProtocol.bytes(0, 8))
}

#if canImport(FoundationNetworking)
@Test("next() and nextChunk() mixed read every byte once, in order")
func mixedReads() async throws {
let reads: [Data?] = try await withScriptedBody(.init(chunks: [5, 5, 5])) { body in
var iterator = body.makeAsyncIterator()
var reads: [Data?] = []
reads.append(try await iterator.next().map { Data([$0]) })
reads.append(try await iterator.nextChunk().map { Data($0) })
reads.append(try await iterator.next().map { Data([$0]) })
reads.append(try await iterator.next().map { Data([$0]) })
reads.append(try await iterator.nextChunk().map { Data($0) })
reads.append(try await iterator.nextChunk().map { Data($0) })
reads.append(try await iterator.nextChunk().map { Data($0) })
reads.append(try await iterator.next().map { Data([$0]) })
return reads
}
let bytes = { ChunkScriptURLProtocol.bytes($0, $1) }
let expected: [Data?] = [
bytes(0, 1), bytes(1, 4), bytes(5, 1), bytes(6, 1), bytes(7, 3), bytes(10, 5), nil, nil,
]
#expect(reads == expected)
}
#endif
}
Loading