Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Sources/MCP/Server/PrincipalResolver.swift
Original file line number Diff line number Diff line change
@@ -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?

Expand Down
13 changes: 13 additions & 0 deletions Sources/MCP/Server/Server+Presets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ extension Server.Configuration: ExpressibleByArrayLiteral {
case cacheHints([String: CacheHint])
case defaultCacheHint(CacheHint)
case maximumSubscriptionStreams(Int)
case maximumSubscriptionStreamsPerPrincipal(Int)
case maximumResourceSubscriptions(Int)
}

Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -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
}
Expand Down
110 changes: 95 additions & 15 deletions Sources/MCP/Server/Server.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -63,6 +69,7 @@ public actor Server {
self.cacheHints = [:]
self.defaultCacheHint = .uncached
self.maximumSubscriptionStreams = 1000
self.maximumSubscriptionStreamsPerPrincipal = 100
self.maximumResourceSubscriptions = 256
}

Expand All @@ -74,27 +81,31 @@ public actor Server {
/// - cacheHints: See ``cacheHints``.
/// - defaultCacheHint: See ``defaultCacheHint``.
/// - maximumSubscriptionStreams: See ``maximumSubscriptionStreams``.
/// - maximumSubscriptionStreamsPerPrincipal: See ``maximumSubscriptionStreamsPerPrincipal``.
/// - maximumResourceSubscriptions: See ``maximumResourceSubscriptions``.
public init(
isStrict: Bool = false,
protocolVersions: [String] = Version.stateless + Version.handshake,
cacheHints: [String: CacheHint] = [:],
defaultCacheHint: CacheHint = .uncached,
maximumSubscriptionStreams: Int = 1000,
maximumSubscriptionStreamsPerPrincipal: Int = 100,
maximumResourceSubscriptions: Int = 256
) {
self.isStrict = isStrict
self.protocolVersions = protocolVersions
self.cacheHints = cacheHints
self.defaultCacheHint = defaultCacheHint
self.maximumSubscriptionStreams = maximumSubscriptionStreams
self.maximumSubscriptionStreamsPerPrincipal = maximumSubscriptionStreamsPerPrincipal
self.maximumResourceSubscriptions = maximumResourceSubscriptions
}

private enum CodingKeys: String, CodingKey {
case isStrict = "strict"
case protocolVersions, cacheHints, defaultCacheHint
case maximumSubscriptionStreams = "maxSubscriptionStreams"
case maximumSubscriptionStreamsPerPrincipal = "maxSubscriptionStreamsPerPrincipal"
case maximumResourceSubscriptions = "maxResourceSubscriptions"
}

Expand All @@ -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
Expand Down Expand Up @@ -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?)] = [:]
Expand Down Expand Up @@ -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 = [:]
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand All @@ -2274,6 +2311,10 @@ public actor Server {
let tasks: Set<ExactString>
/// 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<SubscriptionEvent>.Continuation
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -2395,19 +2467,27 @@ 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()
}
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
Expand All @@ -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<SubscriptionsAcknowledgedNotification>(
Expand Down
2 changes: 2 additions & 0 deletions Tests/MCPTests/OpenTypeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -1022,6 +1023,7 @@ struct CapabilityPresetAndDescriptorTests {
cacheHints: [ListTools.name: updatedToolsHint, ListPrompts.name: promptsHint],
defaultCacheHint: promptsHint,
maximumSubscriptionStreams: 50,
maximumSubscriptionStreamsPerPrincipal: 20,
maximumResourceSubscriptions: 16
)
#expect(serverConfig == expectedServerConfig)
Expand Down
Loading
Loading