diff --git a/CHANGELOG.md b/CHANGELOG.md index 98178e31..25b64f5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -372,6 +372,9 @@ Behavior that can break working code ([docs/migration.md](docs/migration.md#beha `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`. +- `Server.setSubscriptionPrincipal(_:)` and `Server.Configuration.maximumSubscriptionStreamsPerPrincipal` + (default 100) cap the `subscriptions/listen` streams one principal may hold, so one caller of a + shared server cannot take every stream. - `HTTPRequest.init(method:headerFields:body:path:)` takes the header field lines as received and `HTTPRequest.values(forHeader:)` returns each line's value, so the HTTP server transports refuse a repeated `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` or `Mcp-Param-*` header at diff --git a/Sources/MCP/Server/PrincipalResolver.swift b/Sources/MCP/Server/PrincipalResolver.swift index 2a7db177..5f585263 100644 --- a/Sources/MCP/Server/PrincipalResolver.swift +++ b/Sources/MCP/Server/PrincipalResolver.swift @@ -1,5 +1,5 @@ /// Identifies the caller of a request, such as the authenticated user, for binding tasks and -/// request state to it. +/// request state to it and limiting `subscriptions/listen` streams per caller. public struct PrincipalResolver: Sendable { private let resolve: @Sendable (Server.HandlerContext) async -> String? diff --git a/Sources/MCP/Server/Server+Presets.swift b/Sources/MCP/Server/Server+Presets.swift index 0cd5e3af..92f329d8 100644 --- a/Sources/MCP/Server/Server+Presets.swift +++ b/Sources/MCP/Server/Server+Presets.swift @@ -16,6 +16,7 @@ extension Server.Configuration: ExpressibleByArrayLiteral { case cacheHints([String: CacheHint]) case defaultCacheHint(CacheHint) case maximumSubscriptionStreams(Int) + case maximumSubscriptionStreamsPerPrincipal(Int) case maximumResourceSubscriptions(Int) } @@ -74,6 +75,16 @@ extension Server.Configuration: ExpressibleByArrayLiteral { Option(.maximumSubscriptionStreams(limit)) } + /// Sets the maximum number of open `subscriptions/listen` streams per + /// principal. + /// + /// - Parameter limit: See ``Server/Configuration/maximumSubscriptionStreamsPerPrincipal``. + /// - Returns: A configuration option setting + /// ``Server/Configuration/maximumSubscriptionStreamsPerPrincipal``. + public static func maximumSubscriptionStreamsPerPrincipal(_ limit: Int) -> Option { + Option(.maximumSubscriptionStreamsPerPrincipal(limit)) + } + /// Sets the maximum number of resource URIs (and separately task IDs) /// one `subscriptions/listen` stream may name. /// @@ -106,6 +117,8 @@ extension Server.Configuration: ExpressibleByArrayLiteral { defaultCacheHint = hint case .maximumSubscriptionStreams(let limit): maximumSubscriptionStreams = limit + case .maximumSubscriptionStreamsPerPrincipal(let limit): + maximumSubscriptionStreamsPerPrincipal = limit case .maximumResourceSubscriptions(let limit): maximumResourceSubscriptions = limit } diff --git a/Sources/MCP/Server/Server.swift b/Sources/MCP/Server/Server.swift index 41e14d57..6765ec1f 100644 --- a/Sources/MCP/Server/Server.swift +++ b/Sources/MCP/Server/Server.swift @@ -51,6 +51,12 @@ public actor Server { /// streams are refused with -32600. public var maximumSubscriptionStreams: Int + /// The most `subscriptions/listen` streams one principal may have open + /// at once; further streams of that principal are refused with -32600. + /// Applies only when ``Server/setSubscriptionPrincipal(_:)`` sets a + /// resolver; callers without a principal share a single allowance. + public var maximumSubscriptionStreamsPerPrincipal: Int + /// The most resource URIs, and separately the most task IDs, that one /// `subscriptions/listen` stream may name. A stream that names more /// of either is refused with -32602. @@ -63,6 +69,7 @@ public actor Server { self.cacheHints = [:] self.defaultCacheHint = .uncached self.maximumSubscriptionStreams = 1000 + self.maximumSubscriptionStreamsPerPrincipal = 100 self.maximumResourceSubscriptions = 256 } @@ -74,6 +81,7 @@ public actor Server { /// - cacheHints: See ``cacheHints``. /// - defaultCacheHint: See ``defaultCacheHint``. /// - maximumSubscriptionStreams: See ``maximumSubscriptionStreams``. + /// - maximumSubscriptionStreamsPerPrincipal: See ``maximumSubscriptionStreamsPerPrincipal``. /// - maximumResourceSubscriptions: See ``maximumResourceSubscriptions``. public init( isStrict: Bool = false, @@ -81,6 +89,7 @@ public actor Server { cacheHints: [String: CacheHint] = [:], defaultCacheHint: CacheHint = .uncached, maximumSubscriptionStreams: Int = 1000, + maximumSubscriptionStreamsPerPrincipal: Int = 100, maximumResourceSubscriptions: Int = 256 ) { self.isStrict = isStrict @@ -88,6 +97,7 @@ public actor Server { self.cacheHints = cacheHints self.defaultCacheHint = defaultCacheHint self.maximumSubscriptionStreams = maximumSubscriptionStreams + self.maximumSubscriptionStreamsPerPrincipal = maximumSubscriptionStreamsPerPrincipal self.maximumResourceSubscriptions = maximumResourceSubscriptions } @@ -95,6 +105,7 @@ public actor Server { case isStrict = "strict" case protocolVersions, cacheHints, defaultCacheHint case maximumSubscriptionStreams = "maxSubscriptionStreams" + case maximumSubscriptionStreamsPerPrincipal = "maxSubscriptionStreamsPerPrincipal" case maximumResourceSubscriptions = "maxResourceSubscriptions" } @@ -112,6 +123,9 @@ public actor Server { maximumSubscriptionStreams = try container.decodeIfPresent(Int.self, forKey: .maximumSubscriptionStreams) ?? defaults.maximumSubscriptionStreams + maximumSubscriptionStreamsPerPrincipal = + try container.decodeIfPresent(Int.self, forKey: .maximumSubscriptionStreamsPerPrincipal) + ?? defaults.maximumSubscriptionStreamsPerPrincipal maximumResourceSubscriptions = try container.decodeIfPresent(Int.self, forKey: .maximumResourceSubscriptions) ?? defaults.maximumResourceSubscriptions @@ -480,8 +494,10 @@ public actor Server { /// ``serveSkills(from:listsInResources:)``. private var builtInResourceSources: [BuiltInResourceSource] = [] /// This server's observer of `taskManager`'s changes. - private var taskObserver: Int? - private var observingTasks = false + private(set) var taskObserver: Int? + private var observingGeneration: Int? + /// Suspends observer registration in lifecycle tests. + private var beforeAddingTaskObserver: (@Sendable () async -> Void)? /// The 2025-11-25 tasks this server created, by the status last sent in /// `notifications/tasks/status`, with when each task expires. private var notifiedTasks: [String: (status: TaskStatus, expiresAt: Date?)] = [:] @@ -1009,9 +1025,9 @@ public actor Server { let ending = listeners.values.compactMap { listenRequests[$0.context.requestID] } for handling in ending { await handling.value } + observingGeneration = nil if let manager = taskManager, let token = taskObserver { taskObserver = nil - observingTasks = false await manager.removeObserver(token) } notifiedTasks = [:] @@ -1440,12 +1456,20 @@ public actor Server { } /// Starts observing the task manager's changes, once. - private func observeTasks(_ manager: TaskManager) async { - guard !observingTasks else { return } - observingTasks = true - taskObserver = await manager.addObserver { [weak self] record in + func observeTasks(_ manager: TaskManager) async { + let generation = connectionGeneration + guard observingGeneration != generation else { return } + observingGeneration = generation + if let beforeAddingTaskObserver { await beforeAddingTaskObserver() } + let token = await manager.addObserver { [weak self] record in await self?.taskChanged(record) } + guard !isStopping, connection != nil, generation == connectionGeneration else { + if observingGeneration == generation { observingGeneration = nil } + await manager.removeObserver(token) + return + } + taskObserver = token } /// Records a 2025-11-25 task this server created, for status notifications. @@ -1493,7 +1517,6 @@ public actor Server { for id in ids where try await manager.lookup(id, context: context, generation: .v2) != nil { visible.append(id) } - await observeTasks(manager) return visible.isEmpty ? nil : visible } @@ -1859,6 +1882,11 @@ public actor Server { beforeRegisteringOutgoingRequest = hook } + /// Installs a test hook before the task observer is registered. + func setBeforeAddingTaskObserver(_ hook: (@Sendable () async -> Void)?) { + beforeAddingTaskObserver = hook + } + /// Whether `error` is local or the transport's, not the client's answer. private static func isConnectionFailure(_ error: MCPError) -> Bool { switch error { @@ -2266,6 +2294,15 @@ public actor Server { // MARK: - Subscriptions (2026-07-28) + private enum SubscriptionPrincipal: Equatable { + case anonymous + case named(ExactString) + + init(_ principal: String?) { + self = principal.map { .named(ExactString($0)) } ?? .anonymous + } + } + private struct Listener { let filter: SubscriptionFilter /// `filter.resourceSubscriptions`, for lookups by the same code points. @@ -2274,6 +2311,10 @@ public actor Server { let tasks: Set /// The caller, for ``notify(_:where:)``. let context: HandlerContext + /// The caller's principal, when ``Server/setSubscriptionPrincipal(_:)`` + /// set a resolver; counted against + /// ``Server/Configuration/maximumSubscriptionStreamsPerPrincipal``. + let principal: SubscriptionPrincipal? let events: AsyncStream.Continuation } @@ -2304,6 +2345,27 @@ public actor Server { subscriptionAuthorizer = authorize } + /// Identifies the caller of each `subscriptions/listen` stream. + private var subscriptionPrincipal: PrincipalResolver? + + /// Sets how the server identifies the caller of a `subscriptions/listen` + /// stream, so that ``Configuration/maximumSubscriptionStreamsPerPrincipal`` + /// limits each caller's open streams. + /// + /// Without it, only ``Configuration/maximumSubscriptionStreams`` applies, + /// and one caller can hold every stream the server allows. Behind a + /// shared transport, such as ``StatelessHTTPServerTransport``, that + /// refuses every other caller's streams. Return the authenticated + /// principal, such as the token subject; callers it returns `nil` for + /// share one allowance. Set it before the server starts: streams opened + /// earlier are not counted for a principal. + /// + /// - Parameter principal: Identifies the caller of a request, or `nil` to + /// count only the server-wide limit. + public func setSubscriptionPrincipal(_ principal: PrincipalResolver?) { + subscriptionPrincipal = principal + } + /// The most events buffered for a listen stream; older ones are dropped. /// Events are level triggers ("refetch"), so dropping duplicates is safe. private static let listenerBufferSize = 256 @@ -2381,12 +2443,22 @@ public actor Server { guard let connection else { throw MCPError.notConnected } + let principalResolver = subscriptionPrincipal + var principal: SubscriptionPrincipal? func checkCapacity() throws { + try Task.checkCancellation() + guard !isStopping, let current = self.connection, current === connection else { + throw MCPError.connectionClosed + } guard listeners.count < configuration.maximumSubscriptionStreams else { throw MCPError.invalidRequest("Too many open \(OpenSubscriptionStream.name) streams") } + guard let principal else { return } + let open = listeners.values.lazy.filter { $0.principal == principal }.count + guard open < configuration.maximumSubscriptionStreamsPerPrincipal else { + throw MCPError.invalidRequest("Too many open \(OpenSubscriptionStream.name) streams for this caller") + } } - try checkCapacity() var requested = try checked(params.notifications) if requested.taskIDs?.isEmpty == false { guard context.clientCapabilities?.declaresTasksExtension == true else { @@ -2395,6 +2467,14 @@ public actor Server { message: "Task notifications need the \(ExtensionID.tasks) extension") } } + try checkCapacity() + if let principalResolver { + guard configuration.maximumSubscriptionStreamsPerPrincipal > 0 else { + throw MCPError.invalidRequest("Too many open \(OpenSubscriptionStream.name) streams for this caller") + } + principal = SubscriptionPrincipal(await principalResolver.principal(for: context)) + try checkCapacity() + } if let authorize = subscriptionAuthorizer { requested = try checked(try await authorize(requested, context)) try checkCapacity() @@ -2402,12 +2482,12 @@ public actor Server { if let ids = requested.taskIDs, !ids.isEmpty { requested.taskIDs = try await visibleTasks(ids, context: context) try checkCapacity() + if let manager = taskManager { + await observeTasks(manager) + try checkCapacity() + } } - // The server may have stopped, or be stopping, while the authorizer - // or the task lookup ran. - guard !isStopping, let current = self.connection, current === connection else { - throw MCPError.connectionClosed - } + try checkCapacity() let filter = honored(requested) var meta = Metadata() meta.subscriptionID = context.requestID @@ -2421,7 +2501,7 @@ public actor Server { listeners[token] = Listener( filter: filter, resources: Set((filter.resourceSubscriptions ?? []).map { ExactString($0) }), tasks: Set((filter.taskIDs ?? []).map { ExactString($0) }), - context: context, events: continuation) + context: context, principal: principal, events: continuation) defer { listeners[token] = nil } let ack = Message( diff --git a/Tests/MCPTests/OpenTypeTests.swift b/Tests/MCPTests/OpenTypeTests.swift index 3509897d..2be2cae0 100644 --- a/Tests/MCPTests/OpenTypeTests.swift +++ b/Tests/MCPTests/OpenTypeTests.swift @@ -1014,6 +1014,7 @@ struct CapabilityPresetAndDescriptorTests { .cacheHints([ListPrompts.name: promptsHint, ListTools.name: updatedToolsHint]), .defaultCacheHint(promptsHint), .maximumSubscriptionStreams(50), + .maximumSubscriptionStreamsPerPrincipal(20), .maximumResourceSubscriptions(16), ] let expectedServerConfig = Server.Configuration( @@ -1022,6 +1023,7 @@ struct CapabilityPresetAndDescriptorTests { cacheHints: [ListTools.name: updatedToolsHint, ListPrompts.name: promptsHint], defaultCacheHint: promptsHint, maximumSubscriptionStreams: 50, + maximumSubscriptionStreamsPerPrincipal: 20, maximumResourceSubscriptions: 16 ) #expect(serverConfig == expectedServerConfig) diff --git a/Tests/MCPTests/SubscriptionPrincipalLimitTests.swift b/Tests/MCPTests/SubscriptionPrincipalLimitTests.swift new file mode 100644 index 00000000..cd421f33 --- /dev/null +++ b/Tests/MCPTests/SubscriptionPrincipalLimitTests.swift @@ -0,0 +1,327 @@ +import Foundation +import Testing + +@testable import MCP + +/// The principal the resolver returns; the tests switch it between streams. +private actor CurrentPrincipal { + private(set) var value: String? + init(_ value: String?) { self.value = value } + func set(_ value: String?) { self.value = value } +} + +private actor ListenResolverGate { + private(set) var waiting = 0 + private var waiters: [CheckedContinuation] = [] + + func resolve() async -> String? { + await withCheckedContinuation { continuation in + waiting += 1 + waiters.append(continuation) + } + return "alice" + } + + func open() { + for waiter in waiters { waiter.resume() } + waiters = [] + } +} + +private actor ListenCallCount { + private(set) var value = 0 + func increment() { value += 1 } +} + +@Suite("subscriptions/listen limits per principal", .timeLimit(.minutes(2))) +struct SubscriptionPrincipalLimitTests { + private func listenRequest(_ id: Int) -> Data { + Data( + #"{"jsonrpc":"2.0","id":\#(id),"method":"subscriptions/listen","params":{"notifications":{"toolsListChanged":true},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}"# + .utf8) + } + + private func makeServer(streams: Int, perPrincipal: Int) -> Server { + Server( + info: .init(name: "listen", version: "1.0"), + capabilities: .init(tools: .init(listChanged: true)), + configuration: .init( + maximumSubscriptionStreams: streams, maximumSubscriptionStreamsPerPrincipal: perPrincipal)) + } + + private func connect(_ server: Server) async throws -> Client { + let (clientTransport, serverTransport) = InMemoryTransport.makePair() + try await server.start(transport: serverTransport) + let client = Client(info: .init(name: "probe", version: "1.0")) + try await client.connect(transport: clientTransport) + return client + } + + private func expectRefused( + _ client: Client, message: String, sourceLocation: SourceLocation = #_sourceLocation + ) async { + await #expect(sourceLocation: sourceLocation) { + _ = try await client.listen(for: .init(toolsListChanged: true)) + } throws: { error in + (error as? MCPError)?.code == -32600 + && (error as? MCPError)?.data?.objectValue?["detail"] == .string(message) + } + } + + @Test("Without a principal, one caller can hold every stream the server allows") + func serverWideLimitOnly() async throws { + let server = makeServer(streams: 2, perPrincipal: 1) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + // The per-principal limit does not apply without a resolver. + _ = try await client.listen(for: .init(toolsListChanged: true)) + _ = try await client.listen(for: .init(toolsListChanged: true)) + await expectRefused(client, message: "Too many open subscriptions/listen streams") + } + + @Test("A principal at its limit is refused while other principals still get streams") + func perPrincipalLimit() async throws { + let server = makeServer(streams: 10, perPrincipal: 1) + let current = CurrentPrincipal("alice") + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await current.value }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + _ = try await client.listen(for: .init(toolsListChanged: true)) + await expectRefused(client, message: "Too many open subscriptions/listen streams for this caller") + + await current.set("bob") + _ = try await client.listen(for: .init(toolsListChanged: true)) + #expect(await server.openSubscriptionCount == 2) + } + + @Test("Principals are compared byte for byte") + func byteExactPrincipals() async throws { + let server = makeServer(streams: 10, perPrincipal: 1) + let current = CurrentPrincipal("user-K") + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await current.value }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + _ = try await client.listen(for: .init(toolsListChanged: true)) + // U+212A KELVIN SIGN is canonically equivalent to "K" but another principal. + await current.set("user-\u{212A}") + _ = try await client.listen(for: .init(toolsListChanged: true)) + #expect(await server.openSubscriptionCount == 2) + } + + @Test("Callers without a principal share one allowance") + func nilPrincipalsShare() async throws { + let server = makeServer(streams: 10, perPrincipal: 1) + await server.setSubscriptionPrincipal(PrincipalResolver { _ in nil }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + _ = try await client.listen(for: .init(toolsListChanged: true)) + await expectRefused(client, message: "Too many open subscriptions/listen streams for this caller") + } + + @Test("A full shared allowance of callers without a principal does not refuse a principal") + func nilAllowanceDoesNotBlockPrincipals() async throws { + let server = makeServer(streams: 10, perPrincipal: 1) + let current = CurrentPrincipal(nil) + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await current.value }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + _ = try await client.listen(for: .init(toolsListChanged: true)) + await current.set("alice") + _ = try await client.listen(for: .init(toolsListChanged: true)) + #expect(await server.openSubscriptionCount == 2) + } + + @Test("A closed stream frees its principal's allowance") + func closedStreamFreesAllowance() async throws { + let server = makeServer(streams: 10, perPrincipal: 1) + await server.setSubscriptionPrincipal(PrincipalResolver { _ in "alice" }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + let first = try await client.listen(for: .init(toolsListChanged: true)) + await first.cancel() + #expect(await eventually { await server.openSubscriptionCount == 0 }) + _ = try await client.listen(for: .init(toolsListChanged: true)) + #expect(await server.openSubscriptionCount == 1) + } + + @Test("The server-wide limit still applies across principals") + func serverWideLimitStillApplies() async throws { + let server = makeServer(streams: 1, perPrincipal: 5) + let current = CurrentPrincipal("alice") + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await current.value }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + _ = try await client.listen(for: .init(toolsListChanged: true)) + await current.set("bob") + await expectRefused(client, message: "Too many open subscriptions/listen streams") + } + + @Test("Untracked streams do not consume the anonymous allowance") + func untrackedStreamIsSeparate() async throws { + let server = makeServer(streams: 3, perPrincipal: 1) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + _ = try await client.listen(for: .init(toolsListChanged: true)) + await server.setSubscriptionPrincipal(PrincipalResolver { _ in nil }) + _ = try await client.listen(for: .init(toolsListChanged: true)) + await expectRefused(client, message: "Too many open subscriptions/listen streams for this caller") + await server.setSubscriptionPrincipal(nil) + _ = try await client.listen(for: .init(toolsListChanged: true)) + #expect(await server.openSubscriptionCount == 3) + } + + @Test("Non-positive principal limits refuse before resolving") + func nonPositiveLimit() async throws { + for limit in [0, -1] { + let server = makeServer(streams: 3, perPrincipal: limit) + let gate = ListenResolverGate() + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await gate.resolve() }) + let client = try await connect(server) + await expectRefused(client, message: "Too many open subscriptions/listen streams for this caller") + #expect(await gate.waiting == 0) + await client.disconnect() + await server.stop() + } + } + + @Test("Invalid filters and missing capabilities take precedence over stream limits") + func validationPrecedesCapacity() async throws { + let server = makeServer(streams: 0, perPrincipal: 0) + let gate = ListenResolverGate() + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await gate.resolve() }) + let client = try await connect(server) + defer { Task { await client.disconnect(); await server.stop() } } + + await #expect { + _ = try await client.listen(for: .init(resourceSubscriptions: [String(repeating: "x", count: 4097)])) + } throws: { error in + (error as? MCPError)?.code == -32602 + } + await #expect { + _ = try await client.listen(for: .init(taskIDs: ["task-1"])) + } throws: { error in + (error as? MCPError)?.code == -32021 + } + #expect(await gate.waiting == 0) + } + + @Test("Concurrent listens cannot exceed the principal allowance") + func concurrentResolution() async throws { + let server = makeServer(streams: 3, perPrincipal: 1) + let gate = ListenResolverGate() + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await gate.resolve() }) + let transport = MockTransport() + try await server.start(transport: transport) + defer { Task { await server.stop() } } + await transport.queue(data: listenRequest(1)) + await transport.queue(data: listenRequest(2)) + #expect(await eventually { await gate.waiting == 2 }) + await gate.open() + #expect(await eventually { await transport.sentMessages.count >= 2 }) + let sent = await transport.sentMessages + #expect(sent.filter { $0.contains(SubscriptionsAcknowledgedNotification.name) }.count == 1) + #expect(sent.filter { $0.contains("Too many open subscriptions/listen streams for this caller") }.count == 1) + #expect(await server.openSubscriptionCount == 1) + } + + @Test("Stopping while the resolver waits does not acknowledge the stream") + func stopDuringResolution() async throws { + let server = makeServer(streams: 3, perPrincipal: 1) + let gate = ListenResolverGate() + let authorized = ListenCallCount() + await server.setSubscriptionAuthorizer { filter, _ in + await authorized.increment() + return filter + } + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await gate.resolve() }) + let transport = MockTransport() + try await server.start(transport: transport) + await transport.queue(data: listenRequest(1)) + #expect(await eventually { await gate.waiting == 1 }) + await server.stop() + await gate.open() + #expect(await eventually { await server.listenRequestCount == 0 }) + #expect(!(await transport.sentMessages.contains { $0.contains(SubscriptionsAcknowledgedNotification.name) })) + #expect(await server.openSubscriptionCount == 0) + #expect(await authorized.value == 0) + } + + @Test("Cancelling while the resolver waits does not authorize or acknowledge") + func cancelDuringResolution() async throws { + let server = makeServer(streams: 3, perPrincipal: 1) + let gate = ListenResolverGate() + let authorized = ListenCallCount() + await server.setSubscriptionAuthorizer { filter, _ in + await authorized.increment() + return filter + } + await server.setSubscriptionPrincipal(PrincipalResolver { _ in await gate.resolve() }) + let transport = MockTransport() + try await server.start(transport: transport) + defer { Task { await server.stop() } } + await transport.queue(data: listenRequest(1)) + #expect(await eventually { await gate.waiting == 1 }) + await transport.queue(data: Data(#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}"#.utf8)) + await transport.queue(data: Data(#"{"jsonrpc":"2.0","id":9,"method":"ping"}"#.utf8)) + #expect(await eventually { await transport.sentMessages.contains { $0.contains("\"id\":9") } }) + await gate.open() + #expect(await eventually { await server.listenRequestCount == 0 }) + #expect(!(await transport.sentMessages.contains { $0.contains(SubscriptionsAcknowledgedNotification.name) })) + #expect(await authorized.value == 0) + } + + @Test("The resolver receives the HTTP request context") + func httpRequestContext() async throws { + let server = makeServer(streams: 3, perPrincipal: 1) + let captured = CurrentPrincipal(nil) + await server.setSubscriptionPrincipal(PrincipalResolver { context in + let token = context.httpRequest?.value(forHeader: "Authorization") + await captured.set(token) + return token + }) + let transport = StatelessHTTPServerTransport(keepAliveInterval: nil) + try await server.start(transport: transport) + defer { Task { await server.stop() } } + + let response = await transport.handleRequest( + HTTPRequest( + method: "POST", + headers: [ + "Content-Type": "application/json", "Accept": "application/json, text/event-stream", + "Authorization": "Bearer alice", + HTTPHeaderName.protocolVersion: "2026-07-28", MCPRequestHeaders.method: "subscriptions/listen", + ], + body: listenRequest(1))) + guard case .stream(let events) = response.body else { + Issue.record("expected an SSE stream, got \(response.statusCode)") + return + } + #expect(await eventually { await captured.value == "Bearer alice" }) + #expect(await eventually { await server.openSubscriptionCount == 1 }) + await server.closeSubscriptions() + for try await _ in events {} + #expect(await server.openSubscriptionCount == 0) + } + + @Test("Configuration codes the per-principal limit and defaults it when absent") + func configurationCoding() throws { + let configuration = Server.Configuration(maximumSubscriptionStreamsPerPrincipal: 7) + let data = try JSONEncoder().encode(configuration) + #expect(String(decoding: data, as: UTF8.self).contains(#""maxSubscriptionStreamsPerPrincipal":7"#)) + #expect(try JSONDecoder().decode(Server.Configuration.self, from: data) == configuration) + + let saved = try JSONDecoder().decode(Server.Configuration.self, from: Data(#"{"strict":false}"#.utf8)) + #expect(saved.maximumSubscriptionStreamsPerPrincipal == 100) + + let options: Server.Configuration = [.maximumSubscriptionStreamsPerPrincipal(3)] + #expect(options.maximumSubscriptionStreamsPerPrincipal == 3) + } +} diff --git a/Tests/MCPTests/TaskObserverLifecycleTests.swift b/Tests/MCPTests/TaskObserverLifecycleTests.swift new file mode 100644 index 00000000..ac4e45ba --- /dev/null +++ b/Tests/MCPTests/TaskObserverLifecycleTests.swift @@ -0,0 +1,73 @@ +import Testing + +@testable import MCP + +private actor TaskObserverGate { + private(set) var waiting = false + private var waiter: CheckedContinuation? + + func pause() async { + await withCheckedContinuation { continuation in + waiting = true + waiter = continuation + } + } + + func open() { + waiter?.resume() + waiter = nil + } +} + +@Suite("Task observer lifecycle", .timeLimit(.minutes(1))) +struct TaskObserverLifecycleTests { + private func makeServer(manager: TaskManager) async -> Server { + let server = Server(info: .init(name: "tasks", version: "1"), capabilities: .init()) + await server.serveTasks(with: manager) + return server + } + + @Test("Cancelling one registration keeps the shared observer for other requests") + func cancellationKeepsObserver() async throws { + let manager = TaskManager() + let server = await makeServer(manager: manager) + let gate = TaskObserverGate() + await server.setBeforeAddingTaskObserver { await gate.pause() } + try await server.start(transport: MockTransport()) + + let first = Task { await server.observeTasks(manager) } + #expect(await eventually { await gate.waiting }) + let second = Task { await server.observeTasks(manager) } + await second.value + first.cancel() + await gate.open() + await first.value + + #expect(await server.taskObserver != nil) + await server.stop() + #expect(await server.taskObserver == nil) + } + + @Test("A stopped registration cannot block an observer on the next connection") + func restartRegistersObserver() async throws { + let manager = TaskManager() + let server = await makeServer(manager: manager) + let gate = TaskObserverGate() + await server.setBeforeAddingTaskObserver { await gate.pause() } + try await server.start(transport: MockTransport()) + + let old = Task { await server.observeTasks(manager) } + #expect(await eventually { await gate.waiting }) + await server.stop() + await server.setBeforeAddingTaskObserver(nil) + try await server.start(transport: MockTransport()) + + await server.observeTasks(manager) + #expect(await server.taskObserver != nil) + await gate.open() + await old.value + #expect(await server.taskObserver != nil) + await server.stop() + #expect(await server.taskObserver == nil) + } +} diff --git a/design/threat_model.md b/design/threat_model.md index d0f224ce..85f1c704 100644 --- a/design/threat_model.md +++ b/design/threat_model.md @@ -74,6 +74,7 @@ schema cannot be resolved. Tool schemas are cached per `tools/list` handler | Messages buffered per stateless exchange | `StatelessHTTPServerTransport.maximumBufferedMessages` (1024) | | Replay store per stateful session | 1000 events and 16 MiB (`eventStoreCapacity`, `eventStoreByteCapacity`) | | Listen streams per server, URIs per stream | `maximumSubscriptionStreams` (1000), `maximumResourceSubscriptions` (256), 4096-byte URIs | +| Listen streams per principal | `maximumSubscriptionStreamsPerPrincipal` (100), with `setSubscriptionPrincipal(_:)` | | `x-mcp-header` annotations, schema depth | 64, 32 | | `tools/list` pages read to resolve a schema | 100 | | Bridged multi round-trip rounds | 10 | diff --git a/docs/protocol.md b/docs/protocol.md index 80c7df6b..156f15a9 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -669,7 +669,7 @@ await server.setSubscriptionAuthorizer { filter, context in } ``` -`Server.Configuration.maximumSubscriptionStreams` (1000) caps the open streams and `maximumResourceSubscriptions` (256) the URIs, and the task ids, of one stream; duplicates are dropped before the acknowledgement. +`Server.Configuration.maximumSubscriptionStreams` (1000) caps the open streams and `maximumResourceSubscriptions` (256) the URIs, and the task ids, of one stream; duplicates are dropped before the acknowledgement. Behind a transport that many callers share, such as `StatelessHTTPServerTransport`, one caller could hold every stream: call `setSubscriptionPrincipal(_:)` with a `PrincipalResolver` that returns the authenticated principal, and `maximumSubscriptionStreamsPerPrincipal` (100) caps each principal's open streams. Callers it returns `nil` for share one allowance. A limit of 1 can reject a replacement stream until the previous stream closes; allow at least 2 if clients overlap streams while reconnecting. ### Listening from the client @@ -715,6 +715,7 @@ Errors: | -32600 from `subscribeToResource` | The server did not honor the URI (no `resources.subscribe`). | | -32603 "ended before it was acknowledged" | The server answered the listen request without an acknowledgement. | | -32600 "Too many open subscriptions/listen streams" | The server has `maximumSubscriptionStreams` streams open. | +| -32600 "Too many open subscriptions/listen streams for this caller" | The caller's principal has `maximumSubscriptionStreamsPerPrincipal` streams open (only with `setSubscriptionPrincipal(_:)`). | | -32602 from the server | The filter names more than `maximumResourceSubscriptions` URIs, or a URI longer than 4096 bytes. | | HTTP 406 | A listen POST whose `Accept` lacks `text/event-stream`. | diff --git a/docs/server.md b/docs/server.md index fa3343a9..e42def6c 100644 --- a/docs/server.md +++ b/docs/server.md @@ -40,7 +40,7 @@ The parameters of `Server.init`: | `protocolVersions` | `Version.stateless + Version.handshake` | The revisions the server serves, newest first. `initialize` negotiates among the handshake revisions in this list. With no handshake revision, `initialize` and every handshake-era request fail with -32022. | | `cacheHints`, `defaultCacheHint` | `[:]`, `.uncached` | See [Cacheable results](#cacheable-results). | -`Server.Configuration` accepts presets (`.default`, `.strict`, `.handshake`) or an array literal of options (`.strict`, `.handshake`, `.protocolVersions(...)`, `.cacheHints(...)`, `.defaultCacheHint(...)`, `.maximumSubscriptionStreams(...)`, `.maximumResourceSubscriptions(...)`). A strict server for handshake clients only: +`Server.Configuration` accepts presets (`.default`, `.strict`, `.handshake`) or an array literal of options (`.strict`, `.handshake`, `.protocolVersions(...)`, `.cacheHints(...)`, `.defaultCacheHint(...)`, `.maximumSubscriptionStreams(...)`, `.maximumSubscriptionStreamsPerPrincipal(...)`, `.maximumResourceSubscriptions(...)`). A strict server for handshake clients only: ```swift /// A server for `initialize` clients only, that rejects requests sent diff --git a/docs/src/protocol.src.md b/docs/src/protocol.src.md index 9641cdb2..8d66308b 100644 --- a/docs/src/protocol.src.md +++ b/docs/src/protocol.src.md @@ -402,7 +402,7 @@ By default any caller may listen to any list change and resource URI. To restric %include Examples/Snippets/Protocol/Streams.swift listen-authorizer -`Server.Configuration.maximumSubscriptionStreams` (1000) caps the open streams and `maximumResourceSubscriptions` (256) the URIs, and the task ids, of one stream; duplicates are dropped before the acknowledgement. +`Server.Configuration.maximumSubscriptionStreams` (1000) caps the open streams and `maximumResourceSubscriptions` (256) the URIs, and the task ids, of one stream; duplicates are dropped before the acknowledgement. Behind a transport that many callers share, such as `StatelessHTTPServerTransport`, one caller could hold every stream: call `setSubscriptionPrincipal(_:)` with a `PrincipalResolver` that returns the authenticated principal, and `maximumSubscriptionStreamsPerPrincipal` (100) caps each principal's open streams. Callers it returns `nil` for share one allowance. A limit of 1 can reject a replacement stream until the previous stream closes; allow at least 2 if clients overlap streams while reconnecting. ### Listening from the client @@ -438,6 +438,7 @@ Errors: | -32600 from `subscribeToResource` | The server did not honor the URI (no `resources.subscribe`). | | -32603 "ended before it was acknowledged" | The server answered the listen request without an acknowledgement. | | -32600 "Too many open subscriptions/listen streams" | The server has `maximumSubscriptionStreams` streams open. | +| -32600 "Too many open subscriptions/listen streams for this caller" | The caller's principal has `maximumSubscriptionStreamsPerPrincipal` streams open (only with `setSubscriptionPrincipal(_:)`). | | -32602 from the server | The filter names more than `maximumResourceSubscriptions` URIs, or a URI longer than 4096 bytes. | | HTTP 406 | A listen POST whose `Accept` lacks `text/event-stream`. | diff --git a/docs/src/server.src.md b/docs/src/server.src.md index 7d000eb8..d33bb40b 100644 --- a/docs/src/server.src.md +++ b/docs/src/server.src.md @@ -26,7 +26,7 @@ The parameters of `Server.init`: | `protocolVersions` | `Version.stateless + Version.handshake` | The revisions the server serves, newest first. `initialize` negotiates among the handshake revisions in this list. With no handshake revision, `initialize` and every handshake-era request fail with -32022. | | `cacheHints`, `defaultCacheHint` | `[:]`, `.uncached` | See [Cacheable results](#cacheable-results). | -`Server.Configuration` accepts presets (`.default`, `.strict`, `.handshake`) or an array literal of options (`.strict`, `.handshake`, `.protocolVersions(...)`, `.cacheHints(...)`, `.defaultCacheHint(...)`, `.maximumSubscriptionStreams(...)`, `.maximumResourceSubscriptions(...)`). A strict server for handshake clients only: +`Server.Configuration` accepts presets (`.default`, `.strict`, `.handshake`) or an array literal of options (`.strict`, `.handshake`, `.protocolVersions(...)`, `.cacheHints(...)`, `.defaultCacheHint(...)`, `.maximumSubscriptionStreams(...)`, `.maximumSubscriptionStreamsPerPrincipal(...)`, `.maximumResourceSubscriptions(...)`). A strict server for handshake clients only: %include Examples/Snippets/Server/Server.swift configuration