Repository navigation
Add transport for low-level network connection - #2
Merged
Merged
Conversation
devyhan
pushed a commit
to devyhan/swift-sdk
that referenced
this pull request
Apr 4, 2025
bratland
added a commit
to bratland/swift-sdk
that referenced
this pull request
Mar 28, 2026
Add a `connectGeneration` counter to prevent stale `stateUpdateHandler` closures from resuming an already-completed `CheckedContinuation`. The crash occurred when: 1. connect() modelcontextprotocol#1 succeeds — continuation A is resumed via .ready 2. Connection breaks — receiveLoop calls connection.cancel() 3. cancel() triggers the old stateUpdateHandler, which queues a Task capturing continuation A 4. receiveLoop calls connect() modelcontextprotocol#2, resetting `connectionContinuationResumed` to false and creating continuation B 5. The queued Task from step 3 checks the flag (now false), passes the guard, and tries to resume continuation A — which was already resumed in step 1 → SIGTRAP (CheckedContinuation double-resume assertion) The fix increments a generation counter on each connect() call. Each stateUpdateHandler closure captures its generation, and handler methods verify the generation matches before touching the continuation. Also fixes Swift 6 strict concurrency warnings in ClientTests (mutable local variables captured in Sendable closures). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
jeanmatthieu
added a commit
that referenced
this pull request
Nov 30, 2026
On Linux, the test process crashed in CI and in local runs with FoundationNetworking/TaskRegistry.swift:118: Fatal error: Trying to access a behaviour for a task that in not in the registry URLSession.behaviour(for:) _ProtocolClient.urlProtocol(task:didFailWithError:) closure #1 in closure #2 in closure #1 in URLSessionTask.cancel() with no mock protocol on the stack: the failure path of a task the SDK cancelled ran after the session had removed the task. StreamingSession, which streams HTTPClientTransport's responses and ServerCard.fetch's on swift-corelibs-foundation, took the configuration as given, and URLSessionConfiguration.ephemeral has an in-memory URLCache. With a cache, corelibs (release/6.1) first looks each request up in it, and a task cancelled during that lookup can be failed after it has left its session's registry. The session now copies the configuration and sets urlCache to nil. MCP requests are never answered from a cache, and a server card is revalidated with its ETag through fetch(from:ifNoneMatch:session:); on Linux ServerCard.fetch therefore no longer reads the session's cache. Apple platforms do not use this session. With offThreadPool fixed, 60 full runs on two CPUs crashed this way 11 times without the change, and not once in 60 with it; with every change of this branch, 60 more full runs passed. The interleaving cannot be forced from a test, so the regression test checks that the session has no cache and that the caller's configuration keeps its own; it fails without the change. Assisted-by: Claude
jeanmatthieu
added a commit
that referenced
this pull request
Nov 30, 2026
…reaming
Both crash the process on swift-corelibs-foundation (release/6.1) when
a task is cancelled as it finishes or while it starts.
OAuthAuthorizationCodeFlow, without an OAuthAuthorizationDelegate,
crashed with
SWIFT TASK CONTINUATION MISUSE: data(for:delegate:) tried to resume
its continuation more than once, throwing ... Code=-999 "cancelled"
... https://localhost:8080/oauth/authorize?response_type=code...
perform sends the authorization request on its own no-redirect session
and ended with `defer { noRedirectSession.invalidateAndCancel() }`. A
task's success path calls the completion handler, which resumes the
data(for:) continuation, and only then sets the task to .completed
(_ProtocolClient.urlProtocolDidFinishLoading). The resumed caller can
run the defer in between: cancel() still sees .running, and its failure
path completes the task a second time. The request has always ended
when the defer runs, so the session is now invalidated with
finishTasksAndInvalidate(), as the guarded session of
URLSession.oauthData(for:redirects:validator:) already is. Cancelling
the caller still cancels the request through data(for:)'s own
cancellation handler. A stress run (40,000 authorizations, 12 busy
threads on 8 CPUs, Swift 6.1 on Ubuntu 24.04) crashed in 2 of 2 runs
before the change and in none of 6 after it; with fewer busy threads it
did not crash in 28 runs, so no test in the suite can show it reliably.
HTTPClientTransport crashed with
FoundationNetworking/TaskRegistry.swift:118: Fatal error: Trying to
access a behaviour for a task that in not in the registry
URLSession.behaviour(for:)
_ProtocolClient.urlProtocol(task:didFailWithError:)
closure #1 in closure #2 in closure #1 in URLSessionTask.cancel()
StreamingSession, which streams HTTPClientTransport's responses and
ServerCard.fetch's on Linux, took the configuration as given, and
URLSessionConfiguration.ephemeral has an in-memory URLCache. With a
cache, corelibs first looks each request up in it, and a task cancelled
during that lookup can be failed after it has left its session's
registry. The session now copies the configuration and sets urlCache to
nil. MCP requests are never answered from a cache, and a server card is
revalidated with its ETag through fetch(from:ifNoneMatch:session:); on
Linux ServerCard.fetch therefore no longer reads the session's cache.
Apple platforms do not use this session. In 60 full test runs on two
CPUs, with the test fixes of the previous commit, the crash happened 11
times without the change and never in 60 runs with it. The interleaving
cannot be forced from a test, so the regression test checks that the
session has no cache and that the caller's configuration keeps its own;
it fails without the change.
Assisted-by: Claude
jeanmatthieu
added a commit
that referenced
this pull request
Nov 30, 2026
…reaming
Both crash the process on swift-corelibs-foundation (release/6.1) when
a task is cancelled as it finishes or while it starts.
OAuthAuthorizationCodeFlow, without an OAuthAuthorizationDelegate,
crashed with
SWIFT TASK CONTINUATION MISUSE: data(for:delegate:) tried to resume
its continuation more than once, throwing ... Code=-999 "cancelled"
... https://localhost:8080/oauth/authorize?response_type=code...
perform sends the authorization request on its own no-redirect session
and ended with `defer { noRedirectSession.invalidateAndCancel() }`. A
task's success path calls the completion handler, which resumes the
data(for:) continuation, and only then sets the task to .completed
(_ProtocolClient.urlProtocolDidFinishLoading). The resumed caller can
run the defer in between: cancel() still sees .running, and its failure
path completes the task a second time. The request has always ended
when the defer runs, so the session is now invalidated with
finishTasksAndInvalidate(), as the guarded session of
URLSession.oauthData(for:redirects:validator:) already is. Cancelling
the caller still cancels the request through data(for:)'s own
cancellation handler. A stress run (40,000 authorizations, 12 busy
threads on 8 CPUs, Swift 6.1 on Ubuntu 24.04) crashed in 2 of 2 runs
before the change and in none of 6 after it; with fewer busy threads it
did not crash in 28 runs, so no test in the suite can show it reliably.
HTTPClientTransport crashed with
FoundationNetworking/TaskRegistry.swift:118: Fatal error: Trying to
access a behaviour for a task that in not in the registry
URLSession.behaviour(for:)
_ProtocolClient.urlProtocol(task:didFailWithError:)
closure #1 in closure #2 in closure #1 in URLSessionTask.cancel()
StreamingSession, which streams HTTPClientTransport's responses and
ServerCard.fetch's on Linux, took the configuration as given, and
URLSessionConfiguration.ephemeral has an in-memory URLCache. With a
cache, corelibs first looks each request up in it, and a task cancelled
during that lookup can be failed after it has left its session's
registry. The session now copies the configuration and sets urlCache to
nil. MCP requests are never answered from a cache, and a server card is
revalidated with its ETag through fetch(from:ifNoneMatch:session:); on
Linux ServerCard.fetch therefore no longer reads the session's cache.
Apple platforms do not use this session. In 60 full test runs on two
CPUs, with the test fixes of the previous commit, the crash happened 11
times without the change and never in 60 runs with it. The interleaving
cannot be forced from a test, so the regression test checks that the
session has no cache and that the caller's configuration keeps its own;
it fails without the change.
Assisted-by: Claude
jeanmatthieu
added a commit
that referenced
this pull request
Dec 1, 2026
…reaming
Both crash the process on swift-corelibs-foundation (release/6.1) when
a task is cancelled as it finishes or while it starts.
OAuthAuthorizationCodeFlow, without an OAuthAuthorizationDelegate,
crashed with
SWIFT TASK CONTINUATION MISUSE: data(for:delegate:) tried to resume
its continuation more than once, throwing ... Code=-999 "cancelled"
... https://localhost:8080/oauth/authorize?response_type=code...
perform sends the authorization request on its own no-redirect session
and ended with `defer { noRedirectSession.invalidateAndCancel() }`. A
task's success path calls the completion handler, which resumes the
data(for:) continuation, and only then sets the task to .completed
(_ProtocolClient.urlProtocolDidFinishLoading). The resumed caller can
run the defer in between: cancel() still sees .running, and its failure
path completes the task a second time. The request has always ended
when the defer runs, so the session is now invalidated with
finishTasksAndInvalidate(), as the guarded session of
URLSession.oauthData(for:redirects:validator:) already is. Cancelling
the caller still cancels the request through data(for:)'s own
cancellation handler. A stress run (40,000 authorizations, 12 busy
threads on 8 CPUs, Swift 6.1 on Ubuntu 24.04) crashed in 2 of 2 runs
before the change and in none of 6 after it; with fewer busy threads it
did not crash in 28 runs, so no test in the suite can show it reliably.
HTTPClientTransport crashed with
FoundationNetworking/TaskRegistry.swift:118: Fatal error: Trying to
access a behaviour for a task that in not in the registry
URLSession.behaviour(for:)
_ProtocolClient.urlProtocol(task:didFailWithError:)
closure #1 in closure #2 in closure #1 in URLSessionTask.cancel()
StreamingSession, which streams HTTPClientTransport's responses and
ServerCard.fetch's on Linux, took the configuration as given, and
URLSessionConfiguration.ephemeral has an in-memory URLCache. With a
cache, corelibs first looks each request up in it, and a task cancelled
during that lookup can be failed after it has left its session's
registry. The session now copies the configuration and sets urlCache to
nil. MCP requests are never answered from a cache, and a server card is
revalidated with its ETag through fetch(from:ifNoneMatch:session:); on
Linux ServerCard.fetch therefore no longer reads the session's cache.
Apple platforms do not use this session. In 60 full test runs on two
CPUs, with the test fixes of the previous commit, the crash happened 11
times without the change and never in 60 runs with it.
The short-lived OAuth sessions that
URLSession.oauthData(for:redirects:validator:) and
OAuthAuthorizationCodeFlow.perform make on Linux also took the caller's
configuration, cache included, and data(for:) cancels their task when
the calling task is cancelled, so they were open to the same trap. They
now use the same copy without urlCache
(URLSessionConfiguration.withoutURLCache()); OAuth responses are not
meant to be served from a cache anyway.
The interleaving cannot be forced from a test, so the regression tests
check that each of these sessions has no cache: the streaming session
directly, and the OAuth sessions through a URLProtocol that reads the
session of its task. They fail without the change, and the streaming
test also checks that the caller's configuration keeps its own cache.
Assisted-by: Claude
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR adds a
NetworkTransportimplementation to the MCP Swift SDK, providing network-based communication capabilities alongside the existingStdioTransport.Features
Transportprotocol using Apple's Network frameworkNWConnectioninstance, allowing flexibility in network configurationExample Usage
Model Context Protocol currently supports only stdio and SSE interfaces. However,
NetworkTransportcan be helpful when proxying traffic from stdio over a network interface.