Skip to content

feat: limit subscriptions/listen streams per principal - #421

Open
EhsanAzish80 wants to merge 3 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:feat/subscription-principal-limit
Open

EhsanAzish80 wants to merge 3 commits into
modelcontextprotocol:rel/1.0.0from
EhsanAzish80:feat/subscription-principal-limit

Conversation

@EhsanAzish80

Copy link
Copy Markdown
Contributor

Motivation and Context

A shared Server counts all subscriptions/listen streams against one server-wide limit. This adds an optional per-principal limit using PrincipalResolver, while keeping the global limit. The new setting defaults to nil, so existing behavior stays the same until it is configured. Callers without a principal share one allowance.

This adds public API: Server.setSubscriptionPrincipal(_:) and Server.Configuration.maximumSubscriptionStreamsPerPrincipal.

How Has This Been Tested?

  • Automated unit / integration tests
  • Tested manually
  • Tested in a real application

The tests cover the global limit, separate principal allowances, callers without a principal, exact principal matching, stream cleanup, and configuration coding. On the final commit, swift test passed (2,159 SDK tests and 134 snippet tests), DocC passed with warnings as errors, doc coverage and weave checks passed, and 2026-07-28 conformance passed.

Breaking Changes

None. The API is additive and the per-principal limit is off by default.

Types of changes

  • Bug fix
  • New feature
  • Test update
  • Refactoring
  • Breaking change
  • Documentation update
  • CI/build script update

Checklist

  • I have read the MCP Documentation
  • My code follows the repository's style guidelines
  • I have added automated tests for my change
  • New and existing tests pass locally
  • I have added appropriate error handling
  • I have added or updated documentation as needed

Additional context

This is for the 2026-07-28 subscriptions/listen path. The principal resolver should return the authenticated caller's stable identity and be set before the server starts.

AI tools helped prepare the implementation and tests. I reviewed the change and ran the checks.

@EhsanAzish80
EhsanAzish80 requested a review from a team as a code owner December 6, 2026 11:05
Add Server.setSubscriptionPrincipal(_:) and
Server.Configuration.maximumSubscriptionStreamsPerPrincipal (default 100).
With a principal resolver set, each principal may hold at most that many
subscriptions/listen streams, so one caller of a shared server (for example
behind StatelessHTTPServerTransport) cannot take every stream the server
allows. Callers without a principal share one allowance. Without a resolver,
behavior is unchanged.
@EhsanAzish80
EhsanAzish80 force-pushed the feat/subscription-principal-limit branch from 11fa8b9 to 3e741f0 Compare December 6, 2026 11:17

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR — the API shape, ExactString comparison, config coding, and docs updates fit the existing subscription code well. A couple of concurrency/state edge cases in serveListen need fixing before merge (plus a few smaller items noted inline):

  1. Cancellation / stop() across principalResolver: PrincipalResolver.principal(for:) is non-throwing, so cancellation or server.stop() while it is suspended won't abort serveListen before subscriptionAuthorizer, visibleTasks (which can re-register taskObserver after teardown), or connection.send(ack).
  2. Unresolved vs nil principals: Listener.principal: String? conflates streams opened with no resolver and streams whose resolver returned nil.

Minor doc nits (files outside this diff):

  • Sources/MCP/Server/PrincipalResolver.swift:1-2 only mentions tasks and request state; worth updating to mention subscriptions/listen stream limits (Server.setSubscriptionPrincipal(_:)).
  • docs/src/server.src.md:29 enumerates the Server.Configuration array-literal options (including .maximumSubscriptionStreams(...) and .maximumResourceSubscriptions(...)); please add .maximumSubscriptionStreamsPerPrincipal(...) and re-run swift scripts/weave.swift.

Comment thread Sources/MCP/Server/Server.swift Outdated
/// The caller's principal, when ``Server/setSubscriptionPrincipal(_:)``
/// set a resolver; counted against
/// ``Server/Configuration/maximumSubscriptionStreamsPerPrincipal``.
let principal: String?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storing let principal: String? on Listener conflates two states: "no PrincipalResolver was configured when this stream opened" and "a PrincipalResolver returned nil".

  • Line 2478 (principal: principalResolver == nil ? nil : principal) is currently a no-op because principal is already nil when principalResolver == nil.
  • Streams opened before setSubscriptionPrincipal(_:) is called will match $0.principal.map(ExactString.init) == exact when exact == nil, counting against the shared nil-principal allowance despite the doc comment ("streams opened earlier are not counted for a principal").

Using a small private enum avoids the conflation, removes isPrincipalResolved, and avoids re-wrapping each listener's string in ExactString on every capacity check:

private enum SubscriptionPrincipal: Equatable {
    case anonymous
    case named(ExactString)

    init(_ principal: String?) {
        self = principal.map { .named(ExactString($0)) } ?? .anonymous
    }
}

Then Listener.principal: SubscriptionPrincipal? is nil only when no resolver was set, and checkCapacity() compares $0.principal == principal.

Comment thread Sources/MCP/Server/Server.swift Outdated
Comment on lines +2427 to +2443
func checkCapacity() throws {
guard listeners.count < configuration.maximumSubscriptionStreams else {
throw MCPError.invalidRequest("Too many open \(OpenSubscriptionStream.name) streams")
}
guard isPrincipalResolved else { return }
let exact = principal.map(ExactString.init)
let open = listeners.values.filter { $0.principal.map(ExactString.init) == exact }.count
guard open < configuration.maximumSubscriptionStreamsPerPrincipal else {
throw MCPError.invalidRequest("Too many open \(OpenSubscriptionStream.name) streams for this caller")
}
}
try checkCapacity()
if let principalResolver {
principal = await principalResolver.principal(for: context)
isPrincipalResolved = true
try checkCapacity()
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because PrincipalResolver.principal(for:) is non-throwing (async -> String?), it cannot throw CancellationError if the request task is cancelled or server.stop() runs while it is suspended:

  • Client cancellation: a resolver doing cancellable work (e.g. try? await ...) returns nil, and serveListen continues into checkCapacity() (under the nil bucket), subscriptionAuthorizer, visibleTasks, registers in listeners, and sends notifications/subscriptions/acknowledged before for await exits and line 2491 checks cancellation.
  • server.stop(): tearDownConnection() removes taskObserver and cancels the handler task, but !isStopping / self.connection === connection is not checked until line 2462. Until then, serveListen still invokes subscriptionAuthorizer and visibleTasks, and visibleTasks calls await observeTasks(manager) (re-registering a taskObserver after teardown).

Moving try Task.checkCancellation() and the !isStopping / self.connection === connection check into checkCapacity() covers every suspension point before registration and replaces the separate guard at lines 2462–2464.

Comment thread Sources/MCP/Server/Server.swift Outdated
Comment on lines 2439 to 2445
if let principalResolver {
principal = await principalResolver.principal(for: context)
isPrincipalResolved = true
try checkCapacity()
}
var requested = try checked(params.notifications)
if requested.taskIDs?.isEmpty == false {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider running the synchronous validation (checked(params.notifications) and the declaresTasksExtension guard) before await principalResolver.principal(for: context). Right now a malformed filter (-32602) or missing tasks capability (-32021) still invokes the async resolver, and if the caller is at their stream cap it gets -32600 instead of -32602 / -32021.

Comment on lines +28 to +36
return client
}

private func expectRefused(
_ client: Client, sourceLocation: SourceLocation = #_sourceLocation
) async {
await #expect(sourceLocation: sourceLocation) {
_ = try await client.listen(for: .init(toolsListChanged: true))
} throws: { error in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both the server-wide limit and the per-principal limit return -32600, so checking only code == -32600 can't distinguish the two error paths or verify the documented error message ("Too many open subscriptions/listen streams for this caller"). Please assert on the error message as well.

Also worth adding tests for:

  • Two concurrent subscriptions/listen requests for the same principal racing across a suspended principalResolver (only one should succeed).
  • Cancelling a request / calling server.stop() while principalResolver is suspended (no ack sent, authorizer/visibleTasks not called after stop()).
  • Clearing the resolver with setSubscriptionPrincipal(nil) and verifying streams opened before setSubscriptionPrincipal don't consume the nil-principal allowance.

@EhsanAzish80

Copy link
Copy Markdown
Contributor Author

Thanks @varun06 and @jeanmatthieu . I pushed 873f827 with the lifecycle and principal-count fixes, plus tests for concurrent requests, cancellation, stop, and HTTP context. Local tests, docs, and both conformance versions pass. CI is running. I checked the burst-limit concern too: capacity is rechecked after each await, with no await between the final check and listener registration. AI helped write the tests; I ran them.

@varun06 varun06 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing all the previous review items — SubscriptionPrincipal, checkCapacity(), validation ordering, docs, and the new concurrency/lifecycle tests all look great.

One remaining concurrency bug was introduced in observeTasks(_:) in 873f827 (see inline comment on Server.swift:1457-1471). Once that's fixed, this is ready to approve.

Comment thread Sources/MCP/Server/Server.swift Outdated
Comment on lines 1457 to 1471
private func observeTasks(_ manager: TaskManager) async {
guard !observingTasks else { return }
observingTasks = true
taskObserver = await manager.addObserver { [weak self] record in
let generation = connectionGeneration
let token = await manager.addObserver { [weak self] record in
await self?.taskChanged(record)
}
guard !Task.isCancelled, !isStopping, connection != nil,
generation == connectionGeneration else {
observingTasks = false
await manager.removeObserver(token)
return
}
taskObserver = token
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two subtle concurrency issues in the new observeTasks(_:) guard:

  1. Client cancellation of one request can drop task notifications for other live requests: taskObserver is server/connection-wide state, not per-request state. If request A suspends at await manager.addObserver(...), a concurrent request B sees observingTasks == true and returns early (opening its listen stream or tracking a v1 task). If request A is then cancelled by its client, !Task.isCancelled fails, removing token and setting observingTasks = false — leaving request B with no TaskManager observer registered. Dropping !Task.isCancelled from this guard avoids this (the caller serveListen already checks Task.checkCancellation() via try checkCapacity() right after await observeTasks(manager)).
  2. stop() + restart race: tearDownConnection() (Server.swift:1026-1030) only clears observingTasks = false inside if let manager = taskManager, let token = taskObserver. If stop() runs while addObserver is still suspended (taskObserver == nil), observingTasks stays true after connectionGeneration += 1, blocking a restarted connection from adding an observer until the stale observeTasks call resumes and resets observingTasks = false (or clobbering it if cleared).

Tracking private var observingGeneration: Int? instead of observingTasks: Bool handles both cleanly:

// In tearDownConnection():
observingGeneration = nil
if let manager = taskManager, let token = taskObserver {
    taskObserver = nil
    await manager.removeObserver(token)
}

// In observeTasks(_:):
private func observeTasks(_ manager: TaskManager) async {
    let generation = connectionGeneration
    guard observingGeneration != generation else { return }
    observingGeneration = generation
    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
}

Track observer registration by connection generation. Preserve the shared observer when one request is cancelled, clear pending registration on stop, and cover both races with gated tests.
@EhsanAzish80

Copy link
Copy Markdown
Contributor Author

Thanks @varun06 . I pushed 08b7629 to keep the task observer tied to the connection, including when one request is cancelled or the server restarts. Both new race tests failed before the fix and pass now. The full suite and both conformance versions pass locally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants