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
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ jobs:
test:
timeout-minutes: 20
strategy:
# Each leg reports its own result: a flake on one platform does not
# cancel the others.
fail-fast: false
matrix:
include:
# macOS uses the Swift toolchain bundled with Xcode: a standalone toolchain
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,17 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha
second `connect()` while one is in progress throws instead of replacing the first one's
connection, and that includes a `connect()` stopped by `disconnect()` until it has returned,
which can take the rest of its backoff. A `connect()` after that dials a fresh connection.
- On Linux, an OAuth authorization code flow without an `OAuthAuthorizationDelegate` no longer
crashes the process with `SWIFT TASK CONTINUATION MISUSE` after the authorization request.
`OAuthAuthorizationCodeFlow` cancelled its session's request once the request had returned, and
on swift-corelibs-foundation a request cancelled as it finishes completes a second time.
- On Linux, cancelling an `HTTPClientTransport` request no longer crashes the process with
`Trying to access a behaviour for a task that in not in the registry`. The session that streams
responses had the configuration's `URLCache`, and swift-corelibs-foundation could fail a task
cancelled during its cache lookup after the session had let it go; that session now has no
cache, nor do the sessions the OAuth requests run in. `ServerCard.fetch(from:session:)` on
Linux therefore no longer answers from the session's cache; `fetch(from:ifNoneMatch:session:)`
revalidates a card the caller kept.
- 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
2 changes: 1 addition & 1 deletion Examples/Tests/ProtocolSnippetTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Testing
@testable import MCP
@testable import ProtocolSnippets

@Suite("Protocol snippets", .timeLimit(.minutes(1)))
@Suite("Protocol snippets", .timeLimit(.minutes(2)))
struct ProtocolSnippetTests {
@Test func handshakeNegotiatesLatestHandshakeRevision() async throws {
let version = try await connectWithHandshake(server: await makeLifecycleServer())
Expand Down
13 changes: 11 additions & 2 deletions Sources/MCP/Base/Authorization/OAuthAuthorizationCodeFlow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -159,13 +159,22 @@ public struct OAuthAuthorizationCodeFlow: Sendable {
request.setValue(
"text/html, \(ContentType.json)", forHTTPHeaderField: HTTPHeaderName.accept)

#if canImport(FoundationNetworking)
let configuration = session.configuration.withoutURLCache()
#else
let configuration = session.configuration
#endif
let noRedirectDelegate = OAuthNoRedirectSessionDelegate()
let noRedirectSession = URLSession(
configuration: session.configuration,
configuration: configuration,
delegate: noRedirectDelegate,
delegateQueue: nil
)
defer { noRedirectSession.invalidateAndCancel() }
// Not `invalidateAndCancel()`: the request has ended when this runs,
// and on swift-corelibs-foundation cancelling a task that has just
// finished completes it again, so `data(for:)` resumes its
// continuation twice and traps.
defer { noRedirectSession.finishTasksAndInvalidate() }

let (_, response) = try await noRedirectSession.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
Expand Down
6 changes: 3 additions & 3 deletions Sources/MCP/Base/Authorization/OAuthRedirectGuard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,15 @@ extension URLSession {
/// `data(for:)` with the redirect checks of ``OAuthRedirectGuard``.
///
/// swift-corelibs-foundation has no per-task delegates: there the request
/// runs in a session with this session's configuration and the guard as
/// its delegate.
/// runs in a session with this session's configuration, without its URL
/// cache, and the guard as its delegate.
func oauthData(
for request: URLRequest, redirects policy: OAuthRedirectGuard.Policy,
validator: OAuthURLValidator
) async throws -> (Data, URLResponse) {
#if canImport(FoundationNetworking)
let guarded = URLSession(
configuration: configuration,
configuration: configuration.withoutURLCache(),
delegate: OAuthRedirectGuard(policy: policy, validator: validator),
delegateQueue: nil)
defer { guarded.finishTasksAndInvalidate() }
Expand Down
20 changes: 19 additions & 1 deletion Sources/MCP/Base/Transports/ResponseBody.swift
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,21 @@ struct ResponseBody: AsyncSequence, Sendable {
return request
}
}

extension URLSessionConfiguration {
/// A copy of the configuration with no URL cache.
///
/// With a cache, swift-corelibs-foundation looks each request up in it
/// before the request starts, and a task cancelled during that lookup
/// can be failed after it has left the session's registry, which traps
/// ("a task that in not in the registry"). The sessions the SDK makes
/// on Linux use this copy.
func withoutURLCache() -> URLSessionConfiguration {
let configuration = copy() as! URLSessionConfiguration
configuration.urlCache = nil
return configuration
}
}
#endif

extension URLSession {
Expand Down Expand Up @@ -312,7 +327,10 @@ struct StreamingSession: Sendable {
#if canImport(FoundationNetworking)
let delegate = StreamingSessionDelegate(redirects: redirects)
self.delegate = delegate
self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
// The session carries MCP requests, which are not cached, and
// server card fetches, which revalidate with their own ETag.
self.session = URLSession(
configuration: configuration.withoutURLCache(), delegate: delegate, delegateQueue: nil)
#else
self.redirects = redirects
#endif
Expand Down
20 changes: 10 additions & 10 deletions Tests/MCPTests/CancellationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ struct CancellationTests {

@Test(
"A cancellation that arrives before the handler is registered cancels it",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testCancellationBeforeHandlerRegistration() async throws {
let transport = GatedContextTransport(gating: .string("call-1"))
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
Expand Down Expand Up @@ -305,7 +305,7 @@ struct CancellationTests {

@Test(
"A cancellation for a batched request that has not started yet is kept",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testCancellationOfQueuedBatchRequest() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let gate = BatchGate()
Expand Down Expand Up @@ -362,7 +362,7 @@ struct CancellationTests {

@Test(
"A request whose id is in flight is refused with -32600, and the first is answered",
.timeLimit(.minutes(1)), arguments: [false, true])
.timeLimit(.minutes(2)), arguments: [false, true])
func testDuplicateInFlightIDIsRefused(stateless: Bool) async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let gate = BatchGate()
Expand Down Expand Up @@ -397,7 +397,7 @@ struct CancellationTests {

@Test(
"A refusal of an id in flight that cannot be sent is logged, and the next message is handled",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testFailedRefusalIsLogged() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let gate = BatchGate()
Expand Down Expand Up @@ -430,7 +430,7 @@ struct CancellationTests {

@Test(
"A request may reuse an id once its response is sent, while the server still sends it",
.timeLimit(.minutes(1)),
.timeLimit(.minutes(2)),
arguments: [
// Answered by its handler.
#"{"jsonrpc":"2.0","id":"x","method":"ping"}"#,
Expand Down Expand Up @@ -465,7 +465,7 @@ struct CancellationTests {

@Test(
"Cancelling a request after a duplicate of its id was refused cancels its handler",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testCancellationAfterRefusedDuplicate() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let started = BatchGate()
Expand Down Expand Up @@ -501,7 +501,7 @@ struct CancellationTests {

@Test(
"A batched request whose id is in flight or repeated in the batch is refused with -32600",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testDuplicateIDsInBatchAreRefused() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let gate = BatchGate()
Expand Down Expand Up @@ -534,7 +534,7 @@ struct CancellationTests {

@Test(
"A handler that returns after its request was cancelled sends no response",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testSwallowedCancellationSendsNoResponse() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let started = Flag()
Expand Down Expand Up @@ -565,7 +565,7 @@ struct CancellationTests {

@Test(
"A batched handler that returns after its request was cancelled adds no reply",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testSwallowedCancellationInBatchAddsNoReply() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let gate = BatchGate()
Expand Down Expand Up @@ -596,7 +596,7 @@ struct CancellationTests {

@Test(
"A request that reuses the id of a cancelled request still running can be cancelled",
.timeLimit(.minutes(1)))
.timeLimit(.minutes(2)))
func testReusedIDOfCancelledRequestCanBeCancelled() async throws {
let server = Server(name: "TestServer", version: "1.0", capabilities: .init(tools: .init()))
let gate = BatchGate()
Expand Down
Loading
Loading