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..88c716feb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,6 +2,8 @@ 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. +[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`, `RequestContext` +│ │ ├── 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. `Data` data URL encoding) +│ └── 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,24 @@ 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: ```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) -} +/// The newest handshake revision. +@available(*, deprecated, renamed: "latestHandshake", message: "The newest revision is Version.stateless[0]") +public static var latest: String { latestHandshake } ``` +- 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,9 +178,12 @@ 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 @@ -166,6 +197,8 @@ public static func text(_ text: String, metadata: Metadata? = nil) -> Self { `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 @@ -219,18 +252,21 @@ public struct WidgetListChangedNotification: Notification { 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. + appended. `Server.start` registers default handlers (`initialize`, `ping`, `server/discover`, + `subscriptions/listen`, `logging/setLevel`), and `withTasks(_:)` and + `withSkills(_:listInResources:)` 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`. @@ -245,20 +281,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. @@ -276,8 +318,9 @@ 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 @@ -293,6 +336,10 @@ 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 +368,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..cca4dad53 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,316 @@ +# 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 + +- `MCPError` has four new cases, and `serverError` carries `data`. +- `HTTPResponse.data` and `.error` have new associated values. +- `Client.Capabilities.experimental` is `[String: Value]?`. +- Open structs instead of enums: `OAuthAuthorizationError`, `GrantType`, + `TokenEndpointAuthentication`, `PrivateKeyJWTSigningAlgorithm`, `BearerTokenValidationResult`, + `Elicitation.Mode`, `ToolChoice.Mode`. +- An `.unknown` case for kinds from a later revision on the content blocks, `InputRequest`, + `InputResponse` and `CreateElicitation.Parameters`. +- The `Client` convenience methods return result types; `startToolCall` replaces the + `RequestContext` overload of `callTool`; `Client.initialize()` is removed. +- `Client.connect(transport:)` returns `Client.ConnectionInfo`. +- The deprecated `Tool.Content` short forms are removed. +- `HTTPClientTransport` throws `transportError(HTTPStatusError)` and + `transportError(OAuthAuthorizationError)` instead of `internalError` with a message. +- `HTTPClientAuthorizer.authorizationHeader(for:)` is `authorizationHeaders(for:method:)`. +- 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)). +- 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)). + +Behavior that can break working code ([docs/migration.md](docs/migration.md#behavior-changes)): + +- 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 `errorCode` to handle either case. +- An undecodable direct peer result now throws `ResponseDecodingError` 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.maxContextInclusion`, + which defaults to `.none`. Set `maxContextInclusion: .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. +- Behind `StatelessHTTPServerTransport`, a server with an `initializeHook` and no + `statelessRequestHook` refuses handshake requests other than `initialize` with -32600. +- `.none(clientID:)` with a client ID that is not empty and not a URL is pre-registered: no + dynamic client registration. Pass `""` to register. +- 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.tokenEndpoint(issuer:)` 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)). +- `HTTPClientTransport.connect()` after `disconnect()` throws `internalError`: create a new + transport to reconnect. +- `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. + +### Features + +- 2026-07-28: per-request `_meta`, `server/discover`, `subscriptions/listen`, + `StatelessHTTPServerTransport`, `resultType`, multi round-trip requests with sealed + `requestState`, `Mcp-Method`/`Mcp-Name`/`Mcp-Param-*` headers, cache hints, `extensions`, error + codes -32020 to -32022. +- Tasks for `tools/call` at 2025-11-25 (SEP-1686) and the 2026-07-28 tasks extension + (SEP-2663): `Server.withTasks(_:)`, `runAsTask`, `TaskManager` and `TaskStore` on the server; + `Client.Configuration.tasks`, `callTool` that drives a task, and `TaskHandle` on the client. +- `Client.Configuration.maxContextInclusion` caps the `includeContext` a sampling handler sees, and + `Sampling.ContextInclusion` is `Comparable`. + 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. +- The skills extension (SEP-2640): `Server.withSkills(_:listInResources:)`, `SkillCatalog`, + `SkillPackage` and `InMemorySkillCatalog` on the server; `listSkills`, `getSkill`, + `readResourceDirectory` and `loadSkill`, which verifies size, digest and frontmatter, on the + client. +- Authorization: issuer checks (RFC 8414, RFC 9207), `application_type`, authorization server + migration, the JWT bearer grant, enterprise-managed authorization with token exchange, workload + identity, 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 while the server handles + no client request 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`, `ServerCardValidator`, which serves a card at + `/server-card`, and `ServerCard.fetch`, which reads one. +- MCP Apps (SEP-1865): `Server.withAppResources` 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.headerValues(_:)` 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. +- `statelessRequestHook` on `Server.start`, `HTTPClientTransport.cancelRequest(_:)`, + `BearerTokenValidationResult.tokenInfo`, and the `HTTPClientAuthorizer` requirement + `handleChallenge(statusCode:headers:endpoint:operationKey:sentAuthorization:session:)`, with a + default, which receives the `Authorization` header of the challenged request and returns an + `HTTPChallengeResult` that says whether the retry is a DPoP nonce retry. +- The `Transport` requirement `send(_:additionalHeaders:)`, with a default that ignores the + headers, through which the client hands the `Mcp-Param-*` headers of a `tools/call` to any + transport. A custom Streamable HTTP transport sends them on the request's POST, and a wrapping + transport forwards them; `HTTPClientTransport` implements it. +- From `main` after 0.12.1: `Server.init` takes `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(_:)` + takes any `Encodable` instead of `Codable` (#227). +- The full list, with the specification references: [ROADMAP.md](ROADMAP.md#implemented-in-100). + +### Fixes + +- 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, and more private address forms are blocked. +- `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 `streaming: 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 under more than `MCPRequestHeaders.maxSchemaDepth` (32) levels of subschemas is still + ignored. +- `HTTPRequest.header(_:)` 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. +- `Data.isDataURL(string:)` and `Data.parseDataURL(_:)` accept only an empty or `type/subtype` + media type made of RFC 2045 tokens (RFC 2397 §3), so text such as `data: 3 rows, 2 columns` + decodes as `Value.string`, not `.data`. +- `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`. A + `NetworkTransport` whose `BufferConfiguration.maxReceiveBufferSize` is larger than 16 MiB accepts + messages up to that size, and one with `BufferConfiguration.unlimited` keeps no limit. + `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` finds the peer's heartbeats in the received byte stream, 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. A receiver on an earlier release still mishandles heartbeats; + set `HeartbeatConfiguration.disabled` on the peer that sends to it. +- `NetworkTransport.connect()` retries on a fresh connection to the same endpoint instead of + restarting the cancelled `NWConnection`, which reported no further state, so a retry never + completed. `connect()` to an unreachable peer now fails within the retry budget rather than + blocking forever: a `.waiting` connection counts as a failed attempt, so `maxAttempts` and + backoff apply. `disconnect()` stops a `connect()` in progress and releases its connection. A + second `connect()` while one is in progress throws instead of replacing the first one's + connection, and that includes a `connect()` stopped by `disconnect()` until it has returned, + which can take the rest of its backoff. A `connect()` after that dials a fresh connection. +- On Linux, an OAuth authorization code flow without an `OAuthAuthorizationDelegate` no longer + crashes the process with `SWIFT TASK CONTINUATION MISUSE` after the authorization request. + `OAuthAuthorizationCodeFlow` cancelled its session's request once the request had returned, and + on swift-corelibs-foundation a request cancelled as it finishes completes a second time. +- On Linux, cancelling an `HTTPClientTransport` request no longer crashes the process with + `Trying to access a behaviour for a task that in not in the registry`. The session that streams + responses had the configuration's `URLCache`, and swift-corelibs-foundation could fail a task + cancelled during its cache lookup after the session had let it go; that session now has no + cache, nor do the sessions the OAuth requests run in. `ServerCard.fetch(from:session:)` on + Linux therefore no longer answers from the session's cache; `fetch(from:ifNoneMatch:session:)` + revalidates a card the caller kept. +- From `main` after 0.12.1: `Data.parseDataURL(_:)` reads `;base64` from the header only and + decodes any percent-escaped byte (#309, #310); `client_secret_basic` percent-encodes the client + credentials (RFC 6749 §2.3.1, #300); PKCE verifier characters are uniformly distributed (#303); + `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), and then stops its heartbeats (#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 restores the blocking mode of the descriptors (#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 + +- `Version.latest`: use `Version.latestHandshake`. +- Roots, sampling and logging, deprecated by the specification (SEP-2577): `Server.requestSampling`, + `listRoots`, `log(level:logger:data:)`; `Client.withSamplingHandler`, `withRootsHandler`, + `notifyRootsChanged`, `setLoggingLevel`. 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). +- `CreateSamplingMessage.ToolChoice.init(mode:)` with an optional mode: pass a `Mode`. With an + optional parameter, `.none` is `nil`, which is `auto`. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..ef60a1e73 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,353 @@ +# 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) (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`, + `Notification`) 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(_:)`/`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 `DPoPSigningKey`). The transport sets + `authorizationHeaders(for:method:)` after `requestModifier` and passes every response to + `didReceiveResponse(headers:for:)` (DPoP nonces). + This is opt-in — wired in via an `OAuthAuthorizer` passed to `HTTPClientTransport`. +- `Utilities/` holds cross-cutting concerns used by both Client and Server: `Cancellation`, + `Progress`, `Ping`, and `RequestContext` (the client's handle on a pending request: id and + task). Handler context is `Server.currentHandlerContext` (task-local). + +**`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 (`withMethodHandler`). `Tools.swift`, `Resources.swift`, `Prompts.swift`, +`Completion.swift` and `Logging.swift` define the `Method` types and their wire models. +`Configuration.strict` 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. + +**`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. `latest` 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(v)`); `.automatic` retries once on -32022 and falls back to `initialize` on +other MCP errors; `.stateless(v)` never retries. Tests that exercise the handshake pin +`.handshake` (`Tests/MCPTests/Helpers/HandshakeConfiguration.swift`). `send` stamps the `_meta` envelope when +`isStateless`. Request lifecycle: `register` puts a `ResponseSlot` in `pendingRequests` before +`send` returns and `transmit` sends from a task (`unsentRequests`); `withBatch` uses the same +path. Handlers run off the receive loop: notification handlers run one at a time on the +inbound queue; responses are delivered at once, except that a response waits for queued +progress notifications of its own request (`progressTokens`, `parkedResponses`; requests sent +from a notification handler never wait, via the `isHandlingNotification` task-local). The +client handles `notifications/cancelled` and the listen acknowledgement itself in the receive +loop (`handleBuiltIn`). Server-to-client requests run in `incomingRequests` tasks, at most +`maxConcurrentServerRequests` at once (64 more queued), refused at 2026-07-28 and for a +duplicate id. Cancelling the task that awaits `RequestContext.value` cancels the request. `HTTPClientTransport` takes `MCP-Protocol-Version` from the message `_meta`, +delivers JSON-RPC error bodies of non-2xx replies, and `useStatelessProtocol(_:)` drops the +session and GET stream. A handshake POST stream that ends before its response is resumed +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`) +holds the codec and `x-mcp-header` rules. `HTTPClientTransport` adds `Mcp-Method`/`Mcp-Name` +when the version's profile `usesStandardHeaders`; `Client` mirrors `Mcp-Param-*` from +tool schemas cached on `tools/list`. `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). +`withSubscriptionAuthorizer` narrows or refuses filters; `notify(_:to:)` targets callers; +`maxSubscriptionStreams` / `maxResourceSubscriptions` 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(_:)` 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` +(`ttlMs`/`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, 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: `withTasks(manager)`; a `tools/call` handler returns `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`, `SkillsSettings`. +- Server (`Server/Skills.swift`): `withSkills(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`, +`cardURL(forEndpoint:)`, `Remote.url(resolving:)`, `mismatches(with:)`), `ServerCardError`. +`HTTPServer/ServerCardValidator.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`, `UIResourceMeta` (`CSP.policy()`, `restrictiveDefault`, `Permissions`), +`ToolUIMeta`; accessors `Tool.ui` (reads the flat `ui/resourceUri`, never writes it), +`Resource.ui`, `Resource.Content.ui`, `Client.Capabilities.ui`. `Server/Apps.swift`: +`UIResource`, `withAppResources`, `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 +`