Skip to content
Open
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
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ swift-sdk/
│ │ └── Authorization/ # OAuth 2.1 client support for `HTTPClientTransport`
│ ├── Client/ # `Client` actor; client features (sampling, elicitation, roots)
│ ├── Server/ # `Server` actor; server features (tools, resources, prompts, ...)
│ ├── Extensions/ # Extensions on Foundation types (e.g. `Data` data URL encoding)
│ ├── Extensions/ # Extensions on Foundation types (e.g. the base64 coding of binary fields)
│ └── MCP.docc/ # DocC catalog
├── Tests/MCPTests/ # Swift Testing suites
│ └── Helpers/ # MockTransport, WireExchange (`expectWire`), RawPeer, ...
Expand Down Expand Up @@ -270,7 +270,8 @@ public struct WidgetListChangedNotification: Notification {
`OAuthAuthorizer`).
- Don't block threads. Don't use `DispatchSemaphore` or busy-waiting in library code.
- New transports conform to `Transport` (`public actor`) with `public nonisolated let logger: Logger`.
They must finish their `receive()` stream on disconnect.
They follow the contract in `Transport`'s doc comment: they must finish their `receive()` stream
on disconnect. A wrapping transport adopts `TransportWrapper`.

### 5. Platform Compatibility

Expand Down
204 changes: 167 additions & 37 deletions CHANGELOG.md

Large diffs are not rendered by default.

35 changes: 27 additions & 8 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ scripts/ci-linux.sh fuzz
- `Value.swift` is the dynamic JSON value type used wherever the spec allows arbitrary JSON
(tool arguments, resource metadata, etc).
- `Transport.swift` defines the `Transport` protocol — implementations must be `Actor`s and
expose `connect()`/`disconnect()`/`send(_:)`/`receive()` (an `AsyncThrowingStream<Data, Error>`).
expose `connect()`/`disconnect()`/`send(_:options:)`/`receive()` (an `AsyncThrowingStream<Data, Error>`).
- `Transports/` holds the concrete transports: `StdioTransport`, `HTTPClientTransport`,
`HTTPServer/{Stateless,Stateful}HTTPServerTransport` (with a request validation pipeline in
`HTTPRequestValidation.swift`), `InMemoryTransport` (same-process, used heavily in tests), and
Expand All @@ -56,9 +56,25 @@ scripts/ci-linux.sh fuzz
client registration (RFC 7591), PKCE, token endpoint calls, `private_key_jwt` assertions, the
RFC 7523 jwt-bearer grant (`assertionProvider`, no DCR, no retry), RFC 8693 token exchange
(`OAuthTokenExchange`), `OAuthConfiguration.enterpriseManaged(...)` (SEP-990) and DPoP
(`OAuthConfiguration.dpop`, `OAuthDPoP.swift`, any `DPoPSigningKey`). The transport sets
`authorizationHeaders(for:method:)` after `requestModifier` and passes every response to
`didReceiveResponse(headers:for:)` (DPoP nonces).
(`OAuthConfiguration.dpop`, `OAuthDPoP.swift`, any `DPoPSigningKey`). For each POST and GET the
transport checks the endpoint itself (`https` or loopback `http`), awaits
`prepare(for:session:)` (proactive renewal; an error fails the request), runs the async
`requestModifier`, checks the final URL the same way, awaits
`authorizationHeaders(for:method:)`, then
sets `Mcp-Session-Id` from its state after those awaits. It passes every response to
`didReceiveResponse(headers:for:)` (DPoP nonces), and a 401 or 403 to
`handleChallenge(_:session:)` as an `HTTPAuthorizationChallenge`. `OAuthAuthorizer` keeps its
state in a `Mutex`, runs challenges through `gate` and storage writes through
`TokenStore.writes` (`gate` may wait for `writes`, never the reverse), and keys
`OAuthTokenStorage` by the canonical RFC 8707 resource. Redirects
(`Transports/HTTPRedirects.swift`): credentials (`Authorization`, `Proxy-Authorization`,
`Cookie`, `Mcp-Session-Id`) follow a redirect only while the chain stays on the first origin,
`DPoP` never; with an authorizer a same-origin hop's `Authorization` is the authorizer's or none.
MCP requests follow only `http`/`https` targets, never remote to loopback, never `https` to
`http`, and never loopback to non-loopback `http`. On
Apple platforms each request gets an `HTTPRedirectTaskDelegate`, which the caller cancels; on
Linux `responseBody(for:streaming:)` follows redirects itself, since corelibs drops the body and
traps on a late delegate answer.
This is opt-in — wired in via an `OAuthAuthorizer` passed to `HTTPClientTransport`.
- `Utilities/` holds cross-cutting concerns used by both Client and Server: `Cancellation`,
`Progress`, `Ping`, and `RequestContext` (the client's handle on a pending request: id and
Expand Down Expand Up @@ -115,17 +131,20 @@ Client: `Client.Configuration.protocolMode` (`.automatic` default, `.handshake`,
other MCP errors; `.stateless(v)` never retries. Tests that exercise the handshake pin
`.handshake` (`Tests/MCPTests/Helpers/HandshakeConfiguration.swift`). `send` stamps the `_meta` envelope when
`isStateless`. Request lifecycle: `register` puts a `ResponseSlot` in `pendingRequests` before
`send` returns and `transmit` sends from a task (`unsentRequests`); `withBatch` uses the same
path. Handlers run off the receive loop: notification handlers run one at a time on the
`send` returns and `transmit` sends from a task (`unsentRequests`); `withBatch(isolation:body:)`
uses the same path, and its `Batch` registers only while the body runs (`openBatches`).
Handlers run off the receive loop: notification handlers run one at a time on the
inbound queue; responses are delivered at once, except that a response waits for queued
progress notifications of its own request (`progressTokens`, `parkedResponses`; requests sent
from a notification handler never wait, via the `isHandlingNotification` task-local). The
client handles `notifications/cancelled` and the listen acknowledgement itself in the receive
loop (`handleBuiltIn`). Server-to-client requests run in `incomingRequests` tasks, at most
`maxConcurrentServerRequests` at once (64 more queued), refused at 2026-07-28 and for a
duplicate id. Cancelling the task that awaits `RequestContext.value` cancels the request. `HTTPClientTransport` takes `MCP-Protocol-Version` from the message `_meta`,
delivers JSON-RPC error bodies of non-2xx replies, and `useStatelessProtocol(_:)` drops the
session and GET stream. A handshake POST stream that ends before its response is resumed
delivers JSON-RPC error bodies of non-2xx replies, and `didNegotiate(protocolVersion:)` at
2026-07-28 drops the session and GET stream. `Client` and `Server` reach transport features only
through `Transport` hooks (`didNegotiate`, `abandonRequest`, `authorizationEnd`, `prepare`,
`isSessionless`, `httpRequest`), never by downcasting; wrappers adopt `TransportWrapper`. A handshake POST stream that ends before its response is resumed
with a GET carrying that stream's own `Last-Event-ID` (-32603 when it cannot be); at
2026-07-28 it fails at once. `HTTPClientTransport.defaultConfiguration` allows 64
connections per host: server-to-client replies need a connection while each call holds
Expand Down
28 changes: 13 additions & 15 deletions Examples/Snippets/Client/Notifications.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,18 @@ func watchNotes(_ client: Client) async throws -> Set<String> {
}
// resources/subscribe at 2025-11-25; a listen stream per URI at 2026-07-28.
try await client.subscribeToResource(uri: "file:///notes.txt")
let subscribed = await client.subscribedResourceURIs // 2026-07-28 streams only
let subscribed = await client.subscribedResourceURIs // ["file:///notes.txt"]
// ...
try await client.unsubscribeFromResource(uri: "file:///notes.txt")
// endsnippet
return subscribed
}

/// Builds the subscription requests by hand, as a proxy that forwards them does.
func subscriptionRequests(uri: String) -> (Request<ResourceSubscribe>, Request<ResourceUnsubscribe>) {
(ResourceSubscribe.request(.init(uri: uri)), ResourceUnsubscribe.request(.init(uri: uri)))
}

// MARK: - Logging

/// Receives server log messages at `info` and above.
Expand Down Expand Up @@ -133,33 +138,26 @@ actor ProgressInbox {

// MARK: - Batching

/// Sends three tool calls in one JSON-RPC batch (2025-03-26 and earlier peers).
/// Sends three tool calls in one JSON-RPC batch (peers at 2025-03-26).
func callInBatch(_ client: Client) async throws -> [CallTool.Result] {
// snippet: batch
// withBatch's closure is @Sendable, so collect the tasks in an actor.
let collected = TaskCollector<CallTool.Result>()
try await client.withBatch { batch in
let tasks = try await client.withBatch { batch in
var tasks: [Task<CallTool.Result, Error>] = []
for word in ["one", "two", "three"] {
let task = try await batch.addRequest(
CallTool.request(.init(name: "echo", arguments: ["text": .string(word)])))
await collected.append(task)
tasks.append(try await batch.addRequest(
CallTool.request(.init(name: "echo", arguments: ["text": .string(word)]))))
}
return tasks
}
// The batch is sent when the closure returns; await each result.
var results: [CallTool.Result] = []
for task in await collected.tasks {
for task in tasks {
results.append(try await task.value)
}
// endsnippet
return results
}

/// Tasks collected inside a `withBatch` closure.
actor TaskCollector<Output: Sendable> {
private(set) var tasks: [Task<Output, Error>] = []
func append(_ task: Task<Output, Error>) { tasks.append(task) }
}

// MARK: - Capabilities and extensions

/// Declares capabilities and an extension, then reads the server's.
Expand Down
8 changes: 5 additions & 3 deletions Examples/Snippets/Client/Tools.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,16 @@ func readNotes(_ client: Client) async throws -> String? {

let contents = try await client.readResource(uri: "file:///notes.txt").contents
for content in contents {
if let text = content.text {
switch content.body {
case .text(let text):
print("\(content.uri): \(text)")
} else if let blob = content.blob, let data = Data(base64Encoded: blob) {
case .blob(let data):
print("\(content.uri): \(data.count) bytes")
}
}
// endsnippet
return contents.first?.text
guard case .text(let text) = contents.first?.body else { return nil }
return text
}

/// Asks for completions of a prompt argument.
Expand Down
15 changes: 14 additions & 1 deletion Examples/Snippets/Guides/Migration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,10 +119,23 @@ func describeServer(_ client: Client, transport: any Transport) async throws ->
/// `annotations` and `_meta` default to `nil`.
let greeting: [Tool.Content] = [
.text(text: "Hello"),
.image(data: "iVBORw0KGgo=", mimeType: "image/png"),
.image(Data([0x89, 0x50, 0x4E, 0x47]), mimeType: "image/png"),
]
// endsnippet

// snippet: migration-data-url
/// Reads the bytes of a `data:` URL argument, which is now a `.string`.
func imageBytes(_ arguments: [String: Value]?) -> (mimeType: String, data: Data)? {
guard let string = arguments?["image"]?.stringValue, let url = DataURL(string) else { return nil }
return (url.mimeType, url.data)
}

/// Builds a `data:` URL from bytes.
func dataURLString(_ data: Data, mimeType: String) -> String {
DataURL(data: data, mimeType: mimeType).description
}
// endsnippet

// snippet: migration-http-errors
/// HTTP and OAuth failures are typed errors inside `transportError`.
func describeFailure(_ error: any Error) -> String {
Expand Down
61 changes: 28 additions & 33 deletions Examples/Snippets/Guides/Troubleshooting.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,51 +23,46 @@ func makeLoggedTransports() async -> (StdioTransport, InMemoryTransport, InMemor

// snippet: logging-wire
/// Wraps a transport and records every message it sends and receives.
actor WireLog: Transport {
///
/// `TransportWrapper` forwards everything else to `wrapped`, so the wrapped
/// transport keeps its behavior, such as the headers of an HTTP transport.
actor WireLog: TransportWrapper {
nonisolated let wrapped: any Transport
nonisolated let logger: Logger
private let base: any Transport
private(set) var lines: [String] = []
/// The stream `receive()` returns, made by its first call.
private var tapped: AsyncThrowingStream<Data, Swift.Error>?

init(_ base: any Transport, logger: Logger) {
self.base = base
init(_ wrapped: any Transport, logger: Logger) {
self.wrapped = wrapped
self.logger = logger
}

func connect() async throws { try await base.connect() }
func disconnect() async { await base.disconnect() }

func send(_ data: Data) async throws {
record("send", data)
try await base.send(data)
}

func send(_ data: Data, relatedRequestID: ID?) async throws {
record("send", data)
try await base.send(data, relatedRequestID: relatedRequestID)
}

/// Forwards the `Mcp-Param-*` headers of a `tools/call` at 2026-07-28.
func send(_ data: Data, additionalHeaders: [String: String]) async throws {
func send(_ data: Data, options: TransportSendOptions) async throws {
record("send", data)
try await base.send(data, additionalHeaders: additionalHeaders)
try await wrapped.send(data, options: options)
}

func receive() -> AsyncThrowingStream<Data, Swift.Error> {
let base = self.base
return AsyncThrowingStream { continuation in
let task = Task {
do {
for try await data in await base.receive() {
self.record("receive", data)
continuation.yield(data)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
/// Returns the same stream on every call, as `Transport` requires.
func receive() async -> AsyncThrowingStream<Data, Swift.Error> {
if let tapped { return tapped }
let (stream, continuation) = AsyncThrowingStream<Data, Swift.Error>.makeStream()
// Stored before the await, so a concurrent call gets the same stream.
tapped = stream
let messages = await wrapped.receive()
let task = Task {
do {
for try await data in messages {
self.record("receive", data)
continuation.yield(data)
}
continuation.finish()
} catch {
continuation.finish(throwing: error)
}
continuation.onTermination = { _ in task.cancel() }
}
continuation.onTermination = { _ in task.cancel() }
return stream
}

private func record(_ direction: String, _ data: Data) {
Expand Down
42 changes: 25 additions & 17 deletions Examples/Snippets/Protocol/Authorization.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,21 +101,21 @@ func workloadConfiguration(readToken: @escaping @Sendable () throws -> String) -
}

// snippet: auth-token-storage
/// Keeps the access token across launches. Replace the dictionary with the Keychain.
final class PersistentTokenStorage: TokenStorage, @unchecked Sendable {
private let lock = NSLock()
private var stored: Data?
/// Keeps access tokens across launches, one per server. Replace the dictionary
/// with the Keychain, under the resource's `absoluteString`.
actor PersistentTokenStorage: OAuthTokenStorage {
private var stored: [URL: Data] = [:]

func save(_ token: OAuthAccessToken) {
lock.withLock { stored = try? JSONEncoder().encode(token) }
func save(_ token: OAuthAccessToken, for resource: URL) throws {
stored[resource] = try JSONEncoder().encode(token)
}

func load() -> OAuthAccessToken? {
lock.withLock { stored.flatMap { try? JSONDecoder().decode(OAuthAccessToken.self, from: $0) } }
func load(for resource: URL) throws -> OAuthAccessToken? {
try stored[resource].map { try JSONDecoder().decode(OAuthAccessToken.self, from: $0) }
}

func clear() {
lock.withLock { stored = nil }
func clear(for resource: URL) {
stored[resource] = nil
}
}
// endsnippet
Expand All @@ -136,8 +136,15 @@ func verifyToken(_ token: String) -> (subject: String, audience: [String], expir
return ("user-1", ["https://mcp.example.com/mcp"], Date().addingTimeInterval(3600), ["tools:read"])
}

/// A validation pipeline for a protected stateful transport.
func protectedPipeline() -> StandardValidationPipeline {
/// Asks the authorization server about a token (RFC 7662 introspection). A stub that
/// suspends like the network call it stands for.
func introspectToken(_ token: String) async -> (subject: String, audience: [String], expiresAt: Date, scopes: Set<String>)? {
await Task.yield()
return verifyToken(token)
}

/// The validators of a protected stateful transport.
func protectedValidators() -> [any HTTPRequestValidator] {
// snippet: auth-server-pipeline
let resource = URL(string: "https://mcp.example.com/mcp")!
let metadataURL = URL(string: "https://mcp.example.com/.well-known/oauth-protected-resource")!
Expand All @@ -152,7 +159,8 @@ func protectedPipeline() -> StandardValidationPipeline {
resourceMetadataURL: metadataURL,
resourceIdentifier: resource,
tokenValidator: { token, request, context in
guard let claims = verifyToken(token) else {
// The closure may suspend; the transport serves other requests meanwhile.
guard let claims = await introspectToken(token) else {
return .invalidToken(errorDescription: "Unknown token")
}
guard claims.scopes.contains("tools:read") else {
Expand All @@ -163,23 +171,23 @@ func protectedPipeline() -> StandardValidationPipeline {
audience: claims.audience, scopes: claims.scopes, expiresAt: claims.expiresAt))
})

let pipeline = StandardValidationPipeline(validators: [
let validators: [any HTTPRequestValidator] = [
metadata, // before the bearer check: discovery is unauthenticated
bearer,
OriginValidator(allowedHosts: ["mcp.example.com"], allowedOrigins: ["https://app.example.com"]),
AcceptHeaderValidator(mode: .sseRequired),
ContentTypeValidator(),
ProtocolVersionValidator(),
SessionValidator(),
])
]
// endsnippet
return pipeline
return validators
}

/// A protected stateful transport.
func protectedTransport() -> StatefulHTTPServerTransport {
// snippet: auth-server-transport
let transport = StatefulHTTPServerTransport(validationPipeline: protectedPipeline())
let transport = StatefulHTTPServerTransport(validators: protectedValidators())
// endsnippet
return transport
}
Expand Down
Loading
Loading