diff --git a/CHANGELOG.md b/CHANGELOG.md index ff4cb5e9..d968fcc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,9 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha `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 @@ -75,6 +78,8 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha - 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 diff --git a/Sources/MCP/Client/Client.swift b/Sources/MCP/Client/Client.swift index b71089b8..df64062e 100644 --- a/Sources/MCP/Client/Client.swift +++ b/Sources/MCP/Client/Client.swift @@ -72,6 +72,22 @@ public actor Client { /// task it gets back to its result either way. public var tasks: Tasks? + /// The highest `includeContext` level the client passes to a + /// `sampling/createMessage` handler. When a server asks for more, such + /// as ``Sampling/ContextInclusion/allServers``, the client lowers the + /// request to this level before the handler runs; a request without + /// `includeContext` is left as it is. The default is + /// ``Sampling/ContextInclusion/none``, so a server cannot ask the + /// handler to share context from other MCP servers unless the app + /// raises the cap. + /// + /// The cap applies on every revision, to requests sent on the + /// connection and to input requests (2026-07-28) alike. + /// + /// > Important: `thisServer` and `allServers` are deprecated by the + /// specification (SEP-2596). + public var maxContextInclusion: Sampling.ContextInclusion + /// Creates a client configuration. public init( strict: Bool = false, @@ -80,7 +96,8 @@ public actor Client { discoveryTimeout: Duration? = .seconds(10), multiRoundTrip: MultiRoundTrip = .init(), maxConcurrentServerRequests: Int = 4, - tasks: Tasks? = nil + tasks: Tasks? = nil, + maxContextInclusion: Sampling.ContextInclusion = .none ) { self.strict = strict self.protocolMode = protocolMode @@ -89,11 +106,12 @@ public actor Client { self.multiRoundTrip = multiRoundTrip self.maxConcurrentServerRequests = maxConcurrentServerRequests self.tasks = tasks + self.maxContextInclusion = maxContextInclusion } private enum CodingKeys: String, CodingKey { case strict, protocolMode, logLevel, discoveryTimeout, multiRoundTrip, maxConcurrentServerRequests - case tasks + case tasks, maxContextInclusion } /// Decodes a configuration; keys added after `strict` are optional. @@ -109,6 +127,8 @@ public actor Client { maxConcurrentServerRequests = try container.decodeIfPresent(Int.self, forKey: .maxConcurrentServerRequests) ?? 4 tasks = try container.decodeIfPresent(Tasks.self, forKey: .tasks) + maxContextInclusion = + try container.decodeIfPresent(Sampling.ContextInclusion.self, forKey: .maxContextInclusion) ?? .none } public func encode(to encoder: Encoder) throws { @@ -120,6 +140,7 @@ public actor Client { try container.encode(multiRoundTrip, forKey: .multiRoundTrip) try container.encode(maxConcurrentServerRequests, forKey: .maxConcurrentServerRequests) try container.encodeIfPresent(tasks, forKey: .tasks) + try container.encode(maxContextInclusion, forKey: .maxContextInclusion) } /// How the client uses tasks. @@ -1065,17 +1086,22 @@ public actor Client { /// 2026-07-28. Before a `sampling/createMessage` handler runs, the client /// refuses the request with -32602 when it has `tools` or `toolChoice` and /// ``capabilities`` has no `sampling.tools`, or when its messages break the - /// rules for tool uses and tool results. + /// rules for tool uses and tool results. It lowers an `includeContext` + /// above ``Configuration/maxContextInclusion`` to that level. @discardableResult public func withMethodHandler( _ type: M.Type, handler: @escaping @Sendable (M.Parameters) async throws -> M.Result ) -> Self { methodHandlers[M.name] = TypedRequestHandler { [weak self] (request: Request) -> Response in - if let sampling = request.params as? CreateSamplingMessage.Parameters { + var params = request.params + if let sampling = params as? CreateSamplingMessage.Parameters { try await self?.checkSamplingRequest(sampling) + if let capped = await self?.cappingContext(of: sampling) as? M.Parameters { + params = capped + } } - let result = try await handler(request.params) + let result = try await handler(params) return Response(id: request.id, result: result) } return self @@ -1092,6 +1118,12 @@ public actor Client { } } + /// The sampling request with `includeContext` lowered to + /// ``Configuration/maxContextInclusion``. + private func cappingContext(of params: CreateSamplingMessage.Parameters) -> CreateSamplingMessage.Parameters { + params.capping(includeContext: configuration.maxContextInclusion) + } + /// Send a notification to the server public func notify(_ notification: Message) async throws { guard let connection = connection else { diff --git a/Sources/MCP/Client/Sampling.swift b/Sources/MCP/Client/Sampling.swift index 7c9a3aba..1f44a2a1 100644 --- a/Sources/MCP/Client/Sampling.swift +++ b/Sources/MCP/Client/Sampling.swift @@ -164,7 +164,7 @@ public enum Sampling { /// `thisServer` and `allServers` are deprecated by the specification /// (SEP-2596). They are removed no later than sampling. Omit /// `includeContext`, or use ``none``. They still decode and encode. - public enum ContextInclusion: String, Hashable, Codable, Sendable { + public enum ContextInclusion: String, Hashable, Codable, Sendable, Comparable { /// No additional context case none /// Include context from the requesting server @@ -173,6 +173,23 @@ public enum Sampling { /// Include context from all connected MCP servers @available(*, deprecated, message: "Deprecated by the specification (SEP-2596): omit includeContext, or use .none") case allServers + + /// The position in the order `none`, `thisServer`, `allServers`. + /// + /// Reads the raw value, so the SDK does not name the deprecated cases. + private var level: Int { + switch rawValue { + case "none": return 0 + case "thisServer": return 1 + default: return 2 + } + } + + /// Orders the levels by how much context they share: `none` is below + /// `thisServer`, which is below `allServers`. + public static func < (lhs: ContextInclusion, rhs: ContextInclusion) -> Bool { + lhs.level < rhs.level + } } /// Stop reason for sampling completion. @@ -700,6 +717,25 @@ extension CreateSamplingMessage.Parameters { return includeContext != Sampling.ContextInclusion.none } + /// The request with `includeContext` lowered to `maximum`. A request with + /// no `includeContext`, or one at or below `maximum`, is returned as it is. + func capping(includeContext maximum: Sampling.ContextInclusion) -> CreateSamplingMessage.Parameters { + guard let requested = includeContext, requested > maximum else { return self } + return CreateSamplingMessage.Parameters( + messages: messages, + modelPreferences: modelPreferences, + systemPrompt: systemPrompt, + includeContext: maximum, + temperature: temperature, + maxTokens: maxTokens, + stopSequences: stopSequences, + _meta: _meta, + tools: tools, + toolChoice: toolChoice, + metadata: metadata + ) + } + /// The first violation of the message rules for tools, or `nil`. /// /// The rules of the specification: diff --git a/Tests/MCPTests/SamplingTests.swift b/Tests/MCPTests/SamplingTests.swift index 8335c912..2d872731 100644 --- a/Tests/MCPTests/SamplingTests.swift +++ b/Tests/MCPTests/SamplingTests.swift @@ -3,6 +3,8 @@ import Testing import class Foundation.JSONDecoder import class Foundation.JSONEncoder +import class Foundation.JSONSerialization +import struct Foundation.Data @testable import MCP @@ -549,7 +551,7 @@ struct SamplingIntegrationTests { let client = Client( name: "SamplingTestClient", version: "1.0", - configuration: .handshake + configuration: .init(protocolMode: .handshake, maxContextInclusion: allServers) ) // Register sampling handler on client to respond to server's request @@ -997,6 +999,142 @@ struct SamplingIntegrationTests { } } +@Suite("Sampling context inclusion cap", .timeLimit(.minutes(1))) +struct SamplingContextInclusionCapTests { + private actor Seen { + private(set) var values: [Sampling.ContextInclusion?] = [] + func record(_ value: Sampling.ContextInclusion?) { values.append(value) } + } + + /// Connects a client to a server whose tool asks it for sampling with + /// `requested`: a `sampling/createMessage` request at 2025-11-25, an input + /// request at 2026-07-28. Returns what the handler saw, one value for each call. + @available(*, deprecated, message: "Uses the deprecated sampling API (SEP-2577)") + private func seenByHandler( + configuration: Client.Configuration, requested: Sampling.ContextInclusion? + ) async throws -> [Sampling.ContextInclusion?] { + let handshake = configuration.protocolMode == .handshake + let server = Server(name: "CapTestServer", version: "1.0", capabilities: .init(tools: .init())) + await server.withMethodHandler(CallTool.self) { [weak server] params in + if handshake { + guard let server else { throw MCPError.internalError("gone") } + _ = try await server.requestSampling( + messages: [.user("hi")], includeContext: requested, maxTokens: 10) + } else if params.inputResponses?["model"] == nil { + return .inputRequired( + ["model": .sampling(.init(messages: [.user("hi")], includeContext: requested, maxTokens: 10))]) + } + return .init(content: [.text(text: "done")]) + } + let (clientTransport, serverTransport) = await InMemoryTransport.createConnectedPair() + try await server.start(transport: serverTransport) + + let client = Client( + name: "CapTestClient", version: "1.0", + capabilities: .init(sampling: .init(context: .init())), configuration: configuration) + let seen = Seen() + await client.withSamplingHandler { parameters in + await seen.record(parameters.includeContext) + return CreateSamplingMessage.Result( + model: "test-model", stopReason: .endTurn, role: .assistant, content: .text("ok")) + } + try await client.connect(transport: clientTransport) + _ = try await client.callTool(name: "sample") + await client.disconnect() + await server.stop() + return await seen.values + } + + @Test("ContextInclusion is ordered none < thisServer < allServers") + func ordering() { + let none = Sampling.ContextInclusion.none + #expect(none < thisServer) + #expect(thisServer < allServers) + #expect(none < allServers) + #expect(!(allServers < thisServer)) + #expect(!(none < none)) + #expect([allServers, none, thisServer].sorted() == [none, thisServer, allServers]) + } + + @Test("The default cap is none") + func defaultCap() { + #expect(Client.Configuration().maxContextInclusion == Sampling.ContextInclusion.none) + #expect(Client.Configuration.default.maxContextInclusion == Sampling.ContextInclusion.none) + #expect(Client.Configuration.strict.maxContextInclusion == Sampling.ContextInclusion.none) + } + + @Test("The cap is saved with the configuration, and a missing key is none") + func configurationCoding() throws { + let configuration = Client.Configuration(maxContextInclusion: thisServer) + let json = try #require( + JSONSerialization.jsonObject(with: JSONEncoder().encode(configuration)) as? [String: Any]) + #expect(json["maxContextInclusion"] as? String == "thisServer") + #expect(try JSONDecoder().decode(Client.Configuration.self, from: JSONEncoder().encode(configuration)) == configuration) + + let saved = try JSONDecoder().decode(Client.Configuration.self, from: Data(#"{"strict":true}"#.utf8)) + #expect(saved.maxContextInclusion == Sampling.ContextInclusion.none) + } + + @Test( + "The client lowers a requested includeContext to the cap before the handler runs", + arguments: [Client.ProtocolMode.handshake, .automatic], + [ + // (cap, requested, seen by the handler) + (nil, allServers, Sampling.ContextInclusion.none), + (nil, thisServer, Sampling.ContextInclusion.none), + (nil, Sampling.ContextInclusion.none, Sampling.ContextInclusion.none), + (thisServer, allServers, thisServer), + (thisServer, thisServer, thisServer), + (thisServer, Sampling.ContextInclusion.none, Sampling.ContextInclusion.none), + (allServers, allServers, allServers), + (allServers, thisServer, thisServer), + ] as [(Sampling.ContextInclusion?, Sampling.ContextInclusion, Sampling.ContextInclusion)] + ) + @available(*, deprecated, message: "Uses the deprecated sampling API (SEP-2577)") + func cap( + mode: Client.ProtocolMode, + row: (cap: Sampling.ContextInclusion?, requested: Sampling.ContextInclusion, expected: Sampling.ContextInclusion) + ) async throws { + var configuration = Client.Configuration(protocolMode: mode) + if let cap = row.cap { configuration.maxContextInclusion = cap } + let seen = try await seenByHandler(configuration: configuration, requested: row.requested) + #expect(seen == [row.expected]) + } + + @Test("A request without includeContext stays without", arguments: [Client.ProtocolMode.handshake, .automatic]) + @available(*, deprecated, message: "Uses the deprecated sampling API (SEP-2577)") + func absentStaysAbsent(mode: Client.ProtocolMode) async throws { + let configuration = Client.Configuration(protocolMode: mode) + let seen = try await seenByHandler(configuration: configuration, requested: nil) + #expect(seen.count == 1) + #expect(seen.first == .some(nil)) + } + + @Test("The cap keeps every other field of the request") + func cappingKeepsFields() { + let params = CreateSamplingMessage.Parameters( + messages: [.user("hi")], + modelPreferences: .init(hints: [.init(name: "claude")], intelligencePriority: 0.9), + systemPrompt: "system", + includeContext: allServers, + temperature: 0.5, + maxTokens: 10, + stopSequences: ["END"], + _meta: Metadata(additionalFields: ["vendor.example/key": .string("value")]), + metadata: ["k": .string("v")] + ) + let capped = params.capping(includeContext: Sampling.ContextInclusion.none) + #expect(capped.includeContext == Sampling.ContextInclusion.none) + #expect( + CreateSamplingMessage.Parameters( + messages: params.messages, modelPreferences: params.modelPreferences, + systemPrompt: params.systemPrompt, includeContext: Sampling.ContextInclusion.none, + temperature: params.temperature, maxTokens: params.maxTokens, + stopSequences: params.stopSequences, _meta: params._meta, metadata: params.metadata) == capped) + #expect(params.capping(includeContext: allServers) == params) + } +} + @Suite("Sampling 2025-11-25 Spec Tests") struct Sampling2025_11_25Tests { @Test("Audio content encoding and decoding") diff --git a/docs/client.md b/docs/client.md index 5dae9f12..ddf6cf12 100644 --- a/docs/client.md +++ b/docs/client.md @@ -471,6 +471,8 @@ The client checks each sampling request before the handler runs. It answers with At 2026-07-28 the call that received the input request fails with that error. The client does not refuse an `includeContext` it did not declare `context` for: it can ignore the field. +`Configuration.maxContextInclusion` caps `includeContext`. When a server asks for a higher level, the client lowers it to the cap before the handler runs, at both eras. The default is `.none`, so a handler never sees a request to share context from other MCP servers unless the app raises the cap. A request without `includeContext` is not changed. + The two eras differ as for [Roots](#roots): `sampling/createMessage` from the server at 2025-11-25, a `sampling/createMessage` input request at 2026-07-28, the same handler for both. The errors are the same, with `sampling/createMessage` as the method. ## Elicitation diff --git a/docs/migration.md b/docs/migration.md index 5cb7433f..c99d6ae0 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -506,10 +506,29 @@ these releases. `Server.Configuration` gained `protocolVersions`, `cacheHints` and `defaultCacheHint`; `Client.Configuration` gained `protocolMode`, `logLevel`, -`discoveryTimeout` and `multiRoundTrip`. A missing key decodes to the default +`discoveryTimeout`, `multiRoundTrip` and `maxContextInclusion`. A missing key decodes to the default of its initializer parameter, so JSON encoded by the previous release, `{"strict":true}`, still decodes. +### Sampling handlers see `includeContext` capped at `none` + +`Client.Configuration.maxContextInclusion` defaults to `.none`. When a server +asks for `includeContext: thisServer` or `allServers`, the client lowers it to +the cap before the `withSamplingHandler` handler runs, so the handler sees +`.none`. This holds at both eras, for requests and input requests alike. To +keep the previous behavior, raise the cap: + +```swift +let client = Client( + name: "App", version: "1.0", + configuration: .init(maxContextInclusion: .allServers) +) +``` + +Both values are deprecated by the specification (SEP-2596), so the compiler +warns about them. `Sampling.ContextInclusion` is `Comparable`: +`none < thisServer < allServers`. + ### Servers serve 2026-07-28 `Server.Configuration.protocolVersions` defaults to diff --git a/docs/src/client.src.md b/docs/src/client.src.md index aa385e1b..c60623b8 100644 --- a/docs/src/client.src.md +++ b/docs/src/client.src.md @@ -252,6 +252,8 @@ The client checks each sampling request before the handler runs. It answers with At 2026-07-28 the call that received the input request fails with that error. The client does not refuse an `includeContext` it did not declare `context` for: it can ignore the field. +`Configuration.maxContextInclusion` caps `includeContext`. When a server asks for a higher level, the client lowers it to the cap before the handler runs, at both eras. The default is `.none`, so a handler never sees a request to share context from other MCP servers unless the app raises the cap. A request without `includeContext` is not changed. + The two eras differ as for [Roots](#roots): `sampling/createMessage` from the server at 2025-11-25, a `sampling/createMessage` input request at 2026-07-28, the same handler for both. The errors are the same, with `sampling/createMessage` as the method. ## Elicitation diff --git a/docs/src/migration.src.md b/docs/src/migration.src.md index b764489c..31041194 100644 --- a/docs/src/migration.src.md +++ b/docs/src/migration.src.md @@ -406,10 +406,29 @@ these releases. `Server.Configuration` gained `protocolVersions`, `cacheHints` and `defaultCacheHint`; `Client.Configuration` gained `protocolMode`, `logLevel`, -`discoveryTimeout` and `multiRoundTrip`. A missing key decodes to the default +`discoveryTimeout`, `multiRoundTrip` and `maxContextInclusion`. A missing key decodes to the default of its initializer parameter, so JSON encoded by the previous release, `{"strict":true}`, still decodes. +### Sampling handlers see `includeContext` capped at `none` + +`Client.Configuration.maxContextInclusion` defaults to `.none`. When a server +asks for `includeContext: thisServer` or `allServers`, the client lowers it to +the cap before the `withSamplingHandler` handler runs, so the handler sees +`.none`. This holds at both eras, for requests and input requests alike. To +keep the previous behavior, raise the cap: + +```swift +let client = Client( + name: "App", version: "1.0", + configuration: .init(maxContextInclusion: .allServers) +) +``` + +Both values are deprecated by the specification (SEP-2596), so the compiler +warns about them. `Sampling.ContextInclusion` is `Comparable`: +`none < thisServer < allServers`. + ### Servers serve 2026-07-28 `Server.Configuration.protocolVersions` defaults to