Skip to content
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.DS_Store
/.build
/fuzz/.build
/Packages
xcuserdata/
DerivedData/
Expand Down
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha
- A response the client cannot decode (an error `code` that is a string, no `jsonrpc`) fails the
request it names with `internalError("The server sent an invalid response")` instead of leaving
it to wait for its timeout, and the warning logs a sanitized prefix, not the whole message.
- Concurrent `StdioTransport.send(_:)` calls write their messages one at a time, in the order
they were called. A send that waited for room in a full pipe let another send write into the
middle of its message (#263).
- From `main` after 0.12.1: `Data.parseDataURL(_:)` reads `;base64` from the header only and
decodes any percent-escaped byte (#309, #310); `client_secret_basic` percent-encodes the client
credentials (RFC 6749 §2.3.1, #300); PKCE verifier characters are uniformly distributed (#303);
Expand Down
49 changes: 47 additions & 2 deletions Sources/MCP/Base/Transports/StdioTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,14 @@ import struct Foundation.Data
private var isConnected = false
private var readTask: Task<Void, Never>?
private var disconnectTask: Task<Void, Never>?
private var activeSends = 0
/// The sends in progress, including those waiting for their turn. Tests wait on it.
private(set) var activeSends = 0
private var sendsDrained: CheckedContinuation<Void, Never>?
/// Whether a send holds the output. A send can suspend mid-frame on `EAGAIN`, so
/// the others wait in `sendWaiters`, oldest first, and are handed the output in turn.
private var isSending = false
private var sendWaiters: [(id: UInt64, continuation: CheckedContinuation<Void, Swift.Error>)] = []
private var nextSendWaiterID: UInt64 = 0
private let messageStream: AsyncThrowingStream<Data, Swift.Error>
private let messageContinuation: AsyncThrowingStream<Data, Swift.Error>.Continuation
private struct DescriptorState {
Expand Down Expand Up @@ -262,8 +268,11 @@ import struct Foundation.Data
/// Batches should be encoded as a JSON array containing multiple request/notification objects
/// according to the JSON-RPC 2.0 specification.
///
/// Concurrent sends write their messages one at a time, in the order they were called.
///
/// - Parameter message: The message data to send (without a trailing newline)
/// - Throws: Error if the message cannot be sent
/// - Throws: Error if the message cannot be sent, or `CancellationError` if the task is
/// cancelled while the message waits for an earlier one
public func send(_ message: Data) async throws {
guard isConnected else {
throw MCPError.transportError(Errno(rawValue: ENOTCONN))
Expand All @@ -276,6 +285,8 @@ import struct Foundation.Data
sendsDrained = nil
}
}
try await acquireOutput()
defer { releaseOutput() }

// Add newline as delimiter
var messageWithNewline = message
Expand All @@ -302,6 +313,40 @@ import struct Foundation.Data
}
}

/// Waits until no other send holds the output, then takes it.
///
/// - Throws: `CancellationError` if the task is cancelled while it waits.
private func acquireOutput() async throws {
guard isSending else {
isSending = true
return
}
let id = nextSendWaiterID
nextSendWaiterID += 1
try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
sendWaiters.append((id: id, continuation: continuation))
}
} onCancel: {
Task { await self.cancelSendWaiter(id) }
}
}

/// Hands the output to the oldest waiting send, or frees it.
private func releaseOutput() {
if sendWaiters.isEmpty {
isSending = false
} else {
sendWaiters.removeFirst().continuation.resume()
}
}

private func cancelSendWaiter(_ id: UInt64) {
// Not found: the send already has the output and writes its frame.
guard let index = sendWaiters.firstIndex(where: { $0.id == id }) else { return }
sendWaiters.remove(at: index).continuation.resume(throwing: CancellationError())
}

/// Receives messages from the transport.
///
/// Messages may be individual JSON-RPC requests, notifications, responses,
Expand Down
139 changes: 139 additions & 0 deletions Tests/MCPTests/StdioTransportTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,145 @@ struct StdioTransportTests {
#expect(fcntl(output.rawValue, F_GETFL) & O_NONBLOCK == 0)
}

/// A frame larger than a pipe's buffer (64 KiB on Linux and macOS), padded with the
/// `index`th letter.
private static func largeFrame(_ index: Int) -> Data {
let letter = Character(UnicodeScalar(UInt8(ascii: "a") + UInt8(index)))
let padding = String(repeating: letter, count: 512 * 1024)
return Data(#"{"index":\#(index),"padding":"\#(padding)"}"#.utf8)
}

private struct Frame: Decodable {
let index: Int
let padding: String
}

/// Reads `reader` until it has `count` bytes or reaches end of file, off the cooperative pool.
private static func read(_ reader: FileDescriptor, upTo count: Int = .max) async throws -> Data {
try await offThreadPool {
var received = Data()
var buffer = [UInt8](repeating: 0, count: 64 * 1024)
while received.count < count {
let read = try buffer.withUnsafeMutableBufferPointer { pointer in
try reader.read(into: UnsafeMutableRawBufferPointer(pointer))
}
if read == 0 { break }
received.append(contentsOf: buffer[..<read])
}
return received
}
}

@Test("Concurrent backpressured sends write whole frames in call order")
func testConcurrentSendsDoNotInterleave() async throws {
let (input, writer) = try FileDescriptor.pipe()
let (reader, output) = try FileDescriptor.pipe()
defer {
try? input.close()
try? writer.close()
try? reader.close()
}
let transport = StdioTransport(input: input, output: output, logger: nil)
try await transport.connect()

// Nothing reads yet, so the first send fills the pipe and suspends mid-frame, and
// each later one starts while it is.
let frames = (0..<3).map(Self.largeFrame)
var sends: [Task<Void, Swift.Error>] = []
for frame in frames {
sends.append(Task { try await transport.send(frame) })
let count = sends.count
#expect(await eventually { await transport.activeSends == count })
}

let received = Task { try await Self.read(reader) }
let sent = await outcome(within: .seconds(30)) { [sends] in
for send in sends { try await send.value }
}
#expect(!sent.didTimeOut)
#expect(sent.error == nil)
await transport.disconnect()
// The reader returns at end of file.
try output.close()

let lines = try await received.value.split(
separator: UInt8(ascii: "\n"), omittingEmptySubsequences: false)
#expect(lines.count == frames.count + 1)
#expect(lines.last?.isEmpty == true)
for (index, frame) in frames.enumerated() where index < lines.count {
#expect(lines[index] == frame, "Frame \(index) arrived torn or out of order")
let decoded = try? JSONDecoder().decode(Frame.self, from: Data(lines[index]))
#expect(decoded?.index == index)
}
}

@Test("A send cancelled while it waits for its turn throws, and later sends still go out")
func testCancelledWaitingSend() async throws {
let (input, writer) = try FileDescriptor.pipe()
let (reader, output) = try FileDescriptor.pipe()
defer {
try? input.close()
try? writer.close()
try? reader.close()
try? output.close()
}
let transport = StdioTransport(input: input, output: output, logger: nil)
try await transport.connect()

let first = Task { try await transport.send(Self.largeFrame(0)) }
#expect(await eventually { await transport.activeSends == 1 })
let cancelled = Task { try await transport.send(Self.largeFrame(1)) }
#expect(await eventually { await transport.activeSends == 2 })
// The first send still holds the output, so this one is released by cancellation.
cancelled.cancel()
let result = await outcome(within: .seconds(30)) { try await cancelled.value }
#expect(result.error is CancellationError)

let last = Data(#"{"index":2}"#.utf8)
let third = Task { try await transport.send(last) }
let expected = Self.largeFrame(0) + Data("\n".utf8) + last + Data("\n".utf8)
let received = try await Self.read(reader, upTo: expected.count)
try await first.value
try await third.value
#expect(received == expected)
await transport.disconnect()
}

@Test("Disconnect releases sends waiting for their turn")
func testDisconnectReleasesWaitingSends() async throws {
let (input, writer) = try FileDescriptor.pipe()
let (reader, output) = try FileDescriptor.pipe()
defer {
try? input.close()
try? writer.close()
try? reader.close()
try? output.close()
}
let transport = StdioTransport(input: input, output: output, logger: nil)
try await transport.connect()

var sends: [Task<Void, Swift.Error>] = []
for index in 0..<3 {
sends.append(Task { try await transport.send(Self.largeFrame(index)) })
let count = sends.count
#expect(await eventually { await transport.activeSends == count })
}

let disconnected = await outcome(within: .seconds(30)) { await transport.disconnect() }
#expect(!disconnected.didTimeOut)
// Nothing reads, so no frame finishes: the first send stops mid-frame and the
// others never start writing.
for (index, send) in sends.enumerated() {
let result = await outcome(within: .seconds(30)) { try await send.value }
guard case .transportError(let underlying) = result.mcpError else {
Issue.record("Expected send \(index) to fail with a transport error, got \(result)")
continue
}
#expect(underlying as? Errno == Errno(rawValue: ENOTCONN), "Send \(index)")
}
#expect(await transport.activeSends == 0)
}

@Test("Disconnect preserves an already nonblocking descriptor")
func testDisconnectPreservesNonblockingMode() async throws {
let (input, writer) = try FileDescriptor.pipe()
Expand Down
Loading