diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..5050267cc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# GitHub collapses linguist-generated files in pull request diffs and leaves them out of the +# language statistics. Mark only output that CI proves matches its source; generated files +# whose changes are the point of a review (conformance baselines, interop/RESULTS.md) stay +# visible. + +# Woven by scripts/weave.swift from docs/src/*.src.md and README.src.md (`--check` in CI). +/docs/*.md linguist-generated=true +/README.md linguist-generated=true + +# Tests/MCPTests/Generated stays visible: no CI job reruns its generators +# (scripts/frontmatter-corpus.mjs, scripts/server-card-examples.mjs), and it holds the +# expected results the tests compare against. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8a44f6682..af8f3d37c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,19 +1,25 @@ name: CI +# Every job is a line of scripts/ci/jobs, run through scripts/ci/run-jobs.sh, so a +# job is added or changed in one place. + on: push: branches: ["main", "rel/**"] pull_request: branches: ["main", "rel/**"] +# Actions are pinned by commit; the comment names the release. permissions: contents: read - pull-requests: write jobs: test: - timeout-minutes: 10 + 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 @@ -25,96 +31,160 @@ jobs: # Current leg: catches breakage from new Xcode and SDK releases. - os: macos-latest swift-version: Xcode default - - os: ubuntu-24.04 - swift-version: 6.1.0 + - os: ubuntu-latest + container: swift:6.1-rhel-ubi9 + swift-version: "6.1 (RHEL UBI 9)" + - os: ubuntu-latest + container: swift:6.1-noble + swift-version: "6.1 (Ubuntu 24.04)" runs-on: ${{ matrix.os }} + container: ${{ matrix.container }} name: Test (${{ matrix.os }}, Swift ${{ matrix.swift-version }}) steps: - - uses: actions/checkout@v4 - - - name: Prepare Linux apt dependencies - if: matrix.os == 'ubuntu-24.04' - run: | - sudo -n apt-get update - sudo -n apt-get install -y --no-install-recommends libcurl4-openssl-dev - - - name: Setup Swift on Linux - if: matrix.os == 'ubuntu-24.04' - uses: vapor/swiftly-action@v0.2 - with: - toolchain: ${{ matrix.swift-version }} + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Select Xcode if: matrix.xcode run: sudo xcode-select -s /Applications/Xcode_${{ matrix.xcode }}.app - - - name: Show Swift version - run: swift --version - - - name: Build - run: swift build -v - - - name: Run tests - run: swift test -v - - conformance: - timeout-minutes: 10 + - name: Build, test, and run the hello example + run: scripts/ci/run-jobs.sh build-test + + # Every target built for the device SDK of a platform other than macOS, and + # the tests run on its simulator (scripts/ci/apple-platform.sh). One matrix + # entry per apple-* line of scripts/ci/jobs. + apple-platforms: + name: Apple platforms (${{ matrix.platform }}) + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - platform: iOS + job: apple-ios runs-on: macos-latest - name: MCP Conformance Tests - steps: - - uses: actions/checkout@v4 - - - name: Show Swift version - run: swift --version - - - name: Build Swift executables - run: | - swift build --product mcp-everything-client - swift build --product mcp-everything-server - - - name: Run client conformance tests - uses: modelcontextprotocol/conformance@v0.1.15 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Build for the device, test on the simulator + run: scripts/ci/run-jobs.sh ${{ matrix.job }} + - name: Upload the test results + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - mode: client - command: '.build/debug/mcp-everything-client' - suite: 'core' - expected-failures: './conformance-baseline.yml' - node-version: '22' + name: apple-${{ matrix.platform }}-xcresult + path: .build/apple/${{ matrix.platform }}/Tests.xcresult + if-no-files-found: ignore - - name: Start server for testing - run: | - .build/debug/mcp-everything-server & - echo "SERVER_PID=$!" >> $GITHUB_ENV - sleep 3 + documentation: + name: Documentation + runs-on: macos-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: DocC and weave check + run: scripts/ci/run-jobs.sh docs - - name: Run server conformance tests - uses: modelcontextprotocol/conformance@v0.1.15 + # The public API against the newest 1.x release tag (VERSIONING.md). + api-breakage: + name: API breakage + runs-on: macos-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - mode: server - url: 'http://localhost:3001/mcp' - suite: 'core' - expected-failures: './conformance-baseline.yml' - node-version: '22' + fetch-depth: 0 + - name: Compare with the newest release + run: scripts/ci/run-jobs.sh api-breakage + + # libFuzzer on the parsers and the HTTP server transports. Linux only: the + # Xcode toolchain has no libFuzzer. + fuzz: + name: Fuzz + runs-on: ubuntu-latest + container: swift:6.1-noble + timeout-minutes: 30 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Run each target for a minute + run: scripts/ci/run-jobs.sh fuzz + - name: Upload crashing inputs + if: failure() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: fuzz-artifacts + path: .build/fuzz/artifacts/ + if-no-files-found: ignore - - name: Cleanup server + # Every conformance leg and tier score, baseline-enforced, on macOS and on Linux + # (RHEL UBI 9 and Ubuntu 24.04). The baselines are shared. + conformance: + name: Conformance (${{ matrix.os }}${{ matrix.container && format(', {0}', matrix.container) || '' }}) + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + include: + - os: macos-latest + - os: ubuntu-latest + container: swift:6.1-rhel-ubi9 + - os: ubuntu-latest + container: swift:6.1-noble + runs-on: ${{ matrix.os }} + container: ${{ matrix.container }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + if: runner.os == 'macOS' + with: + node-version: "22" + - name: Run conformance + run: scripts/ci/run-jobs.sh --strict --timeout 20 'conformance-.*' 'tier-.*' + - name: Upload conformance results if: always() - run: | - if [ -n "$SERVER_PID" ]; then - kill $SERVER_PID 2>/dev/null || true - fi - - documentation: - name: Documentation - runs-on: macos-latest - timeout-minutes: 10 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: conformance-${{ matrix.os }}-${{ strategy.job-index }} + path: .build/conformance/ + if-no-files-found: ignore + + # The matrix must match interop/RESULTS.md on macOS and on Linux. On Linux, + # scripts/ci/lib.sh installs Go, uv and Node with scripts/ci/deps-linux.sh. + interop: + name: Interop (${{ matrix.os }}) + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + include: + - os: macos-latest + - os: ubuntu-latest + container: swift:6.1-rhel-ubi9 + runs-on: ${{ matrix.os }} + container: ${{ matrix.container }} steps: - - uses: actions/checkout@v4 - - name: Show Swift version - run: swift --version - - name: Build Documentation - run: swift package generate-documentation --target MCP --warnings-as-errors + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5.6.0 + if: runner.os == 'macOS' + with: + go-version: "1.25" + - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6.8.0 + if: runner.os == 'macOS' + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + if: runner.os == 'macOS' + with: + node-version: "22" + - name: Run interop + run: scripts/ci/run-jobs.sh --strict interop + - name: Upload interop report + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: interop-${{ matrix.os }} + path: | + .build/interop/report.md + .build/interop/results/ + .build/interop/logs/ + if-no-files-found: ignore static-linux-sdk-build: name: Linux Static SDK Build (${{ matrix.swift-version }} - ${{ matrix.os }}) @@ -128,11 +198,12 @@ jobs: timeout-minutes: 30 steps: - name: Check out code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install static SDK and build env: BUILD_FLAGS: "" run: | which curl || (apt -q update && apt -yq install curl) - curl -s --retry 3 https://raw.githubusercontent.com/swiftlang/github-workflows/refs/heads/main/.github/workflows/scripts/install-and-build-with-sdk.sh | \ + # Pinned commit of swiftlang/github-workflows (main on 2026-10-24). + curl -sf --retry 3 https://raw.githubusercontent.com/swiftlang/github-workflows/87329d126a6992483ba89aabefa1eaef1e5b0aad/.github/workflows/scripts/install-and-build-with-sdk.sh | \ bash -s -- --static --flags="$BUILD_FLAGS" ${{ matrix.swift-version }} diff --git a/.gitignore b/.gitignore index 2d0abd048..bd3153210 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store /.build +/fuzz/.build /Packages xcuserdata/ DerivedData/ diff --git a/AGENTS.md b/AGENTS.md index 914a63dcf..77ec2f364 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,9 @@ # AGENTS.md Guidance for AI coding agents, and the humans driving them, working on the Swift SDK for the -[Model Context Protocol](https://modelcontextprotocol.io). Read this file before changing code. +[Model Context Protocol](https://modelcontextprotocol.io/docs/2026-07-28/getting-started/intro). Read this file before changing code. +[CLAUDE.md](CLAUDE.md) has the architecture notes (protocol versions, stateless serving, the +request lifecycle, the conformance ratchet). ## Agent Behavior Policy @@ -12,12 +14,17 @@ AI agents should: and the patterns in neighboring files - Build and test locally (see [Commands](#commands)) before proposing a commit - Read the relevant MCP specification section before changing protocol behavior, and match the - spec's wire format exactly. Use the revision the work targets: - - Changes to existing behavior: [`2025-11-25`](https://modelcontextprotocol.io/specification/2025-11-25), - the latest revision the SDK implements - - Work that explicitly adopts the new spec: [`2026-07-28`](https://modelcontextprotocol.io/specification/2026-07-28) - - Don't mix the two in one change. If the task doesn't say which revision it targets, ask. + spec's wire format exactly. Use the revision the code serves: + - Handshake behavior (`initialize`, sessions, server-to-client requests): + [`2025-11-25`](https://modelcontextprotocol.io/specification/2025-11-25), the newest + handshake revision + - Stateless behavior (per-request `_meta`, `server/discover`, input-required results): + [`2026-07-28`](https://modelcontextprotocol.io/specification/2026-07-28) + + Code that serves both reads `ProtocolProfile` flags (see + [Follow the MCP Specification](#2-follow-the-mcp-specification)). A change for one revision + must not change the other unless the task says so. If the task doesn't say which revision it + targets, ask. - Call out every change to public API, and keep source compatibility for existing users Agents must NOT: @@ -25,8 +32,11 @@ Agents must NOT: - Skip, disable, or weaken tests to make CI pass - Modify CI workflows, `CODEOWNERS`, `SECURITY.md`, `LICENSE`, or release automation unless explicitly asked -- Add package dependencies without explicit approval. When approved, update **both** - `Package.swift` and `Package@swift-6.0.swift`, and commit the updated `Package.resolved` +- Add package dependencies without explicit approval. When approved, follow + [DEPENDENCY_POLICY.md](DEPENDENCY_POLICY.md), update `Package.swift` (the only manifest), and + commit the updated `Package.resolved` +- Edit generated files by hand: `docs/*.md` and `README.md` (from `docs/src/*.src.md` and + `README.src.md`), the conformance baselines, and `interop/RESULTS.md` - Commit unrelated formatting changes. `.vscode/settings.json` enables format-on-save, so check the diff for reformatted lines outside the change and revert them - Commit secrets, credentials, or changes to git config @@ -43,23 +53,28 @@ stop and tell the user it needs discussion first (see ``` swift-sdk/ ├── .agents/ # Shared agent development skills (see .agents/README.md) -├── .github/workflows/ # GitHub Actions CI -├── Package.swift # Manifest for Swift 6.1+ (library + conformance executables) -├── Package@swift-6.0.swift # Manifest for Swift 6.0 (library and tests only) -├── conformance-baseline.yml # Expected conformance failures (keep empty when possible) -├── scripts/ # Helper scripts (local conformance runs) -├── Sources/ -│ ├── MCP/ # The `MCP` library product -│ │ ├── Base/ # Core JSON-RPC types, lifecycle, versioning, errors, `Transport` -│ │ │ ├── Utilities/ # Ping, cancellation, progress, `_meta`, `RequestContext` -│ │ │ ├── Transports/ # stdio, HTTP client, HTTP server, Network.framework, in-memory -│ │ │ └── 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) -│ └── MCPConformance/ # `mcp-everything-client` / `mcp-everything-server` executables -└── Tests/MCPTests/ # Swift Testing suites - └── Helpers/MockTransport.swift # Scriptable mock transport +├── .github/workflows/ # GitHub Actions CI; the jobs call scripts/ci/run-jobs.sh +├── Package.swift # The manifest (Swift 6.1 tools): library, fixtures, examples +├── Sources/MCP/ # The `MCP` library product +│ ├── Base/ # JSON-RPC types, lifecycle, versioning, errors, `Transport`, +│ │ │ # wire types of tasks, skills, apps and server cards +│ │ ├── Utilities/ # Ping, cancellation, progress, `_meta`, `RequestHandle` +│ │ ├── Transports/ # stdio, HTTP client, HTTP server (stateful and stateless), +│ │ │ # Network.framework, in-memory +│ │ └── 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. the base64 coding of binary fields) +│ └── MCP.docc/ # DocC catalog +├── Tests/MCPTests/ # Swift Testing suites +│ └── Helpers/ # MockTransport, WireExchange (`expectWire`), RawPeer, ... +├── Examples/ # Hello client and server, HTTP server, doc snippets and SnippetTests +├── conformance/ # `mcp-everything-client` / `mcp-everything-server` and baselines +├── interop/ # Interop matrix against the Go and Python SDKs +├── fuzz/ # libFuzzer targets (a separate package; Linux only) +├── docs/ # Guides; `docs/src/*.src.md` are the sources +├── design/ # Design notes +└── scripts/ # Conformance, interop, docs and CI scripts (`scripts/ci/`) ``` The server-to-client methods (sampling, elicitation, roots) live in `Client/`, because the client @@ -69,24 +84,28 @@ implements them. The server-side methods (tools, resources, prompts, completion, ## Environment & Tooling - **Language**: Swift 6 with Swift Concurrency. The `MCP` target enables `StrictConcurrency`. -- **Toolchains**: CI builds with Swift 6.1 on Linux, Xcode 16.3 (Swift 6.1) on `macos-15`, and the - default Xcode on `macos-latest`. On macOS, use the toolchain bundled with Xcode. -- **Platforms**: macOS 13+, iOS / Mac Catalyst / tvOS 16+, watchOS 9+, visionOS 1+, and Linux - (glibc and the static musl SDK). On Linux, install `libcurl4-openssl-dev`. -- **Dependencies**: `swift-system`, `swift-log`, `eventsource` (Apple platforms only), `swift-nio` - (conformance server only), and `swift-docc-plugin`. +- **Toolchains**: Swift 6.1 or later. CI builds with Swift 6.1 on Linux (RHEL UBI 9 and Ubuntu + 24.04), Xcode 16.3 (Swift 6.1) on `macos-15`, and the default Xcode on `macos-latest`, which + also runs the tests on an iOS simulator. On macOS, use the toolchain bundled with Xcode. +- **Platforms**: macOS 15+, iOS / Mac Catalyst / tvOS 18+, watchOS 11+, visionOS 2+, and Linux + (glibc and the static musl SDK). On Linux, install `libcurl4-openssl-dev`. The minimums follow + [VERSIONING.md](VERSIONING.md#platforms); don't add `@available` checks for releases below them. +- **Dependencies**: `swift-system`, `swift-log`, `swift-crypto`, `Yams` (skill frontmatter), + `swift-nio` (the conformance server and the HTTP server example), and `swift-docc-plugin`. - **Tests**: [Swift Testing](https://developer.apple.com/documentation/testing) (`import Testing`). Do not add XCTest. - **Docs**: DocC, built in CI with `--warnings-as-errors` and published on the Swift Package Index. + Guides in `docs/` are woven from `docs/src/*.src.md` and the compiled snippets in + `Examples/Snippets/` by `scripts/weave.swift`. - **Conformance**: [`modelcontextprotocol/conformance`](https://github.com/modelcontextprotocol/conformance), - which needs Node.js and `npx`. + pinned in `scripts/conformance-harness/`, which needs Node.js 22. ## Commands ```bash -# Build and test (the CI `test` job) +# Build and test (the CI `build-test` job) swift build swift test @@ -94,20 +113,28 @@ swift test swift test --filter CompletionTests # One suite swift test --filter "CompletionTests/testPromptReferenceEncodingDecoding" # One test -# Documentation (must build with no warnings) +# Documentation (the CI `docs` job; must pass with no warnings) swift package generate-documentation --target MCP --warnings-as-errors +swift scripts/doc-coverage.swift # every public declaration has a doc comment +swift scripts/weave.swift # regenerate docs/*.md and README.md; --check in CI # Conformance tests (needs Node.js; builds both executables first) -scripts/run-conformance.sh # Client and server -scripts/run-conformance.sh --mode client # Client only -scripts/run-conformance.sh --mode server # Server only, on http://localhost:3001/mcp +scripts/run-conformance.sh --spec-version 2025-11-25 # Handshake wire +scripts/run-conformance.sh --spec-version 2026-07-28 # Stateless wire +scripts/run-conformance.sh # Default wire, extension scenarios included +scripts/run-conformance.sh --mode server # Server only, on http://localhost:3001/mcp + +# The CI jobs (scripts/ci/jobs), on macOS or in a Linux container +scripts/ci/run-jobs.sh 'conformance-.*' +scripts/ci-linux.sh build-test ``` Before you open a PR, run at least `swift build` and `swift test`. If you touched doc comments on -public symbols, also build the documentation. If you touched protocol behavior, transports, or -`Sources/MCPConformance/`, also run the conformance tests. +public symbols or guides, also run the documentation commands. If you touched protocol behavior, +transports, or `conformance/`, also run the conformance tests, and `scripts/run-interop.sh --check` +for transport changes. ## Development Workflow @@ -126,23 +153,49 @@ assistance. ### 1. Maintain Stable Public Interfaces ⚠️ CRITICAL -The SDK follows [Semantic Versioning](https://semver.org). Before 1.0, minor releases may break API, -but breakage must be deliberate and called out in the PR. +The SDK follows [Semantic Versioning](https://semver.org) as [VERSIONING.md](VERSIONING.md) +defines it: from 1.0.0, a breaking change to the public API needs a major release. The CI +`api-breakage` job compares the public API with the newest release. -- Before changing anything `public`, search for its usage in `Sources/`, `Tests/`, `README.md`, and - `Sources/MCPConformance/`. +- Before changing anything `public`, search for its usage in `Sources/`, `Tests/`, `Examples/`, + `conformance/`, `interop/`, `docs/src/`, and `README.src.md`. - Prefer additive changes. Give new initializer parameters and new properties defaults, so existing call sites still compile. -- To replace an API, keep the old one as a deprecated shim that forwards to the new one: +- **Post-1.0 minor releases**: to replace a public API, keep the old one working as a deprecated + shim (`@available(*, deprecated, renamed:/message:)`) that forwards to the new one until the next + major release: ```swift -/// Deprecated compatibility factory for older call sites that used `.text("...")`. -@available(*, deprecated, message: "Use .text(text:annotations:_meta:) instead.") -public static func text(_ text: String, metadata: Metadata? = nil) -> Self { - .text(text: text, annotations: nil, _meta: metadata) +// A 1.x minor release renames a method: the old name forwards to the new one. +/// Lists the server's tools. +@available(*, deprecated, renamed: "listTools(cursor:)") +public func tools(cursor: String? = nil) async throws -> ListTools.Result { + try await listTools(cursor: cursor) } ``` +- **Pre-1.0 and major breaking changes**: remove flawed or superseded APIs cleanly rather than + carrying callable 0.x compatibility shims through the whole next major version. For symbols that + shipped in the previous release (such as `0.12.1` moving to `1.0.0`), add an + `@available(*, unavailable, renamed:/message:)` tombstone so call sites fail with a targeted + compiler diagnostic or fix-it — use `renamed:` only when the old call maps label for label, and + `message:` otherwise. Omit the tombstone when it would collide with an internal name, create + overload ambiguity, when the removed API is a pattern (a pattern cannot have a stub), or when + the symbol only existed in prereleases/alphas (cover those in + [docs/migration.md](docs/migration.md)): + +```swift +/// Renamed to ``latestHandshake``. The newest revision the SDK implements +/// is `stateless[0]`. +@available(*, unavailable, renamed: "latestHandshake", message: "The newest revision is Version.stateless[0]") +public static var latest: String { fatalError() } +``` + + Protocol features deprecated by the MCP specification (such as SEP-2577 / SEP-2596) remain + `@available(*, deprecated)` so they keep working on revisions that include them. + +- Every public enum is frozen, extensible, or an open type, as + [VERSIONING.md](VERSIONING.md#enums-and-open-types) decides. Follow that rule for new enums. - Keep implementation details `internal`. Use `package` only when another target in this package needs the symbol. - Wire format is public API too. Changing a `CodingKeys` raw value or an encode/decode rule can @@ -150,22 +203,27 @@ public static func text(_ text: String, metadata: Metadata? = nil) -> Self { ### 2. Follow the MCP Specification -- The SDK implements protocol versions up to `2025-11-25`, listed in `Version.supported` - (`Base/Versioning.swift`). Don't add a newer version until the SDK implements it. Adding a version - also requires updating `VersioningTests`. +- `Base/Versioning.swift` lists the revisions the SDK implements: `Version.handshake` (served + through `initialize`, newest `2025-11-25`), `Version.stateless` (`2026-07-28`, served per + request), and `Version.supported`, both. Don't add a revision until the SDK implements it. + Adding one also requires updating `VersioningTests` and `ProtocolProfile`. +- Code that differs per revision reads `ProtocolProfile` flags (`Version.profile(for:)`). Don't + compare version strings. - Link each type to its spec section in its doc comment, using the revision the code implements: ```swift /// To discover available tools, clients send a `tools/list` request. -/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/server/tools/#listing-tools +/// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/server/tools#listing-tools ``` -- Use spec field names as wire keys, including `_meta`. Decode leniently: use `decodeIfPresent` with +- Use spec field names as wire keys, including `_meta` as the `CodingKeys` raw value. Decode leniently: use `decodeIfPresent` with sensible defaults for optional fields, so messages from other implementations still parse. - Gate capability-dependent behavior through the existing `validateServerCapability` / `validateClientCapability` helpers. Don't add ad-hoc checks. - Cite RFC sections in comments when implementing HTTP or OAuth behavior, for example `// RFC 6749 §2.3.1`. +- A change that implements a SEP updates its row in the "SEP coverage" table of + [ROADMAP.md](ROADMAP.md). ### 3. Defining Protocol Messages @@ -185,7 +243,7 @@ public struct ListWidgetsRequest: Codable { ```swift /// - SeeAlso: https://modelcontextprotocol.io/specification/2025-11-25/... -public enum ListWidgets: Method { +public enum ListWidgets: MCP.Method { public static let name = "widgets/list" public struct Parameters: NotRequired, Hashable, Codable, Sendable { @@ -198,43 +256,56 @@ public enum ListWidgets: Method { public struct Result: Hashable, Codable, Sendable { public let widgets: [Widget] public let nextCursor: String? - public var _meta: Metadata? + public var meta: Metadata? + + public init(widgets: [Widget], nextCursor: String? = nil, meta: Metadata? = nil) { ... } - public init(widgets: [Widget], nextCursor: String? = nil, _meta: Metadata? = nil) { ... } + private enum CodingKeys: String, CodingKey { + case widgets, nextCursor + case meta = "_meta" + } } } -public struct WidgetListChangedNotification: Notification { +public enum WidgetListChangedNotification: MCP.Notification { public static let name: String = "notifications/widgets/list_changed" } ``` +Outside `Sources/MCP`, in files that import Foundation, qualify `MCP.Method` and +`MCP.Notification` (Foundation declares `Notification`, and Apple platforms bring in +`ObjectiveC.Method`). + - Use `Empty` (the default) or `public typealias Parameters = Empty` for methods without parameters. Conform `Parameters` to `NotRequired` when clients may omit `params` entirely. -- Expose `_meta` as `public var _meta: Metadata?`, with a `_meta: Metadata? = nil` initializer - parameter. +- Expose `_meta` as `public var meta: Metadata?` with the wire key `_meta` in `CodingKeys`, and a + `meta: Metadata? = nil` initializer parameter. - Group related types in a namespace `enum` when a feature has many types (see `Sampling`, `Elicitation`). - Add a typed convenience method to `Client` or `Server` that callers use instead of building requests by hand. Requests are sent with `try await send(request).value`. -- Server handlers are registered with `withMethodHandler(_:handler:)`, which replaces any existing - handler for that method. Notification handlers registered with `onNotification(_:handler:)` are - appended. `Server.start` registers default `Initialize` and `Ping` handlers. +- Server handlers are registered with `setHandler(for:_:)`, which replaces any existing handler for + that method. Notification handlers registered with `addNotificationHandler(for:_:)` are appended + and return a `NotificationHandlerRegistration`. `Server.start` registers default handlers + (`initialize`, `ping`, `server/discover`, `subscriptions/listen`, `logging/setLevel`), and + `serveTasks(with:)` and `serveSkills(from:listsInResources:)` register those of their feature; an + application handler for the same method replaces the default. ### 4. Concurrency - `Client`, `Server`, and every `Transport` are actors. Data types are `Sendable` value types. -- Don't capture `[weak self]` in handlers that `Client` or `Server` register on themselves (for - example `withMethodHandler` or `onNotification` closures in `Server.swift`). The actor owns those - closures, so `self` is never `nil` there. Keep `[weak self]` in callbacks handed to other objects, - such as `NWConnection` handlers and continuation `onTermination` closures in `NetworkTransport`, - where it prevents retain cycles. +- Capture `self` weakly in handlers that `Client` or `Server` store on themselves (for example the + default handlers registered in `Server.swift`), and throw when it is gone. The actor owns those + closures, so a strong capture is a retain cycle that keeps every started server alive. Keep + `[weak self]` in callbacks handed to other objects too, such as `NWConnection` handlers in + `NetworkTransport`. - Avoid `@unchecked Sendable`, `nonisolated(unsafe)`, and `@preconcurrency`. Use them only where a - type is provably serialized by an actor, and document why next to the declaration (see + type is provably serialized by an actor or a lock, and document why next to the declaration (see `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 @@ -245,20 +316,26 @@ platform-specific code with `canImport` checks where possible, and follow the ex | ---------------------------------------- | ------------------------------------------------------------------ | | `Network.framework` (`NetworkTransport`) | `#if canImport(Network)` | | `URLSession` on Linux | `#if canImport(FoundationNetworking)` | -| SSE streaming (`EventSource`) | `#if !os(Linux)` (the package links it on Apple platforms only) | | POSIX I/O (`StdioTransport`) | `#if canImport(Darwin) \|\| canImport(Glibc) \|\| canImport(Musl)` | | `System` vs `SystemPackage` | `#if canImport(System)` | -| PKCE S256 hashing | `#if canImport(CryptoKit)` | +| Secure Enclave keys (DPoP) | `#if canImport(CryptoKit)`; other hashing and signing use `Crypto` | +| Starting a process (`Process`) | `#if !(os(iOS) \|\| os(tvOS) \|\| os(watchOS) \|\| os(visionOS))` | -If a change can affect Linux, call that out in the PR, because CI is the only Linux check most -contributors get. +The doc snippets that start a process also hand its pipes to `StdioTransport` as `System` +`FileDescriptor`s, so they gate on `#if canImport(System) && os(macOS)` and compile on macOS +only. + +`HTTPClientTransport` streams SSE through the same code on every platform. If a change can affect +Linux, call that out in the PR and run `scripts/ci-linux.sh build-test` if you can, because CI is +the only Linux check most contributors get. ### 6. Testing Requirements - Every new feature and every bug fix MUST come with tests. A bug fix needs a regression test that fails without the fix. - Tests live in `Tests/MCPTests/`, one file per feature area (`ToolTests.swift`, - `HTTPClientTransportTests.swift`, ...). Add to the existing file when there is one. + `HTTPClientTransportTests.swift`, ...). Add to the existing file when there is one. Snippet + tests live in `Examples/Tests/`. - Use Swift Testing: a `@Suite("Readable Name") struct`, and `@Test("Readable description")` on each test. Assert with `#expect` / `#require`, and use `Issue.record` for unreachable paths. @@ -267,8 +344,8 @@ contributors get. struct ToolTests { @Test("ListTools result round-trips with _meta") func testListToolsResultRoundTrip() throws { - let meta = Metadata(additionalFields: ["vendor.example/key": .string("value")]) - let result = ListTools.Result(tools: [], _meta: meta) + let meta = Metadata(fields: ["vendor.example/key": .string("value")]) + let result = ListTools.Result(tools: [], meta: meta) let data = try JSONEncoder().encode(result) let decoded = try JSONDecoder().decode(ListTools.Result.self, from: data) #expect(decoded == result) @@ -276,23 +353,28 @@ struct ToolTests { } ``` -- **Wire format**: assert on the encoded JSON (`JSONSerialization`), not only on a decode - round-trip, so a symmetric encode/decode bug can't pass. +- **Wire format**: assert on the encoded JSON, not only on a decode round-trip, so a symmetric + encode/decode bug can't pass. Golden wire tests use `expectWire` and `WireExchange` + (`Tests/MCPTests/Helpers/WireExchange.swift`). - **Client/server behavior**: use a real pair over `InMemoryTransport`: ```swift -let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() -let server = Server(name: "test", version: "1.0", capabilities: .init(tools: .init())) -await server.withMethodHandler(ListTools.self) { _ in .init(tools: []) } +let (clientTransport, serverTransport) = InMemoryTransport.makePair() +let server = Server(info: .init(name: "test", version: "1.0"), capabilities: .init(tools: .init())) +await server.setHandler(for: ListTools.self) { _, _ in .init(tools: []) } try await server.start(transport: serverTransport) -let client = Client(name: "test", version: "1.0") +let client = Client(info: .init(name: "test", version: "1.0")) _ = try await client.connect(transport: clientTransport) // ... exercise and assert ... await client.disconnect() await server.stop() ``` +The default client connects at 2026-07-28 when the server serves it. A test of handshake +behavior pins the client to it with `configuration: .handshake` +(`Tests/MCPTests/Helpers/HandshakeConfiguration.swift`). + Use `MockTransport` (`Tests/MCPTests/Helpers/`) when you need to script exact messages or inspect what was sent. @@ -321,11 +403,17 @@ while mockConnection.state != .cancelled && ContinuousClock.now < deadline { in `OAuthComponentTestHelpers.swift`. Mirror the existing `#if swift(>=6.1)`, `canImport(FoundationNetworking)`, and `canImport(Network)` gates. - **Conformance**: for protocol features, add or update a scenario in - `Sources/MCPConformance/Client/main.swift` (`scenarioHandlers`) or `Server/main.swift`. Don't add - entries to `conformance-baseline.yml` to hide a failure you introduced. + `conformance/everything-client/main.swift` (`scenarioHandlers`) or `conformance/everything-server/`. + A change that fixes or breaks a scenario regenerates the affected baseline + (`conformance/baseline*.yml`) with `--update-baseline` in the same change. Don't add entries to + a baseline to hide a failure you introduced. ### 7. Documentation -- Update `README.md` when you add or change user-facing API. Its examples must compile against the - current API. +- Update the guides (`docs/src/*.src.md`) and `README.src.md` when you add or change user-facing + API, then run `swift scripts/weave.swift` and commit the sources and the output together. Code + in the guides comes from the snippet targets in `Examples/Snippets/`, which `swift build` + compiles and `SnippetTests` runs. +- A breaking change updates [docs/migration.md](docs/migration.md) (through its source) and + [CHANGELOG.md](CHANGELOG.md). - Keep doc comments accurate when behavior changes. A stale comment is a bug. diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..98178e317 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,598 @@ +# Changelog + +Release notes, newest first. Each release lists breaking changes, features, fixes, dependency +changes and deprecations ([VERSIONING.md](VERSIONING.md#release-notes)). + +## 1.0.0 (unreleased) + +The first release with the 1.x stability promise ([VERSIONING.md](VERSIONING.md)). It adds the +2026-07-28 revision of MCP next to the `initialize`-based revisions (2024-11-05 through +2025-11-25), on one `Server` and one `Client`. Changes since 0.12.1 (`a0ae212`), including the +fixes merged to `main` after it (up to `234e412`), with before and after code: +[docs/migration.md](docs/migration.md). + +### Breaking changes + +- Names follow the Swift API Design Guidelines; each renamed 0.12.1 symbol carries an + `@available(*, unavailable)` tombstone with a compiler fix-it or message + ([details](docs/migration.md#renamed-api)). +- `Notification` drops `Hashable` and `Codable` (keeping `Sendable`), and the SDK's notification + types are now caseless `enum`s matching `Method`. Short names (`Method`, `Notification`, + `HTTPRequest`, `HTTPResponse`, `Tool`, `Prompt`, `Empty`) keep their names; qualify + `MCP.Method`, `MCP.Notification`, etc. where another module declares the same name + ([details](docs/migration.md#name-collisions)). +- Swift `_meta` properties (with fix-it tombstones) and `_meta:` initializer labels (without + tombstones) are renamed to `meta`; the JSON wire key remains `"_meta"` + ([details](docs/migration.md#meta)). +- Handler registration and context: `Server.setHandler(for:_:)` and `Client.setHandler(for:_:)` + replace `withMethodHandler` and pass `(Parameters, HandlerContext)`; + `Client.setElicitationHandler(_:)` replaces `withElicitationHandler`; and + `Server.currentHandlerContext` is removed (tombstoned). Inside a handler, use `context.notify`, + `context.reportProgress`, `context.log`, and `context.request*` to reach the request's stream + ([details](docs/migration.md#handler-registration-and-context)). +- Notification handlers: `addNotificationHandler(for:_:)` replaces `onNotification(_:handler:)` on + `Server` and `Client`, returning a `NotificationHandlerRegistration` whose `remove()` stops + delivery; `Client.addNotificationHandler(for:_:)` drops `async` + ([details](docs/migration.md#notification-handlers)). +- `RequestContext` is renamed to `RequestHandle` (`requestID` → `id`), adds `progress` and + `cancel(reason:)`, and makes its initializer internal (tombstoned) + ([details](docs/migration.md#requesthandle)). +- Content blocks, roles and annotations are consolidated into `ContentBlock` (`Tool.Content` and + `Prompt.Message.Content` are typealiases), `Role`, and top-level `Annotations`. + `.text(_:annotations:meta:)` and `.resource(_:annotations:meta:)` drop their first labels + (labeled patterns fail to compile), deprecated 0.12 short forms are unavailable, binary `image` + and `audio` cases take unlabeled `Data` instead of base64 `String` (old `data: String` factories + are unavailable; pattern matches bind `Data`), `.resourceLink(Resource)` replaces the + six-argument case, and `Tool.Annotations` drops `ExpressibleByNilLiteral` + ([details](docs/migration.md#content-blocks-roles-and-annotations)). +- `Client.Info` and `Server.Info` are unified into `Implementation` (`websiteUrl` → `websiteURL`). + `Client.init(info:capabilities:configuration:)` and `Server.init(info:...)` accept + `Implementation` for display metadata (`title`, `description`, `websiteURL`, `icons`, whose flat + initializer parameters are unavailable); `Client.init(name:version:...)` and + `Server.init(name:version:...)` remain available as shorthands; `name`/`title`/`version` directly + on `Client` and `Server` are unavailable; `Client`'s `info`, `capabilities`, and `configuration` + are `nonisolated let`; and `Server`'s `capabilities` and `configuration` are `private(set)` + ([details](docs/migration.md#implementation)). +- `MCPError.code` and `MCPError.serverError(code:)` are now `MCPError.Code` (`Comparable`, + integer-literal) instead of `Int` ([details](docs/migration.md#mcperrorcode)). +- `MCPError` has seven new cases since 0.12.1 (`resourceNotFound`, `headerMismatch`, + `missingRequiredClientCapabilities`, `unsupportedProtocolVersion`, and local lifecycle cases + `notConnected`, `alreadyConnected`, `requestFinished`), its case set is frozen for 1.x, and + `serverError` carries `data` ([details](docs/migration.md#mcperror-cases)). +- Optional `Bool?` capability and protocol flags (`listChanged`, `subscribe`, `isError`, `hasMore`, + `isRequired`) became non-optional `Bool` defaulting to `false` + ([details](docs/migration.md#capability-flags)). +- `HTTPResponse` is now a struct with `statusCode`, `headers`, frozen `Body` (`.empty`, `.data`, + `.stream`), `bodyData`, and static factories; and `HTTPRequest.header(_:)` is renamed to + `value(forHeader:)` ([details](docs/migration.md#http-server-types)). +- `Server.AdmissionCheck` passed to `Server.init(..., admissionCheck:)` replaces `initializeHook` + on `Server.start(transport:initializeHook:)` (unavailable); `Server.start(transport:)` takes + only `transport:` ([details](docs/migration.md#admission-check)). +- OAuth configuration and errors are reshaped: `OAuthConfiguration` uses grant-specific factories + (`.authorizationCode`, `.clientCredentials`, `.jwtBearer`, `.enterpriseManaged`) with mutable + properties; `TokenEndpointAuthentication.none(clientID:)` is replaced by + `.publicClient(clientID:)`, `.dynamicRegistration`, and `.clientIDMetadataDocument(_:)`; + `OAuthSigningKey` powers `.privateKeyJWT(clientID:privateKey:lifetime:)` alongside + `.privateKeyJWT(clientID:assertionProvider:)`; `PrivateKeyJWTSigningAlgorithm` and + `PrivateKeyJWTAssertionError` are removed; `OAuthProtectedResourceServerMetadata` is merged into + `OAuthProtectedResourceMetadata` (`authorizationServers` is now `[String]?` instead of `[URL]`); + `AccessTokenProvider` returns `OAuthAccessToken?`; + `OAuthAuthorizationDelegate.presentAuthorizationURL(_:redirectURI:)` receives `redirectURI`; + `OAuthBearerChallenge.scope` becomes `scopes: Set?`; and `OAuthAuthorizationError` is a + struct with renamed codes (`protectedResourceMetadataDiscoveryFailed`, + `clientIDMetadataDocumentNotSupported`, `insecureEndpoint`), removed `pkceS256Unavailable`, + twelve new codes, `statusCode: Int?`, and unavailable value-taking factories + ([OAuth configuration](docs/migration.md#oauth-configuration), + [OAuthAuthorizationError](docs/migration.md#oauthauthorizationerror)). +- `TimeInterval` and `Int` millisecond APIs (`sessionIDWaitTimeout`, `retryInterval`, + `backoffDelay(forAttempt:)`, `proactiveRefreshWindow`, `isExpired(at:skew:)`, `lifetime:`, etc.) + now use Swift's `Duration` ([details](docs/migration.md#durations)). +- Extension points: `RequestStateCodec.seal(_:)` and `unseal(_:)` are `async throws` + (`RequestStateProtection.unprotected`, `AESGCMRequestStateCodec.KeyError`), `SkillCatalog` + methods take `context: Server.HandlerContext`, `TaskStore` adds pagination and conditional update + methods, and `serveTasks(with:)` and `serveSkills(from:listsInResources:)` must be called before + `Server.start(transport:)` (`serveAppResources(_:listsInResources:)` stays callable at runtime) + ([details](docs/migration.md#extension-points)). +- Defaulted initializer parameters moved after required parameters on `Tool`, `GetPrompt.Result`, + `Initialize.Parameters`, `Resource.Content`, `UIResource`, `AppResourceContents`, `TaskSnapshot`, + and `TaskRecord` ([details](docs/migration.md#parameter-order)). +- Implementation helpers made internal: `OAuthURLValidator` (and `urlValidator:` parameters), + `PKCE`, `OAuthAuthorizationCodeFlow`, `OAuthTokenExpirySkew`, `OAuthWWWAuthenticateParsing`, + `DefaultOAuthWWWAuthenticateParser`, `OAuthAuthorizer.init(...challengeParser:...)`, the 14 + value-taking `OAuthAuthorizationError` factories, `InMemoryTransport.init(logger:)`, + `Server.send(_ response:)`, and `RequestHandle.init` (all 0.12.1 symbols except + `InMemoryTransport.init(logger:)` keep unavailable tombstones; `OAuthMetadataDiscovering` and + `DefaultOAuthMetadataDiscovery` remain public) + ([details](docs/migration.md#api-that-is-now-internal)). +- `Version.latest` (fix-it to `Version.latestHandshake`) and + `CreateSamplingMessage.ToolChoice.init(mode: Mode?)` (pass a `Mode`) are now unavailable + tombstones ([details](docs/migration.md#renamed-api)). +- `Client.Capabilities.experimental` is `[String: Value]?` + ([details](docs/migration.md#clientcapabilitiesexperimental)). +- Open structs instead of enums: `OAuthAuthorizationError`, `OAuthConfiguration.GrantType`, + `OAuthConfiguration.TokenEndpointAuthentication`, `OAuthAccessToken.TokenType`, + `OAuthTokenExchange.TokenType`, `BearerTokenValidator.Result`, `Elicitation.Mode`, and + `CreateSamplingMessage.ToolChoice.Mode` ([details](docs/migration.md#open-structs)). +- An `.unknown` case for kinds from a later revision on `ContentBlock`, + `Sampling.Message.Content.ContentBlock`, `InputRequest`, `InputResponse`, and + `CreateElicitation.Parameters` ([details](docs/migration.md#unknown-kinds)). +- The `Client` convenience methods (`listTools`, `listPrompts`, `listResources`, + `listResourceTemplates`, `callTool`, `getPrompt`, `readResource`, `complete`) return result + types; `startToolCall` replaces the `RequestContext` overload of `callTool`; `Client.initialize()` + is unavailable ([details](docs/migration.md#client-convenience-methods)). +- `Client.connect(transport:)` returns `Client.ConnectionInfo` + ([details](docs/migration.md#clientconnecttransport)). +- `Resource.Content` replaces its stored `text: String?` and `blob: String?` properties with + `body: Resource.Content.Body` (`.text(String)` or `.blob(Data)`); `text` and `blob` are + unavailable with compiler diagnostics pointing to `body` + ([details](docs/migration.md#resourcecontent)). +- `Value.data(mimeType:_:)` is removed: every JSON string, including `data:` URLs, decodes as + `Value.string`. Parse and format `data:` URLs explicitly with `DataURL`; `Value.dataValue`, + `Data.isDataURL(string:)`, `Data.parseDataURL(_:)` and `Data.dataURLEncoded(mimeType:)` are + unavailable with compiler diagnostics pointing to `DataURL` + ([details](docs/migration.md#valuedata-and-dataurl)). +- `Server.cancelRequest(_:reason:)` is removed (unavailable with a compiler diagnostic); cancel the + task awaiting `requestSampling`, `requestElicitation`, or `listRoots` instead + ([details](docs/migration.md#server-to-client-request-cancellation)). +- `HTTPClientTransport` throws `transportError(HTTPStatusError)` and + `transportError(OAuthAuthorizationError)` instead of `internalError` with a message + ([details](docs/migration.md#http-client-errors)). +- `HTTPClientAuthorizer` is no longer class-bound (`Sendable`, not `AnyObject`): + `authorizationHeader(for:)` is `authorizationHeaders(for:method:) async throws`; + `prepareAuthorization(for:session:)` is renamed `prepare(for:session:)` (with an empty default — + custom authorizers that still define `prepareAuthorization` compile without it being called — + and its thrown errors now fail the request rather than being ignored); + `handleChallenge(_:session:)` takes `HTTPAuthorizationChallenge` and returns + `HTTPChallengeResult`; `didReceiveResponse(headers:for:)` is `async`; + `maxAuthorizationAttempts` is renamed `maximumAuthorizationAttempts`; and + `validateEndpointSecurity(for:)` is removed from `HTTPClientAuthorizer` and `OAuthAuthorizer` + because the transport always runs the check ([details](docs/migration.md#httpclientauthorizer)). +- `TokenStorage` and `InMemoryTokenStorage` are replaced by `OAuthTokenStorage` (not class-bound, + keyed by canonical resource `URL`, with `async throws` `load(for:)`, `save(_:for:)`, and + `clear(for:)`) and `InMemoryOAuthTokenStorage` ([details](docs/migration.md#oauthtokenstorage)). +- `OAuthScopeSelecting` refines `Sendable`. +- `HTTPClientTransport`'s `requestModifier` is `@Sendable (inout URLRequest) async throws -> Void` + instead of `(URLRequest) -> URLRequest` + ([details](docs/migration.md#httpclienttransport-requestmodifier)). +- `Transport`: `logger` is `nonisolated`; `send(_:options:)` with `TransportSendOptions` replaces + `send(_:)` as the requirement; `receive()` is `async`; six defaulted protocol hooks replace + concrete transport downcasts; `HTTPContextProviding` is removed (`httpRequestContext(for:)` is + renamed `httpRequest(for:)`); `HTTPClientTransport.updateNegotiatedProtocolVersion(_:)` is + renamed `didNegotiate(protocolVersion:)` + ([details](docs/migration.md#transport-protocol)). +- `HTTPRequestValidationPipeline` and `validationPipeline:` are removed in favor of + `validators:` (defaulting to `defaultValidators`), and `HTTPRequestValidator.validate`, + `BearerTokenValidator.TokenVerifier` (renamed from `TokenValidator`), and + `StandardValidationPipeline.validate` are `async` + ([details](docs/migration.md#async-http-request-validation)). +- `NetworkTransport.Heartbeat`, `HeartbeatConfiguration`, `BufferConfiguration` and the old + five-parameter initializer are removed in favor of + `init(connection:maximumMessageLength:connectionTimeout:reconnection:logger:)`; reconnection is + off by default (`.default` → `.enabled`, `enabled` → `isEnabled`, `maxAttempts` → + `maximumAttempts`, `backoffDelay(for:)` → `backoffDelay(forAttempt:) -> Duration`) and heartbeats + are no longer sent. `MCPError.isResourceTemporarilyUnavailable(_:)` is removed + ([details](docs/migration.md#networktransport-and-mcperrorisresourcetemporarilyunavailable)). +- `Server.waitUntilCompleted()` is renamed `Server.waitUntilFinished()` and is now `async throws` + (add `try`); `Server.start` throws `MCPError.alreadyConnected` on overlapping starts and + `MCPError.connectionClosed` when `stop()` is called while connecting + ([details](docs/migration.md#serverwaituntilfinished)). +- `Client.withBatch(body:)` is now `@discardableResult withBatch(isolation:body:)`, generic over + `R: Sendable`, and `Client.Batch` is a `Sendable` struct whose `add(_:)` (replacing + `addRequest(_:)`) returns `RequestHandle` and throws `MCPError.requestFinished` after + `withBatch` returns ([details](docs/migration.md#clientwithbatchisolationbody-and-clientbatch)). +- Clients connect with `ProtocolMode.automatic`: `server/discover` at 2026-07-28, then + `initialize` for older servers. Servers serve both eras by default. +- `Version.supported` lists 2026-07-28; `Version.handshake` lists the `initialize` revisions + ([details](docs/migration.md#clients-connect-at-2026-07-28)). +- `Response.id` (and its `Identifiable.ID` type) changed from `ID` to `ID?` so JSON `"id": null` + on unattributed error responses is distinct from `""`; unwrap `response.id` where non-optional + `ID` is expected ([details](docs/migration.md#responseid)). +- Swift 6.1 tools are required. +- The minimum platforms are macOS 15, Mac Catalyst 18, iOS 18, tvOS 18, watchOS 11 and + visionOS 2 (were macOS 13, Mac Catalyst 16, iOS 16, tvOS 16, watchOS 9 and visionOS 1). For + older deployment targets, stay on 0.12 ([details](docs/migration.md#platforms)). + +What still compiles: `.text("Hello")` is the case itself again; integer comparisons, switches, +ranges, and literals against `MCPError.code` (`error.code == -32600`, `case -32600:`, +`case -32099 ... -32000:`, `.serverError(code: -32000, ...)`); reads through an optional parent +capability (`caps.tools?.listChanged`); trailing-closure `withBatch`; `try await client.send(request).value`; +and `MCP.Method`-qualified conformances. + +Behavior that can break working code ([docs/migration.md](docs/migration.md#behavior-changes)): + +- Cancelling a task awaiting `RequestHandle.value` now cancels the underlying request (0.12.1's + `Task.value` was passive); wrap in `Task { try await handle.value }.value` to wait without + cancelling ([details](docs/migration.md#requesthandle)). +- Operations on `Server.HandlerContext` throw `MCPError.requestFinished` after the handler returns + and `CancellationError` after the request is cancelled + ([details](docs/migration.md#handler-registration-and-context)). +- Explicit `false` capability and protocol flags re-encode as absent (`{}`) + ([details](docs/migration.md#capability-flags)). +- A JSON-RPC response with `"id": null` and a `result` is refused, and `""` is no longer confused + with `null` ([details](docs/migration.md#icon-themes-response-errors-and-task-equality)). +- `Server.AdmissionCheck` runs before `initialize` (including custom `Initialize` handlers), + every 2026-07-28 request, every sessionless handshake request behind + `StatelessHTTPServerTransport`, and any handshake request received before a session is + initialized ([details](docs/migration.md#admission-check)). +- `HTTPClientAuthorizer.didReceiveResponse(headers:for:)` receives the URL that answered (after + redirects), not the initial request URL ([details](docs/migration.md#httpclientauthorizer)). +- A -32042 error whose data cannot be represented by `urlElicitationRequired` now decodes as + `serverError` and keeps its data, including metadata, other keys and undecodable elicitation + items. Match `error.code == .urlElicitationRequired` to handle either case. +- An undecodable direct peer result now throws `ResultDecodingError` with the expected type, + raw result and underlying decoding error instead of an empty internal type mismatch error. + Task result methods also throw it instead of a bare decoding error or a generic missing-result + error. This local error is separate from `MCPError`. +- After an established session ends and validation passes, its transport returns 400 without a + session ID and 404 with any session ID. +- `MCPError` decoding: -32000 and -32001 decode as `serverError`, -32602 with `data.uri` as + `resourceNotFound`, and the standard cases without `data.detail` drop their own message text + ([details](docs/migration.md#mcperror-decoding)). +- A request whose parameters do not decode fails with -32602 instead of -32603. +- A `sampling/createMessage` handler sees `includeContext` capped at + `Client.Configuration.maximumContextInclusion`, which defaults to `.none`. Set + `maximumContextInclusion: .allServers` for the previous behavior + ([details](docs/migration.md#sampling-handlers-see-includecontext-capped-at-none)). +- `StatefulHTTPServerTransport` answers an unsupported `MCP-Protocol-Version` with -32022 instead + of -32600. +- Authorization server metadata whose `issuer` does not match fails discovery + (`authorizationServerIssuerMismatch`) instead of being used. +- An OAuth URL a server names (a challenge's `resource_metadata`, the listed authorization + servers, and the endpoints in authorization server or identity provider metadata, including the + one `OAuthTokenExchange.discoverTokenEndpoint(forIssuer:session:)` returns) may be on a loopback + host only when that server is, and fails with `privateIPAddressBlocked` otherwise. Set + `endpointOverrides` for a local authorization server used with a remote MCP endpoint + ([details](docs/migration.md#authorization)). +- `DefaultOAuthMetadataDiscovery.canonicalResourceURI(from:)` normalizes resource URIs per RFC + 3986 §6 (lowercase scheme and host, dot segments collapsed, trailing slash stripped, hostless + URLs such as `https:///` rejected), including `endpointOverrides.resource`; servers where a + trailing slash is significant can pass a custom `OAuthMetadataDiscovering`. Reloaded tokens + after a resource key change are checked against the listed authorization servers and DPoP + requirements, and DPoP nonce keys normalize host case and omit default ports `443`/`80` + ([details](docs/migration.md#authorization)). +- `HTTPClientTransport` sends `Authorization`, `Proxy-Authorization`, `Cookie`, and + `Mcp-Session-Id` only on same-origin redirects (also separating credentials from + `URLSessionConfiguration.httpAdditionalHeaders` so they never reach cross-origin redirects or + the authorizer's own requests), re-authorizes same-origin hops (fresh DPoP proofs; no stale + `Authorization` when empty), refuses non-HTTP(S), `https`→`http`, and remote↔loopback/unspecified + redirects, fails credential-less `401`/`403` after a cross-origin redirect with + `protectedResourceMismatch`, and does not mark a live session expired on a `404` from a + redirected hop that did not send `Mcp-Session-Id` + ([details](docs/migration.md#http-client-transport)). +- `connect()` after `disconnect()` throws `MCPError.connectionClosed` (and a second `connect()` + throws `MCPError.alreadyConnected`) on all SDK transports (`HTTPClientTransport`, + `StdioTransport`, `NetworkTransport`, `InMemoryTransport`): create a new transport to reconnect. + Sends before `connect()` throw `MCPError.notConnected`, and sends after `disconnect()` or peer + close throw `MCPError.connectionClosed`. +- `StdioTransport` read errors finish the receive stream with `MCPError.transportError` instead + of ending it like end of input, and `StdioTransport` no longer mutates `O_NONBLOCK` on its + descriptors. +- `StatefulHTTPServerTransport` rejects `Last-Event-ID` counter `0` (emitted counters start at 1). +- `HTTPClientTransport` ignores `Mcp-Session-Id` on replies to 2026-07-28 requests and on + transports configured for 2026-07-28 (handshake `initialize` fallback still records it). +- `ID`, `ProgressToken`, task IDs and owners, method names, SEP-2243 request headers and + argument keys, resource subscription URIs and `RequestState` audiences compare by exact Unicode + scalars rather than Swift canonical equivalence + ([details](docs/migration.md#exact-code-point-matching-and-32-bit-safety)). +- `Client.connect(transport:)` disconnects and throws `internalError` when the server answers + `initialize` with a version that is not in `Version.handshake`. The client used that version + before. +- In strict mode, `Client.subscribeToResource(uri:)` and handshake `unsubscribeFromResource(uri:)` + now require `resources.subscribe == true` and throw `methodNotFound` (-32601) when `subscribe` is + `false` or omitted. +- `Server.requestSampling`, `requestElicitation`, and `listRoots` (and their counterparts on + `Server.HandlerContext`) withdraw the request (`notifications/cancelled`) and throw + `CancellationError` when their awaiting task is cancelled + ([details](docs/migration.md#server-to-client-request-cancellation)). +- Binary image/audio `data` and resource `blob` fields decode as standard RFC 4648 §4 base64 + (accepting ASCII whitespace and omitted trailing `=` padding). Non-standard URL-safe base64 + (`-`, `_`), invalid base64, or a `Resource.Content` item with both or neither of `text` and + `blob` fails decoding of the containing result with `DecodingError.dataCorrupted`. +- `Client.Configuration` and `Client.Configuration.TaskOptions` encode durations as + whole-millisecond JSON keys (`discoveryTimeoutMs`, `minimumPollIntervalMs`, + `maximumPollIntervalMs`, `defaultPollIntervalMs`, `requestedTimeToLiveMs`) instead of Swift + `Duration`'s `[high, low]` attosecond form. + +### Features + +- 2026-07-28: per-request `_meta`, `DiscoverServer` (`server/discover`), `OpenSubscriptionStream` + (`subscriptions/listen`), `StatelessHTTPServerTransport`, `resultType`, multi round-trip + requests (`InputRequirement`) with sealed `requestState`, `Mcp-Method`/`Mcp-Name`/`Mcp-Param-*` + headers, cache hints, `extensions`, error codes -32020 to -32022. +- `RequestHandle.progress` (`AsyncSequence` of progress updates) and `RequestHandle.cancel(reason:)`; + `NotificationHandlerRegistration.remove()`. +- `Client.connectionInfo`, `Client.isConnected`, `Client.waitUntilDisconnected()`, + `Client.HandlerContext` (with `Origin`), `Client.discoverServer(meta:)`, + `Client.submitToolCall(name:arguments:meta:)` (returning frozen `Client.ToolCallSubmission`), + and `Client.perform(_:)`. +- Local lifecycle `MCPError` cases (`notConnected`, `alreadyConnected`, `requestFinished`) and + `MCPError.Code: Comparable`. +- `HTTPServerTransport` protocol, `HTTPResponse` struct with frozen `Body`, `Tool.HeaderParameter` + (`Tool.headerParameters()`), and SEP-2243 constants on `HTTPHeaderName`. +- `Metadata` read-write subscript and dictionary literal conformance; `ProgressToken` string and + integer literal conformances. +- Array-literal descriptors and static presets for `Server.Capabilities` (`Capability`, nested + `.enabled`/`.all` presets), `Client.Capabilities` (`Capability`, nested `.enabled`/`.all` + presets), `Server.Configuration` (`Option`, `.handshake`), `Client.Configuration` (`Option`, + `.handshake`), `TaskManager.Configuration` (`Option`, `.default`), `CreateElicitation.Result` + (`.accept`/`.decline`/`.cancel`), `CreateElicitation.Parameters` (`.form`/`.url`), + `InputRequest.elicitation(message:url:elicitationID:)`, `CreateSamplingMessage.ToolChoice` + (`.auto`/`.required`/`.disabled`), `SkillsExtensionSettings`, `UIExtensionSettings`, + `UIResourceMetadata.CSP` (`Directive`), `UIResourceMetadata.Permissions` (`Permission`), + `SubscriptionFilter` (`Entry`, `.allListChanges`), `Tool.Annotations` (`Hint`), `Tool.Execution` + (`.taskForbidden`/`.taskOptional`/`.taskRequired`), `CallTool.Result` (`.text`/`.error`/`.image`/ + `.audio`/`.resource`/`.resourceLink`/`.structured` and array literals), collection-returning + handler results (`ListTools.Result`, `ListResources.Result`, `ListResourceTemplates.Result`, + `ReadResource.Result`, `ListPrompts.Result`, `GetPrompt.Result`, `ListRoots.Result`, + `Complete.Result`), `ContentBlock.textValue`, typed notification factories + (`ResourceUpdatedNotification.message(uri:)`, + `ElicitationCompleteNotification.message(elicitationID:)`), `Method.request(id:meta:)` for all + `NotRequired` methods, `Client.Configuration.MultiRoundTripOptions` (`.enabled`/`.disabled`), + `Client.Configuration.TaskOptions` (`.enabled`), and `Client.SkillLoadingOptions` (`.default`). +- Tasks for `tools/call` at 2025-11-25 (SEP-1686) and the 2026-07-28 tasks extension + (SEP-2663): `Server.serveTasks(with:)`, `Server.HandlerContext.runAsTask(timeToLive:pollInterval:_:)`, + `TaskManager`, `TaskStore` (with pagination `records(owner:startingAt:limit:)` and conditional + update `update(_:ifUnchangedFrom:)`), and `PrincipalResolver` on the server; + `Client.Configuration.tasks`, `callTool` that drives a task, and `TaskHandle` on the client. + A `tools/call` cancelled after the server created its task, also while the answer is on its + way, sends `tasks/cancel` for that task. Over `HTTPClientTransport` at 2026-07-28 the + cancellation closes the response stream, and an answer the client has not read by then is + lost: that task keeps running. +- `Client.Configuration.maximumContextInclusion` caps the `includeContext` a sampling handler sees, + and `Sampling.ContextInclusion` is `Comparable`. +- The skills extension (SEP-2640): `Server.serveSkills(from:listsInResources:)`, `SkillCatalog`, + `SkillPackage` and `InMemorySkillCatalog` (`replaceSkills(with:)`) on the server; `listSkills`, + `getSkill`, `readResourceDirectory` and `loadSkill`, which verifies size, digest and frontmatter, + on the client. +- Authorization: `OAuthConfiguration` grant-specific factories (`.authorizationCode`, + `.clientCredentials`, `.jwtBearer`, `.enterpriseManaged`), `OAuthSigningKey`, `DPoP.ephemeral()`, + `HTTPAuthorizationChallenge.bearerChallenge` and `.dpopChallenge`, issuer checks (RFC 8414, + RFC 9207), `application_type`, authorization server migration, the JWT bearer grant, + enterprise-managed authorization with token exchange, workload identity, and DPoP. +- Sampling with tools (SEP-1577): `Server.requestSampling` takes `tools` and `toolChoice`. Server + and client check the `sampling.tools` and `sampling.context` capabilities and the rules for + tool uses and tool results. +- Request association (SEP-2260): a sampling or elicitation request sent on `Server` outside a + handler context logs one warning for each method. At 2025-11-25 it is still sent. At 2026-07-28 + a request to the client throws -32600, also from code that handles no request. +- Tool names (SEP-986): `Tool.isValidName(_:)`; server and client log a warning once for each + listed name that does not have the format of the specification. +- Foundation Models, on macOS 26, iOS 26, visionOS 26 and watchOS 27 and later + ([#135](https://github.com/modelcontextprotocol/swift-sdk/issues/135), + [#169](https://github.com/modelcontextprotocol/swift-sdk/issues/169)): `Tool` initializers + that take `Generable` argument and output types or a `FoundationModels.Tool`, + `CallTool.Parameters.arguments(as:)`, `CallTool.Result(_:)` and `call(_:)` on a + `FoundationModels.Tool` on the server; `Client.languageModelTools(approval:)`, + `Client.LanguageModelTool` and `GenerationSchema(jsonSchema:name:)` on the client; conversions + between `Value` and `GeneratedContent`. The framework is weak-linked: the deployment targets do + not change. +- Server Cards (SEP-2127): `ServerCard`, `ServerCardResponder`, which serves a card at + `/server-card`, and `ServerCard.fetch`, which reads one. +- MCP Apps (SEP-1865): `Server.serveAppResources(_:listsInResources:)` serves `ui://` views, + `Tool.ui` and `Resource.ui` read and write `_meta.ui`, and `Client.readAppResource` reads a view + with its effective metadata and Content Security Policy. No View-Host bridge. +- A built-in `logging/setLevel` handler that filters `Server.log`. +- `HTTPRequest.init(method:headerFields:body:path:)` takes the header field lines as received and + `HTTPRequest.values(forHeader:)` returns each line's value, so the HTTP server transports refuse + a repeated `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` or `Mcp-Param-*` header at + 2026-07-28 (-32020) without guessing from commas. A repeated `MCP-Protocol-Version` that names + only handshake revisions keeps -32022. Adapters should switch to it; the SwiftNIO example does. +- `Server.AdmissionCheck` (`admissionCheck:` on `Server.init`), `BearerTokenValidator.Result.tokenInfo`, + and `HTTPClientAuthorizer.handleChallenge(_:session:)`, which receives an + `HTTPAuthorizationChallenge` (carrying status, headers, endpoint, operation key, the + `Authorization` header the request sent, and parsed `bearerChallenge`/`dpopChallenge`) and + returns an `HTTPChallengeResult` (`.retry`, `.retryWithDPoPNonce`, or `.unhandled`). +- `TransportSendOptions` (`relatedRequestID`, `headers`), `Transport.send(_:options:)`, six + defaulted transport protocol hooks, and `TransportWrapper`, through which the client hands + `Mcp-Param-*` headers and per-request routing to any transport and wrapping transports forward + every hook automatically. +- `SubscribeToResource.Parameters.init(uri:meta:)` and + `UnsubscribeFromResource.Parameters.init(uri:meta:)` are public, and + `Client.subscribedResourceURIs` lists active handshake subscriptions in addition to 2026-07-28 + listen streams. +- `DataURL`: explicit RFC 2397 `data:` URL value type (`Codable`, `Hashable`, `Sendable`) with + strict RFC 2045 token header validation and MIME type normalization. +- From `main` after 0.12.1: `Implementation` carries `description`, `websiteURL` and `icons`, sent + in `serverInfo` and, at 2026-07-28, in the `_meta` server info of every result, with `data:` icon + URLs as written (#258); `Value.numberValue` reads `.int` and `.double` as `Double` (#226); + `Value.init(encoding:)` takes any `Encodable` instead of `Codable` (#227). +- The full list, with the specification references: [ROADMAP.md](ROADMAP.md#implemented-in-100). + +### Fixes + +- Prompt message content blocks keep `annotations` and `meta`, and `resourceLink` blocks keep + `size`, `icons`, and `meta`. +- `Response.id` (`ID?`) represents JSON `null` distinctly from `""`, and rejects a `null` ID on a + `result` response with `DecodingError.dataCorrupted`. +- `HTTPAuthorizationChallenge.operationKey` includes the tool name for `tools/call` (for example + `"tools/call fetch"`), so scope step-up tracking distinguishes different tools. +- A stopped `Server` is released; every started server leaked before. +- On Linux, `HTTPClientTransport` reads responses as they arrive and handles server-sent events, + so streamed results, server-to-client requests and notifications arrive as on Apple platforms. +- A 4xx reply (other than 401, 403, 408 and 429) with the request's JSON-RPC error delivers that error; + 408, 429 and 5xx fail with the status error. +- A refresh token goes only to the authorization server that issued it, and concurrent OAuth + challenges run one at a time. +- Server-to-client requests run off the receive loop, at most four at a time, and can be cancelled. + The client answers a server `ping`, at once, instead of -32601. +- When the transport ends its receive stream, pending requests fail with `connectionClosed` + instead of waiting forever; `connect(transport:)` on a connected client disconnects the previous + transport. +- `data:` URL strings in messages arrive as sent instead of rewritten as base64 `data:` URLs. +- A decoded standard error equals the error that was sent, without its message text repeated. +- OAuth: a challenge keeps the stored tokens when the authorization server metadata cannot be + read, proactive renewal tries each token once, a failed client registration is tried again, + `http://[::1]` counts as loopback, more private address forms are blocked, error descriptions + redact URL userinfo, query, and fragment, and `private_key_jwt` signing uses `Int64` + `NumericDate`s with a positive `Duration` lifetime and rejects `Int64` overflow. +- HTTP redirects: `HTTPClientTransport`, OAuth discovery/token requests, and `ServerCard.fetch` + separate credentials from `URLSessionConfiguration.httpAdditionalHeaders` and keep them + same-origin; on Linux `HTTPClientTransport` follows up to 20 redirects itself, preserving + 307/308 bodies and stripping representation headers and `Host` when 301/302/303 rewrite to `GET`. +- `HTTPStatusError`'s `debugDescription` names the response headers without their values. +- An `HTTPClientTransport` dropped without `disconnect()` is released and stops its GET stream; + before, it was never released and, with `opensStandaloneStream: true`, kept reconnecting. +- A `connect(transport:)` that throws disconnects the transport and stops the receive loop; + before, both kept running and kept the client and the transport alive. +- Every target builds for iOS: the interop client and the `HelloClient` example no longer use + `Process` on iOS, tvOS, watchOS or visionOS. CI builds every target for the iOS device SDK and + runs the tests on an iOS simulator; `scripts/ci/apple-platform.sh` also takes tvOS, watchOS, + visionOS and Mac Catalyst, which CI does not check. +- A message with a `method` and a string or integer `id` that also has a `result` or an `error` + is a response when it reads as one, as `Server` and `Client` already read a single such + message: the HTTP server transports accept it (HTTP 202) and give it to `Server`, so an answer + to a server request that carries an extra `method` completes that request. A JSON-RPC batch + item reads the same way, instead of being served as a request. Before, neither HTTP transport + answered the POST, the stateful one kept the request's state until the session ended, an + `initialize` with a `result` opened a session, and the stateless one gave the answer to + `Server` under another `id`, so its request was never completed. One that does not read as a + response, such as `"error": 5`, gets -32600 with its `id` (HTTP 400) over HTTP and in a batch, + while a single one on stdio, Network and in-memory transports is served by `Server` as before. +- A request whose `id` is not a string or an integer (`null`, `1.5`, `[]`, `true`, `1e20`), or + whose `jsonrpc` is not `"2.0"`, gets -32600 (HTTP 400) instead of being taken for a notification + and left unanswered. `""` is a valid id: the HTTP transports serve it, and `Request` no longer + decodes a `null` id as `""`. In a JSON-RPC batch each invalid item gets its own -32600 and the + other requests are still answered; a response in a batch answers the server's request it names + instead of failing the batch. +- The HTTP server transports and `Server` answer JSON that is not a JSON-RPC message (a scalar, + an array over HTTP, an object with no `method`, `result` or `error`) with -32600 instead of + -32700, which is kept for a body that is not JSON. A response whose `jsonrpc` is not `"2.0"` + gets -32600 (HTTP 400) instead of 202, and is answered with `"id": null`, alone or in a batch. + An error response with `"id": null` (JSON-RPC 2.0 §5) is accepted with 202 instead of 400, and + gets no reply in a batch. +- A server-to-client request answered with a message `Server` cannot read fails with -32603 instead + of waiting forever, on every transport, alone or in a batch. Over HTTP the answer still gets + 400 when its `jsonrpc` is not `"2.0"`. `Client` likewise fails its request on an answer whose + `method` is not a string. +- A request whose `id` can be read but whose `params` cannot, such as one holding a number out of + range (`1e400`), gets -32600 with its `id` instead of -32700 with `"id": null`. Over the + stateful HTTP transport its POST got no answer. +- A server that serves no handshake revision answers a request that names no `_meta` protocol + version with -32602 (HTTP 400) and `data.supported`, not -32022 or -32601: the field is required, + not unsupported. A `progressToken` that is not a string or an integer gets -32602 in every + revision instead of being ignored. +- `BearerTokenValidator` answers credentials of another scheme (`Basic …`) with 401 and the + Bearer challenge, as for no credentials, instead of 400 without one; a malformed Bearer header + and `.malformedRequest` get 400 with `WWW-Authenticate: Bearer error="invalid_request"` and + `resource_metadata` (RFC 6750 §3.1). +- `OriginValidator.localhost()` and `localhost(port: 80)` accept a loopback `Host` or `http://` + `Origin` without a port, which means the scheme's default port, 80 for `http` (RFC 9110 + §4.2.1); before, both refused it with 421 or 403. `localhost(port:)` with another port still + refuses a value without a port, and every port refuses `https://localhost`. +- A `subscriptions/listen` stream the server ends (`closeSubscriptions()`, `stop()`) is followed, + after its result, by `notifications/cancelled` for the listen request on stdio and other + message-stream transports, as cancellation.mdx requires; `stop()` sends both before it + disconnects the transport. Over HTTP the end of the response stays the teardown. +- An `x-mcp-header` annotation off the `properties` chain (under `items`, `anyOf`, `$defs` or + another subschema keyword, or on the root) makes the tool invalid: the client drops it from + `tools/list` and the server hides it, as streamable-http.mdx requires. Before, it was ignored. + One nested deeper than 32 levels of subschemas is still ignored. +- `HTTPRequest.value(forHeader:)` joins the values of keys that differ only in case, in key order; + it returned whichever the dictionary listed first. At 2026-07-28 a repeated + `MCP-Protocol-Version` or `Mcp-Method` (joined with commas by the adapter, RFC 9110 §5.3) gets + -32020 (HTTP 400) instead of -32022 or a match on one copy. `HTTPRequest.headers` documents the + joining. +- `StatelessHTTPServerTransport` checks `MCP-Protocol-Version` against the versions of its server + (`Server.Configuration.protocolVersions`), so -32022 lists those; it listed every version the + SDK implements. +- A response the client cannot decode (an error `code` that is a string, no `jsonrpc`) fails the + request it names with `internalError("The server sent an invalid response")` instead of leaving + it to wait for its timeout, and the warning logs a sanitized prefix, not the whole message. +- `DataURL` accepts only an empty or `type/subtype` media type made of RFC 2045 tokens + (RFC 2397 §3), so prose such as `data: 3 rows, 2 columns` is rejected. +- Outbound millisecond duration conversions (`timeToLive`, `pollInterval`) clamp negative durations + to `0` and saturate at `Int.max` instead of trapping on overflow, while lenient decoding returns + `nil` for negative or out-of-range values and clamps values above `Int.max` on 32-bit platforms; + `TaskRecord` and `CacheHint` pin their `CodingKeys`; task RFC 3339 timestamps (`createdAt`, + `lastUpdatedAt`) clamp store dates outside `1970-01-01T00:00:00Z...9999-12-31T23:59:59Z` (and + `NaN` to the epoch) so encoded timestamps are always valid four-digit-year dates. +- `Server` answers a request whose `id` is already in flight with -32600 and runs no handler for + it, also for a batch item, including a second item of one batch with the same `id`. Before, the + duplicate replaced the first request's entry, so `notifications/cancelled` stopped the wrong + handler and the first could no longer be cancelled. The `id` is free again once its response is + sent. A handler that catches the cancellation and returns sends no response, and adds no reply + to its batch (#270). +- `StdioTransport` and `NetworkTransport` search each received byte for a newline once. Before, + each read searched the whole unfinished message again, so an 8 MiB message read in 4 KiB pieces + was searched about 8 GiB in all. A received message longer than 16 MiB, the limit of an SSE line + on `HTTPClientTransport`, now ends the receive stream with `internalError` instead of being + buffered however long it grows. That closes the connection: a `Client` fails its pending + requests with the error, and `NetworkTransport` also cancels its `NWConnection`. On + `NetworkTransport`, pass `maximumMessageLength:` to raise the limit (`Int.max` removes it). + `StdioTransport` has no setting that raises or removes the limit. +- Concurrent `StdioTransport.send(_:)` calls write their messages one at a time, in the order + they were called. A send that waited for room in a full pipe let another send write into the + middle of its message (#263). +- A `StdioTransport.send(_:)` cancelled after writing part of its message finishes the message. + Before, it stopped mid-line, the next message continued that line, and the peer lost both. If + the peer stops reading but keeps the pipe open, only `disconnect()` ends such a send. A send + cancelled while it waits for an earlier send or for room in the pipe, before it writes + anything, throws `CancellationError`, also when it was handed its turn as it was cancelled. +- `NetworkTransport` no longer sends heartbeats, and skips incoming heartbeats from 0.12 peers + where a message would start instead of in the first bytes of each read. Before, a message that + arrived in the same read after a heartbeat was dropped, a heartbeat at the end of a read or + split across two reads left its bytes at the start of the next message, and a read that started + at U+1F493 inside a message was discarded. +- `NetworkTransport.connect()` retries (when reconnection is enabled) on a fresh connection to + the same endpoint instead of restarting the cancelled `NWConnection`, which reported no further + state, so a retry never completed. `connectionTimeout` (30 seconds by default) bounds + `connect()` and reconnections while `.waiting` connections wait without consuming retry + attempts. `disconnect()` stops a `connect()` in progress and releases its connection, and + `connect()` after `disconnect()` throws `connectionClosed` (create a new transport to reconnect). + A second `connect()` while one is in progress throws `alreadyConnected` instead of replacing the + first one's connection. +- Disconnected `InMemoryTransport` pairs clear their peer references so both actors deallocate + instead of leaking in a retain cycle. +- Wire-controlled integers that exceed `Int` bounds on 32-bit platforms saturate instead of + trapping. +- `Server` drains queued `start()` and `stop()` calls in FIFO order, clears `connection` when + `start()` fails without a concurrent `stop()`, and waits for `stop()` to disconnect before + settling `waitUntilFinished()`. +- `Icon` decodes unrecognized `theme` strings as `nil` instead of failing the enclosing listing + (`Icon.Theme` remains frozen in 1.x; unrecognized themes are not re-encoded). +- `Response.init(from:)` reports the failing coding path when `result` or `error` fails to decode + instead of throwing a generic root `"Invalid response"` error. +- `TaskSnapshot` equality and hashing ignore its internal wire-generation field. +- On Linux, an OAuth authorization code flow without an `OAuthAuthorizationDelegate` no longer + crashes the process with `SWIFT TASK CONTINUATION MISUSE` after the authorization request. + The authorization code flow 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: `DataURL` 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); + `WWW-Authenticate` parameter values unescape every quoted pair, not only `\"` (#305); + `NetworkTransport` without reconnection cancels its connection when the receive loop gives up, + so the socket no longer stays in `CLOSE_WAIT`, and finishes the receive stream with + `connectionClosed` after repeated empty reads (#283); heartbeats are no longer sent (#326); + `NetworkTransport` clears the connection's state update handler only on the actor's executor, + which removes a data race (#301); `StdioTransport.disconnect()` waits for + sends in progress, and `StdioTransport` leaves descriptor blocking flags unchanged (#297). +- The other behavior changes: [docs/migration.md](docs/migration.md#behavior-changes). + +### Dependencies + +- Added swift-crypto (`3.0.0..<5.0.0`): `requestState` sealing, PKCE and `private_key_jwt`, also + on Linux. +- Added Yams (`from: "6.0.0"`): the YAML frontmatter of skills (SEP-2640). +- Removed eventsource: `HTTPClientTransport` parses server-sent events itself. +- swift-docc-plugin is required `from: "1.4.0"` instead of its `main` branch, so packages can + depend on a released version of `MCP`. + +### Deprecations + +- Roots, sampling and logging, deprecated by the specification (SEP-2577): `Server.requestSampling`, + `listRoots`, `log(level:logger:data:)`; `Client.withSamplingHandler`, `withRootsHandler`, + `notifyRootsChanged`, `setLoggingLevel`. `withSamplingHandler` and `withRootsHandler` keep their + names and signatures; they work on every revision that has them. The server logs a notice the + first time a client declares `roots` or `sampling`, the client when a server declares `logging`. +- `Sampling.ContextInclusion.thisServer` and `.allServers` (SEP-2596): omit `includeContext`, or + use `.none`. +- The list, with the migrations: + [docs/rough_edges.md](docs/rough_edges.md#deprecated-by-the-specification). diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..8ddf16434 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,377 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Overview + +This is the official [Swift SDK](https://github.com/modelcontextprotocol/swift-sdk) +for the [Model Context Protocol](https://modelcontextprotocol.io/docs/2026-07-28/getting-started/intro) (MCP). The package (`mcp-swift-sdk`) +exposes a single library product, `MCP`, implementing both client and server sides of the protocol +against the [2025-11-25](https://modelcontextprotocol.io/specification/2025-11-25) and 2026-07-28 MCP +specifications. See `README.md` +for full API usage examples (client/server setup, transports, tools/resources/prompts, sampling, +elicitation, OAuth authorization). `ROADMAP.md` "SEP coverage" gives the status of every SEP; a +change that implements a SEP updates its row. + +## Common Commands + +```bash +swift build -v # build the package +swift test -v # run the full MCPTests suite +swift test --filter ClientTests # run one test class +swift test --filter ClientTests/testX # run one test method + +# Conformance suite executables (built by scripts/run-conformance.sh) +swift build --product mcp-everything-client +swift build --product mcp-everything-server + +# DocC build; every public declaration needs a doc comment +swift package generate-documentation --target MCP --warnings-as-errors +swift scripts/doc-coverage.swift + +# libFuzzer targets in fuzz/ (Linux only), 60 s per target; for longer runs: +# scripts/ci-linux.sh -- scripts/ci/fuzz.sh +scripts/ci-linux.sh fuzz +``` + +`Package.swift` requires Swift 6.1 tools, the minimum for 1.x; there is no second manifest. + +## Architecture + +**`Sources/MCP/Base/`** — protocol-level building blocks, transport-agnostic: +- `Messages.swift` defines the generic JSON-RPC envelope (`Request`, `Response`, + `Message`) keyed by a `Method` protocol with associated `Parameters`/`Result` types. + New MCP methods are added by defining a type conforming to `Method`, not by extending the + envelope types. +- `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(_:options:)`/`receive()` (an `AsyncThrowingStream`). +- `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 + `NetworkTransport` (Apple platforms only, Network.framework). +- `MCPRequestHeaders.swift` implements SEP-2243 (`Mcp-Method`/`Mcp-Name`/`Mcp-Param-*`). +- `Authorization/` implements OAuth 2.1 client-side flows: discovery (RFC 9728/8414), dynamic + 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 `OAuthSigningKey`). 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 `RequestHandle` (the client's handle on a pending request: id, progress, + cancellation, and value). Handler contexts are passed explicitly to handlers as + `Server.HandlerContext` (`Server/HandlerContext.swift`) and `Client.HandlerContext`. + +**`Sources/MCP/Client/Client.swift`** — `Client` is an `actor`. Owns the transport, drives +`initialize`/capability negotiation, and dispatches outgoing requests/notifications. Also registers +handlers for the server-initiated request types (sampling, elicitation, roots) since MCP allows +some requests to flow server→client. + +**`Sources/MCP/Server/Server.swift`** — `Server` is an `actor`. Owns capability negotiation and +handler registration (`setHandler(for:_:)`). `Tools.swift`, `Resources.swift`, `Prompts.swift`, +`Completion.swift` and `Logging.swift` define the `Method` types and their wire models. +`Configuration.isStrict` controls whether the server rejects requests from a client that hasn't sent +`initialize` yet. + +**`conformance/everything-{client,server}`** — two executables (`MCPConformanceClient`, `MCPConformanceServer`) +that implement the "everything" reference client/server used by the +`modelcontextprotocol/conformance` test suite in CI. Not part of the `MCP` library product. + +**`Examples/`** — `HelloServer`, `HelloClient`, `HTTPServerExample` and the doc snippet targets +(`*Snippets`, tests in `SnippetTests`). `docs/*.md` and `README.md` are generated from +`docs/src/*.src.md` and `README.src.md` by `swift scripts/weave.swift` (`--check` in CI); +never edit the generated files. `.gitattributes` marks them `linguist-generated` (collapsed in +PR diffs); a new generator adds its output there only when CI proves it matches its source, +while output reviewers need to see (conformance baselines, `interop/RESULTS.md`, and +`Tests/MCPTests/Generated/`) stays unmarked. + +**`Tests/MCPTests/`** — one test file per source area; most transport/client/server tests run +against `InMemoryTransport` or `Helpers/MockTransport.swift` rather than real sockets/processes. + +## Protocol versions + +`Sources/MCP/Base/Versioning.swift` is the single source of truth: + +- `Version.handshake` (newest first) are the revisions served through `initialize`; + `Version.stateless` (`2026-07-28`) are served per request with `_meta`. +- `Version.supported` (both lists) and `Version.latestHandshake` (2025-11-25, what `initialize` + requests) are explicit. `latestHandshake` is not `max()`. `Version.negotiate` only ever returns a + handshake revision. `StatefulHTTPServerTransport` validates against `Version.handshake`. +- `Version.profile(for:)` returns a `ProtocolProfile` (`usesInitializeHandshake`, + `usesRequestMeta`, `usesResultType`, `usesSessions`, `allowsServerRequests`, + `usesSubscriptionsListen`, `usesStandardHeaders`, `allowsPrimingEvents`). Code that + differs per revision reads these flags instead of comparing version strings. + +Stateless serving: `Server.handleRequest` classifies each request with +`StatelessRequests.classify` (`Server/StatelessRequests.swift`) from `_meta`; stateless +requests get removed-method/undeclared-capability -32601, `HandlerContext` client fields, +log gating, result annotation (`resultType`, serverInfo, cache hints). `server/discover` +is a default handler. `StatelessHTTPServerTransport` rewrites JSON-RPC ids per exchange, +checks header vs `_meta` version, maps error codes to HTTP status, and streams related +notifications as SSE. Route with `HTTPRequest.statelessProtocolVersion`; the stateful +transport answers such requests with -32022 (handshake versions only). + +Client: `Client.Configuration.protocolMode` (`.automatic` default, `.handshake`, +`.stateless(version: v)`); `.automatic` retries once on -32022 and falls back to `initialize` on +other MCP errors; `.stateless(version: 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(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 +`maximumConcurrentServerRequests` at once (64 more queued), refused at 2026-07-28 and for a +duplicate id. Cancelling the task that awaits `RequestHandle.value` cancels the request. `HTTPClientTransport` takes `MCP-Protocol-Version` from the message `_meta`, +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 +one. The conformance client picks the mode from `MCP_CONFORMANCE_PROTOCOL_VERSION`. + +Request headers (SEP-2243): `MCPRequestHeaders` (`Base/Transports/MCPRequestHeaders.swift`, +internal) holds the codec and `x-mcp-header` rules; the public surface is `HTTPHeaderName` and +`Tool.HeaderParameter`. `Client` computes `Mcp-Method`/`Mcp-Name` and `Mcp-Param-*` (from tool +schemas cached on `tools/list`) into `TransportSendOptions.headers` when the version's profile +`usesStandardHeaders`, and `HTTPClientTransport` forwards them. `StatelessHTTPServerTransport` +checks `Mcp-Method`/`Mcp-Name`; `Server` checks `Mcp-Param-*` against the `tools/list` handler's +schema and drops tools with invalid annotations at stateless. Stateless HTTP tests must +send these headers (the `statelessRequest` test helper derives them). + +Listen streams (SEP-2575): `Server.serveListen` is the built-in `subscriptions/listen` +handler (`listeners` registry; ack first; events from `notify`, which sends list-changed and +resource-updated notifications on the connection only for initialize sessions). +`setSubscriptionAuthorizer` narrows or refuses filters; `notify(_:where:)` targets callers; +`maximumSubscriptionStreams` / `maximumResourceSubscriptions` cap streams and URIs. +`StatelessHTTPServerTransport` restores the client id in `subscriptionId`, cancels a request +whose SSE consumer goes away, refuses listen without SSE (406) and sends `: keep-alive` +comments. `Client.listen(for:)` returns a `Subscription`; the client keeps one background +stream (`refreshNotificationStream`) for list-changed handlers and `subscribeToResource` URIs, +replaced after the successor's ack and reopened with backoff when it fails. + +Other 2026-07-28 foundations: `MCPError` has `data` plus `resourceNotFound(uri:)` +(-32602), `headerMismatch` (-32020), `missingRequiredClientCapabilities` (-32021), +`unsupportedProtocolVersion` (-32022); `Request.meta` / `Message.meta` merge into +`params._meta` (`MetaKey` + typed `Metadata` accessors in `MetaKeys.swift`); +`extensions`/`experimental` on both capability structs; `ResultType`, `CacheScope`, +`CacheableResult` (`Results.swift`). Golden wire tests use `Tests/MCPTests/Helpers/WireExchange.swift`. + +## Conformance: the baseline ratchet + +`scripts/run-conformance.sh` is the single entry point for CI and developer machines. It +runs `@modelcontextprotocol/conformance` pinned exactly to `0.2.0-alpha.12` (2026-07-28 exists +only in the `0.2.0-alpha.*` line). The harness and its dependency tree are locked by +`scripts/conformance-harness/package-lock.json` and installed with `npm ci` into +`.build/conformance-harness`; `CONFORMANCE_PKG` runs another version through `npx`. To bypass +a private npm registry, `export npm_config_registry=https://registry.npmjs.org`. + +```bash +scripts/run-conformance.sh --spec-version 2025-11-25 # stateful handshake wire +scripts/run-conformance.sh --spec-version 2026-07-28 # stateless per-request _meta wire +scripts/run-conformance.sh # bare leg, harness default wire +scripts/run-conformance.sh --requirements 2026-07-28 # tier score (frozen requirement set) +``` + +Flags: `--mode client|server|both`, `--update-baseline`, `--bin-path ` (skip `swift build`; +use `$(swift build --show-bin-path)`), `--port`, `--output-dir` (default `.build/conformance`), +`--solo-attempts` (re-run unexpected failures alone before failing). + +### Legs and baselines + +Every leg runs `--suite all`, which includes `pending` and `draft` scenarios. + +| Leg | Baseline | +|---|---| +| `--spec-version 2025-11-25` | `conformance/baseline.2025-11-25.yml` | +| `--spec-version 2026-07-28` | `conformance/baseline.2026-07-28.yml` | +| bare (default wire) | `conformance/baseline.yml`; the only leg that reaches extension scenarios (`tasks-*`, the skills `sep-2640-*` and the `auth/` extensions) | +| `--requirements ` | none; scores the frozen set `conformance tier-check` uses | + +Baselines are generated, not hand-edited (`--update-baseline`, via +`scripts/conformance-baseline.mjs`). Entries are `:` (no space after the +colon), or a bare `` for a scenario that failed without producing a failing check. + +The harness fails a run on an **unexpected failure** (unlisted) and on a **stale entry** +(listed but now passing). `WARNING` counts as a failure; `SKIPPED` and `INFO` do not. Fixing +conformance therefore forces a baseline regeneration in the same change, and entries only go +down. + +The tier score passes a scenario when it has at least one `SUCCESS` and no `FAILURE` check +(`scripts/conformance-score.mjs`). Tier 1 needs 100% for every claimed revision. + +Since alpha.11 every scenario carries a `wire-schema-valid` check: every message the SDK sends +is validated against the negotiated revision's JSON schema. alpha.12 validates a +`resultType: "task"` result only as a generic result (not against `CallToolResult`), gives +server scenarios a 30 s timeout, and adds the skills scenarios (`sep-2640-*`, default leg; a +scenario SKIPs when its fixture does not declare `io.modelcontextprotocol/skills`). + +## The 2026-07-28 upgrade + +2026-07-28 is brutally breaking. It removes the `initialize`/`notifications/initialized` +handshake, `Mcp-Session-Id`, `ping`, `logging/setLevel`, +`resources/subscribe`/`unsubscribe`, SSE resumability (`Last-Event-ID`), the HTTP GET +endpoint, and all server-initiated requests. It adds `server/discover`, +`subscriptions/listen`, a required `resultType` on every result, `CacheableResult` +(`timeToLive`/`cacheScope`), per-request `_meta` protocol version and capabilities, and +renumbered error codes. + +The SDK stays dual-era: a request carrying `io.modelcontextprotocol/protocolVersion` in +`_meta` is served at 2026-07-28; anything else uses the legacy handshake. + +## Multi round-trip requests (SEP-2322) + +`tools/call`, `prompts/get` and `resources/read` handlers may return +`.inputRequired(.requests(requests, requestState: ...))`. +- Server (`serveRoundTrips` in Server.swift): seals and verifies `requestState` at stateless + (`RequestStateBoundary`, AES-GCM, failure -32602). It rejects content + input (-32603) and + undeclared capabilities (-32021). For handshake clients it bridges by sending the requests + itself, up to 10 rounds. +- Client: `send(_:)` loops through `resolveInputRequests` with the registered + sampling/elicitation/roots handlers (`Configuration.multiRoundTrip`). + +## Tasks (SEP-1686, SEP-2663) + +One model, two wire forms (`design/tasks.md`): v1 at 2025-11-25 (`task` param, `tasks/result`, +`tasks/list`) and v2, the `io.modelcontextprotocol/tasks` extension at 2026-07-28 (server +decides, outcome inlined in `tasks/get`, `tasks/update`). `Base/TaskTypes.swift` has the wire +types; `TaskSnapshot`'s internal `generation` picks the encoding. +- Server: `serveTasks(with: manager)`; a `tools/call` handler returns `context.runAsTask { task in ... }`. + `Server/TaskManager.swift`: `TaskManager` (work, limits, principal, input exchanges, ordered + observers) over a `TaskStore`. `Server.taskRuntime` reads `execution.taskSupport` from the + `tools/list` handler (`ToolInfo`, one pass per call) and refuses before the handler (-32601 v1, -32021 + v2). Capabilities are derived (`advertisedCapabilities`); `execution` is stripped except at + 2025-11-25. v1 `tasks/result` delivers input on its own stream with related-task `_meta`. +- Client: `Configuration.tasks` (`nil` = no tasks); `callTool` drives a task + (`ClientTasks.swift`, `TaskHandle`); v1 augmentation from `toolTaskSupport`. +- Tests: `Tests/MCPTests/TaskTests.swift`; the default conformance leg's `tasks-*` scenarios; + the interop `tasks` profile (Swift and TypeScript at 2025-11-25). + +## Skills (SEP-2640) + +`io.modelcontextprotocol/skills` (`design/skills.md`). `Base/SkillFrontmatter.swift` (internal) +extracts and parses `SKILL.md` frontmatter with Yams, converting the node tree itself with the +YAML 1.2 core schema the harness's `yaml` npm package uses (`.yaml11` opt-in), on a 16 MiB-stack +thread (Yams recursion), bounded (64 KiB, 10,000 nodes). `scripts/frontmatter-corpus.mjs` +regenerates `Tests/MCPTests/Generated/FrontmatterCorpus.swift` from the harness install; +`fuzz/FuzzFrontmatter`. `Base/SkillTypes.swift`: `Skill`, `SkillResource`, `ListSkills`, +`GetSkill`, `ReadResourceDirectory`, `SkillsExtensionSettings`. +- Server (`Server/Skills.swift`): `serveSkills(from: catalog)`; `SkillCatalog` protocol; + `SkillPackage` (validated, digests); `InMemorySkillCatalog`. `Server.skillResources` + answers `resources/read` of skill files before the app's handler and merges `resources/list` + (first page: the app's and the catalog's; `SkillListingCursor` carries both). Gating in `StatelessRequests.isDeclared`; cache hints via + `cacheableMethods`. +- Client (`Client/ClientSkills.swift`): `listSkills`, `getSkill`, `readResourceDirectory`, + `loadSkill` (size, digest, frontmatter; `SkillVerificationError`), `LoadedSkill.read`. +- Fixtures: everything-server serves `pdf-processing` and `acme/billing/refunds`; + everything-client lists (`no-prefetch`) or loads (`verify-*`). Default leg only. + +## Server Cards (SEP-2127) + +Outside the protocol (`design/server_cards.md`), pinned to `modelcontextprotocol/ext-server-card` +at `526201bb`. `Base/ServerCard.swift`: `ServerCard` (the document, `validate()`, `fetch`, +`url(forEndpoint:)`, `Remote.url(resolving:)`, `mismatches(with:)`), `ServerCardError`. +`HTTPServer/ServerCardResponder.swift` answers `/server-card` (ETag, 304, HEAD, +CORS preflight); the stateless transport passes its 304, the stateful one runs validators for +other methods. `scripts/server-card-examples.mjs` regenerates +`Tests/MCPTests/Generated/ServerCardExamples.swift`. `Examples/http-server` serves a card. + +## MCP Apps (SEP-1865) + +`io.modelcontextprotocol/ui` (`design/apps.md`), pinned to `modelcontextprotocol/ext-apps` at +`v2.0.4` (`7af9a75d`, draft text). `Base/AppTypes.swift`: `ExtensionID.ui`, +`UIExtensionSettings`, `UIResourceMetadata` (`CSP.contentSecurityPolicy`, `restrictiveDefault`, `Permissions`), +`UIToolMetadata`; accessors `Tool.ui` (reads the flat `ui/resourceUri`, never writes it), +`Resource.ui`, `Resource.Content.ui`, `Client.Capabilities.ui`. `Server/Apps.swift`: +`UIResource`, `serveAppResources`, `HandlerContext.clientUISettings`. Views and skills share +`Server/BuiltInResources.swift` (ordered sources before the app's handler, one +`mcp-resources:` listing cursor). `Client/ClientApps.swift`: `readAppResource(uri:listing:)` +(content `_meta.ui` over the listing's). No View-Host bridge (ROADMAP "Planned"). + +## Interop + +`scripts/run-interop.sh [--update-results | --check]` runs the Swift, Go and Python SDKs' clients and +servers against each other (profiles basic, advanced, connect, session, tasks, apps), in both eras, over +HTTP and stdio, and writes `.build/interop/report.md` (`--update-results` copies it to +`interop/RESULTS.md`; `--check` fails when the result rows differ from it, via +`interop/report.py --expect`). The other SDKs are pinned releases: `interop/go-client/go.mod`, +`interop/python-client/requirements.in` (hashed lock `requirements.txt`, example servers +checked against `examples.sha256`) and `interop/ts-client/package.json` (`npm ci` from +`package-lock.json`); no local checkouts. The TypeScript SDK (2025-11-25 only) runs the tasks +and apps profiles: `ts-client/client.mjs` and a server, `ts-client/server.mjs`, on its SEP-1686 +runtime and the `ext-apps` 1.7.5 server helpers; the Swift fixture is +`conformance/everything-server/Apps.swift`. The drivers in `interop/{swift-client,go-client,python-client,ts-client}` take the same +flags and checks; keep them in step. Findings: `interop/README.md`. + +## CI + +One job list, two runners. `scripts/ci/jobs` lists every job as +`