Repository navigation
Conversation
…modelcontextprotocol#306) * ci: use the Xcode toolchain on macOS runners macos-latest now runs macOS 26 with Xcode 26.6, whose macOS SDK is built with Swift 6.3. The standalone Swift 6.1 toolchain installed by swift-actions/setup-swift cannot build against it, so every macOS job (Test, MCP Conformance Tests, Documentation) fails while loading the SDK: error: failed to build module 'Darwin'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.3.2 ...', while this compiler is 'Apple Swift version 6.1 (swift-6.1-RELEASE)'). Use the toolchain bundled with the runner's Xcode on macOS. Swift 6.1 remains covered by the Linux test job. * ci: add a pinned macOS 15 / Xcode 16.3 (Swift 6.1) test leg The macOS test job now runs twice: on macos-15 with Xcode 16.3, which ships Swift 6.1 to match the Linux job, and on macos-latest with its default Xcode to catch breakage from new Xcode and SDK releases. Documentation and conformance stay on macos-latest. --------- Co-authored-by: Varun <varunks@apple.com>
…erver (modelcontextprotocol#299) [weak self] inside actor method closures is incorrect — actors are reference types whose lifetime is tied to their task tree, so the guard-let nil check is never true in practice and misleads readers into thinking deallocation is a normal case. Removed from: - Client.connect: CancelledNotification handler - Server.registerDefaultHandlers: Initialize method handler - Server.registerCancellationHandler: CancelledNotification handler Server was allocating a fresh JSONEncoder (+ outputFormatting setup) on every outbound send call (response, notification, request, batch). Added cached encoder/decoder stored properties matching Client's existing pattern, eliminating the per-call allocations across all four send paths and the message-handling loop's inline JSONDecoder. Co-authored-by: Alex Bullitt <abullitt@apple.com>
…elcontextprotocol#300) * fix: percent-encode client credentials in client_secret_basic RFC 6749 section 2.3.1 requires encoding the client_id and client_secret with application/x-www-form-urlencoded before forming the Basic auth header. Credentials containing ':', '@', '%', '+', or non-ASCII characters were previously included verbatim, which could produce a header that authorization servers decode to the wrong credentials. * test: cover RFC 6749 percent-encoding of client_secret_basic credentials Covers unreserved passthrough, reserved characters (: @ % + / =), a colon in the client ID not shifting the user/password boundary, and UTF-8 encoding of non-ASCII secrets. --------- Co-authored-by: Alex Bullitt <abullitt@apple.com> Co-authored-by: Varun <varunks@apple.com>
…delcontextprotocol#302) The default loopback redirect URI picks a random ephemeral port but does not bind it, so another local process could claim the port before the callback server does and receive the authorization code. Document this and recommend a fixed port or custom URL scheme for production. Co-authored-by: Alex Bullitt <abullitt@apple.com>
…ol#303) * fix: correct PKCE verifier rejection-sampling threshold makeVerifier maps random bytes onto a 66-character unreserved set using rejection sampling. The threshold `255 - (255 % 66)` evaluates to 198, so bytes 0...198 (199 values) were accepted and byte 198 wrapped to index 0, making the first character slightly more likely than the rest. The inline comment (`256 % 66 == 52`, `// 252`) was also wrong. Use `66 * (256 / 66) - 1 = 197` so exactly 3 x 66 byte values are accepted and every character is equally likely. * test: add PKCE verifier tests --------- Co-authored-by: Alex Bullitt <abullitt@apple.com>
…delcontextprotocol#304) sendAndAwait was an internal shim that bridged the sync-throwing send() and its async .value property, adding nothing beyond an extra name. All internal call sites now use try await send(request).value directly, which is the idiomatic Swift async throws pattern already documented on RequestContext. Co-authored-by: Alex Bullitt <abullitt@apple.com>
Co-authored-by: Paul Berman <pberman@cisco.com> Co-authored-by: Varun <varunkumar.saini06@gmail.com>
…ogger. (modelcontextprotocol#155) Co-authored-by: Varun <varunkumar.saini06@gmail.com>
…protocol#309) * fix: detect base64 from the data URL header, not the payload Data.parseDataURL decided base64 with string.contains(";base64,"), which also searched the payload, so "data:text/plain,hello;base64,world" was treated as base64 and returned nil even though isDataURL accepted it. The regex now captures the optional ;base64 marker and that capture drives the decision. * test: cover ;base64 after a charset parameter
…protocol#310) * fix: decode any percent-encoded byte in non-base64 data URLs Non-base64 payloads were percent-decoded through a String round trip, which rejected bytes that are not valid UTF-8 (e.g. %FF). Escapes are now decoded directly into bytes, as RFC 2397 allows any octet. * test: cover the RFC 2397 charset example and malformed escapes
…ontextprotocol#311) The test simulated ECONNRESET, slept 500 ms, and expected the connection state to be .failed. That is the state the mock sets itself, so the test did not check anything the transport did. It was also flaky: the transport cancels the connection before reconnecting, after backoffDelay(for: 1), which is also 500 ms, changing the state to .cancelled. When the cancel won the race, the test failed. The test now waits, with a timeout, for the transport to cancel the connection, then checks that it stops sending heartbeats.
…delcontextprotocol#305) * fix: unescape all quoted-pair sequences in WWW-Authenticate parameters The previous implementation only handled \" -> " in quoted parameter values. RFC 7230 section 3.2.6 defines quoted-pair as a backslash followed by any character, so \X -> X for any X. De-escape character by character so that \\, \_, and other escape sequences are handled correctly. * test: cover RFC 7230 quoted-string unescaping in WWW-Authenticate parser --------- Co-authored-by: Alex Bullitt <abullitt@apple.com>
…ontextprotocol#227) Co-authored-by: Varun <varunkumar.saini06@gmail.com>
…contextprotocol#226) JSON has a single `number` type, but Swift's JSONEncoder writes whole-number Doubles without a decimal point (`Value.double(0)` → JSON `0`) and Value's decoder tries Int first (JSON `0` → `Value.int(0)`). Result: `Value.double(0).doubleValue` returns the value, but the same value after a JSON round-trip returns nil — a footgun for any tool dispatch reading numeric tool arguments from LLMs (`[0, 0, 1]` is the natural unit-vector shape). `numberValue: Double?` returns the underlying scalar promoted to Double for both .int and .double, nil for everything else. Additive to existing `intValue` / `doubleValue` accessors; no API change, no breaking change. Closes modelcontextprotocol#225. Co-authored-by: Varun <varunkumar.saini06@gmail.com>
Co-authored-by: Varun <varunkumar.saini06@gmail.com>
… disabled (modelcontextprotocol#283) * Fix socket leak (CLOSE_WAIT) in NetworkTransport when reconnection is disabled When reconnectionConfig.enabled is false and the receive loop's connection terminates for any reason -- including the peer closing gracefully -- the loop finishes the message stream without calling connection.cancel(). NWConnection.state never transitions to .cancelled or .failed on its own after a peer-initiated FIN, so nothing else cleans up the connection either. The socket is left stuck in CLOSE_WAIT until the process exits. The reconnecting branches already call connection.cancel() before retrying; this adds the same call to the two non-reconnecting "give up" branches so the underlying socket is always released. Verified against a server using reconnectionConfig: .disabled for per-client connections (mattt/iMCP): before this fix, a burst of ~250 client connect/disconnect cycles left 247+ sockets in CLOSE_WAIT within 10 seconds; after the fix, 0. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * Cancel connection on empty-read exit and add regression test When the receive loop gives up after repeated empty reads on a connection that is no longer ready, cancel the connection and finish the message stream with MCPError.connectionClosed so the socket is released and receive() callers don't hang. Add a test that a receive failure with reconnection disabled finishes the stream with an error and cancels the connection. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Varun <varunkumar.saini06@gmail.com>
…ntextprotocol#301) * fix: eliminate data races in NetworkTransport and MockNetworkConnection NetworkTransport.attemptConnection() was writing connection.stateUpdateHandler from two contexts: the actor's executor (setting the handler) and AsyncStream's onTermination callback (clearing it to nil), which can fire on any thread. Fix: remove onTermination and use defer to clear the handler on the actor's executor after the for-await loop exits, regardless of normal return or throw. MockNetworkConnection was @unchecked Sendable with entirely unprotected mutable state. The Task { @mainactor in } wrappers were inconsistent: simulateFailure wrote mockError directly while receive read it on @mainactor, and stateUpdateHandler was set from NetworkTransport's actor executor while being read/written on @mainactor. Fix: add NSLock protecting all mutable state; snapshot handler before calling it to avoid holding the lock during the callback. * test: dequeue mock receive data under one lock, after state checks MockNetworkConnection.receive removed a queued item before checking for a cancelled or failed connection, dropping that item on those paths, and read isLast under a separate lock acquisition. Check state, dequeue, and compute isLast together under a single lock. Addresses review feedback on modelcontextprotocol#301. --------- Co-authored-by: Alex Bullitt <abullitt@apple.com>
modelcontextprotocol#318) * feat(docs): Add skill for PR review, AGENTS.md, and contributing guide Signed-off-by: Andrey Velichkevich <andrey.velichkevich@gmail.com> * Address review comments --------- Signed-off-by: Andrey Velichkevich <andrey.velichkevich@gmail.com>
Bumps the swift group with 1 update in the / directory: [github.com/apple/swift-nio](https://github.com/apple/swift-nio). Updates `github.com/apple/swift-nio` from 2.94.0 to 2.100.0 - [Release notes](https://github.com/apple/swift-nio/releases) - [Commits](apple/swift-nio@2.94.0...2.100.0) --- updated-dependencies: - dependency-name: github.com/apple/swift-nio dependency-version: 2.100.0 dependency-type: direct:production dependency-group: swift ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Varun <varunkumar.saini06@gmail.com>
Fixes README examples that don't compile against the current API, and updates facts that have drifted from the code. Examples (all Swift snippets now type-check against the library): - Tool content patterns: `.text`/`.image`/`.audio` have four associated values; drop the old `metadata` width/height logic. - Completion and prompt arguments are `[String: String]`: remove `.string(...)` / `.stringValue`. - Elicitation `requestedSchema` is not optional. - Cancellation: `callTool`/`send` need `await` from outside the actor, and the `RequestContext` overload needs a type annotation. - Batching: collect tasks in an actor instead of mutating a captured `var` in the `@Sendable` closure. - Replace deprecated `Tool.Content.text(_:)` with `.text(text:annotations:_meta:)`. - Graceful shutdown: `Duration` has no `.days`, and ServiceLifecycle's `Service` only requires `run()`. Wait on `server.waitUntilCompleted()` and stop the server from `withGracefulShutdownHandler`. - `Tool` requires `inputSchema`; give the `customer-support` prompt a real implementation. Facts: - Requirements: Swift 6.1+ (Xcode 16.3+); install from 0.12.0. - Client stdio: `StdioTransport()` uses the current process's stdio; show how to connect to a server subprocess through its pipes. - Sampling and elicitation are client capabilities: show the client declaring them, and remove `sampling:` from `Server` capabilities. - Batching was removed from the spec in 2025-06-18. - Transports table: link 2025-11-25 spec, Linux glibc and musl, SSE on Apple platforms only, stateless server limits, NetworkTransport is a custom transport with heartbeats and reconnection on by default. - Authentication: CIMD, token refresh and scope step-up; warn about the default random-port redirect URI; keep `OriginValidator` and `ProtocolVersionValidator` in custom pipelines and show where the pipeline is passed. - Platform availability: list Linux limitations. - Debugging: log to standard error (stdout carries MCP messages for stdio servers), pass the logger to the transport, and give the client and the server their own transports (follow-up to modelcontextprotocol#155). - TOC: add Custom Transport Implementation; fix heading levels.
|
Sorry @branben, your pull request is larger than the review limit of 150,000 diff characters |
|
ⓘ Qodo reviews are paused because the subscription is no longer active. Ask your workspace admin to reactivate the subscription to resume reviews. Manage billing |
| throw MCPError.transportError(Errno(rawValue: CInt(errno))) | ||
| } | ||
| return DescriptorState( | ||
| flags: flags, device: UInt64(truncatingIfNeeded: status.st_dev), inode: UInt64(truncatingIfNeeded: status.st_ino)) |
There was a problem hiding this comment.
🔴 Critical · bug · 🔍 From reading the diff, not reproduced in a run
PR targets main from feature branch, bundling 70 unrelated files (+8,178 lines)
The pull request is titled and described as a focused 3-line fix for StdioTransport (fix(StdioTransport): don't trap on socketpair stdio (st_dev == -1)). However, the PR was opened from feature/mcp-2026-07-28 against main.
Because feature/mcp-2026-07-28 includes modern protocol additions, OAuth components, HTTP server transports, and documentation changes (70 changed files, +8,178 lines), merging this PR will unintentionally merge the entire unreleased feature branch into main.
Recommendation: Either retarget this PR to the appropriate feature base branch, or cherry-pick the StdioTransport.swift fix (a85fa98) onto a dedicated fix branch branched directly from main.
| deinit { | ||
| close(readEnd) | ||
| close(writeEnd) | ||
| } | ||
| } | ||
|
|
||
| @Test("StdioTransport does not trap on socketpair (st_dev == -1)") | ||
| func testStdioTransportSocketpairNoTrap() async throws { | ||
| let pair = SocketpairPair() | ||
| defer { close(pair.readEnd); close(pair.writeEnd) } |
There was a problem hiding this comment.
🟠 Major · reliability · 🔍 From reading the diff, not reproduced in a run
Double-close of file descriptors in regression test
SocketpairPair defines a deinit that calls close(readEnd) and close(writeEnd). However, testStdioTransportSocketpairNoTrap also registers a defer block that closes pair.readEnd and pair.writeEnd.
When the test function returns, defer runs and closes both descriptors. Immediately after, pair is released and its deinit executes, closing the same file descriptor numbers a second time. In concurrent test environments, double-closing file descriptors risks closing an unrelated descriptor opened by another thread or test, leading to flaky EBADF errors or data corruption.
| /// Minimal socketpair using pipes for macOS testing | ||
| private actor SocketpairPair { | ||
| let readEnd: CInt | ||
| let writeEnd: CInt | ||
|
|
||
| init() { | ||
| let fds = try! FileDescriptor.pipe() | ||
| self.readEnd = fds.readEnd.rawValue | ||
| self.writeEnd = fds.writeEnd.rawValue | ||
| } | ||
|
|
||
| deinit { | ||
| close(readEnd) | ||
| close(writeEnd) | ||
| } | ||
| } | ||
|
|
||
| @Test("StdioTransport does not trap on socketpair (st_dev == -1)") | ||
| func testStdioTransportSocketpairNoTrap() async throws { | ||
| let pair = SocketpairPair() | ||
| defer { close(pair.readEnd); close(pair.writeEnd) } | ||
|
|
||
| let transport = StdioTransport( | ||
| input: FileDescriptor(rawValue: pair.readEnd), | ||
| output: FileDescriptor(rawValue: pair.writeEnd), | ||
| logger: nil | ||
| ) | ||
|
|
||
| try await transport.connect() | ||
| await transport.disconnect() | ||
| } |
There was a problem hiding this comment.
🟠 Major · test-gap · 🔍 From reading the diff, not reproduced in a run
Regression test uses FileDescriptor.pipe() instead of socketpair()
The test is titled testStdioTransportSocketpairNoTrap and aimed at verifying that StdioTransport does not crash when stdio is a socketpair where st_dev == -1 (issue modelcontextprotocol#327).
However, SocketpairPair allocates descriptors via FileDescriptor.pipe(), which creates standard unidirectional POSIX pipes (pipe(2)), not sockets. On Darwin/macOS, pipe descriptors report a valid filesystem device number and do not trigger st_dev == -1.
To accurately test and protect against regression for issue modelcontextprotocol#327, use POSIX socketpair(AF_UNIX, SOCK_STREAM, 0, &fds) directly. This creates a real socket pair on Darwin (where st_dev == -1), tests the actual failure scenario, and simplifies the test by removing SocketpairPair.
| /// Minimal socketpair using pipes for macOS testing | |
| private actor SocketpairPair { | |
| let readEnd: CInt | |
| let writeEnd: CInt | |
| init() { | |
| let fds = try! FileDescriptor.pipe() | |
| self.readEnd = fds.readEnd.rawValue | |
| self.writeEnd = fds.writeEnd.rawValue | |
| } | |
| deinit { | |
| close(readEnd) | |
| close(writeEnd) | |
| } | |
| } | |
| @Test("StdioTransport does not trap on socketpair (st_dev == -1)") | |
| func testStdioTransportSocketpairNoTrap() async throws { | |
| let pair = SocketpairPair() | |
| defer { close(pair.readEnd); close(pair.writeEnd) } | |
| let transport = StdioTransport( | |
| input: FileDescriptor(rawValue: pair.readEnd), | |
| output: FileDescriptor(rawValue: pair.writeEnd), | |
| logger: nil | |
| ) | |
| try await transport.connect() | |
| await transport.disconnect() | |
| } | |
| @Test("StdioTransport does not trap on socketpair (st_dev == -1)") | |
| func testStdioTransportSocketpairNoTrap() async throws { | |
| var fds: [CInt] = [0, 0] | |
| guard socketpair(AF_UNIX, SOCK_STREAM, 0, &fds) == 0 else { | |
| throw MCPError.transportError(Errno(rawValue: CInt(errno))) | |
| } | |
| defer { | |
| close(fds[0]) | |
| close(fds[1]) | |
| } | |
| let transport = StdioTransport( | |
| input: FileDescriptor(rawValue: fds[0]), | |
| output: FileDescriptor(rawValue: fds[1]), | |
| logger: nil | |
| ) | |
| try await transport.connect() | |
| await transport.disconnect() | |
| } |
Code Review: fix(StdioTransport): don't trap on socketpair stdio (st_dev == -1)The fix in However, there are three important issues:
📋 Walkthrough (9 files)
🔍 Code reviewFrom reading the diff — not reproduced in a run.
Was this review useful? React with 👍 or 👎 to help TestDriver improve. Want help from the team that built TestDriver? Explore TestDriver for Business |
adc9989 to
a85fa98
Compare
Add Discover/listen/per-request `_meta` alongside the legacy initialize era, and close parked listen SSE on cancel so refresh cannot fan-out duplicates or leak HTTP connections.
- Convert st_dev/st_ino via UInt64(truncatingIfNeeded:) to preserve bit pattern - Prevents Fatal error: Negative value is not representable on macOS - Regression test: testStdioTransportSocketpairNoTrap Bead: school-core-zjcu Co-authored-by: hermes <hermes@nousresearch.com>
a85fa98 to
619a6bb
Compare
Summary
StdioTransport.connect()traps (Fatal error: Negative value is not representable) when stdin/stdout is a socket — e.g. Node'schild_process.spawnwithstdio: ['pipe', 'pipe', 'inherit']on macOS, which reportsst_dev == -1.Outer-loop ticket: View shareable context — epic
school-core-zjcu, PRD, SPEC, decisions D1–D12.Related issue: #327 — StdioTransport socket crash (Negative value not representable)
Problem
Since modelcontextprotocol#297 (merged 2026-10-31),
StdioTransport.connect()traps when stdin/stdout is a socket. Node-based MCP clients (Claude Desktop, Claude Code) all hit this: "Connection closed" right afterinitialize.fstaton a socket reportsst_dev == -1.dev_tis signed (Int32on Darwin), soUInt64(status.st_dev)traps. Every Node-based MCP client hits this.Affected lines:
StdioTransport.swiftL147 (state creation), L159–160 (restore path comparison).Solution
Convert by bit pattern instead of value (the values are only compared for identity):
Applied to all 3 call sites (state creation in
connect(), and both comparison sites inrestoreFlags()). The same fix also applies toRestoreFlagscomparison (L159–160).Testing
Automated (
swift test --filter StdioTransport):testStdioTransportSocketpairNoTrap)Manual: Verified the socketpair reproduction path maps to a pipe pair where
st_dev == -1.Known gaps:
FileDescriptor.pipe(); a cross-platform parity check (glibc usesdev_ttoo) is recommended for downstream users, not the fix itself.Risk
Level: Low — opt-in behind feature flag; no behavior change to v1. A bit-pattern reinterpretation is mathematically equivalent for identity comparison.
Back out: Revert the three lines in
StdioTransport.swift+ remove the regression test. No config required.AI Disclosure
AI-assisted. Implementation (fix + regression test) authored by
@hermes(solar-mini4). All engineering work verified by the contributor (branben) before handoff.Review
swift test→ 650/650); CI will re-verify on pushRelated