Skip to content

Add transport for low-level network connection - #2

Merged
mattt merged 1 commit into
mainfrom
mattt/network-transport
Feb 27, 2025
Merged

mattt merged 1 commit into
mainfrom
mattt/network-transport

Conversation

@mattt

@mattt mattt commented Feb 27, 2025

Copy link
Copy Markdown
Contributor

This PR adds a NetworkTransport implementation to the MCP Swift SDK, providing network-based communication capabilities alongside the existing StdioTransport.

Features

  • Implements the Transport protocol using Apple's Network framework
  • Handles connection establishment, message sending and receiving over network connections
  • Properly manages connection state with async/await patterns
  • Includes robust error handling and logging
  • Works with any NWConnection instance, allowing flexibility in network configuration

Example Usage

import Network
import MCP

// Create a TCP connection to a server
let connection = NWConnection(
    host: "example.com", 
    port: 8080, 
    using: .tcp
)

// Create the transport with the connection
let transport = NetworkTransport(connection: connection)

// Use with MCP client
let client = Client(name: "MyApp", version: "1.0.0")
try await client.connect(transport: transport)

Model Context Protocol currently supports only stdio and SSE interfaces. However, NetworkTransport can be helpful when proxying traffic from stdio over a network interface.

@mattt
mattt merged commit 1367621 into main Feb 27, 2025
@mattt
mattt deleted the mattt/network-transport branch February 27, 2025 22:50
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant