Skip to content

[Server] Handle notifications/cancelled on the handshake era - #734

Open
ump45nose wants to merge 3 commits into
modelcontextprotocol:mainfrom
ump45nose:contrib/0f7930183833
Open

ump45nose wants to merge 3 commits into
modelcontextprotocol:mainfrom
ump45nose:contrib/0f7930183833

Conversation

@ump45nose

@ump45nose ump45nose commented Nov 10, 2026 •

Copy link
Copy Markdown

Summary

Handle notifications/cancelled on handshake-era servers by dropping the suspended handler fiber (for example one waiting on elicitation or sampling) and not answering the cancelled request. Unknown, already-finished and un-cancellable ids are ignored. 2026-07-28 stdio cancellation of subscriptions/listen is unchanged.

TransportInterface::setCancellationChecker() is new: transports that extend BaseTransport get it automatically; a custom implementor must add the setter and drop a cancelled fiber from the polling loop without sending a response.

On review feedback, the bookkeeping was reworked so a shared Protocol cannot mix up sessions or workers:

  • A suspended fiber and the cached cancellation are matched by session id and request id. Two sessions may send the same id, and a cancellation authenticated for one must not drop the other's handler.
  • A cancellation is cached in this process only for a fiber this process owns. Another worker's fiber is dropped through _mcp.cancelled_requests in the session instead.
  • The reload, cleanup and save of a cancelled request happen under the session lock. The handler is still dropped when the lock is busy (a cancelled request must not answer) and the session markers are cleared when a later request of that session reuses the id.
  • A resumed request clears _mcp.in_flight_requests before its locked save, so storage does not keep an answered request in flight.
  • The fiber keeps its identity and cancellation state until the transport has checked whether a response may be sent, so a cancellation recorded while the resumed handler finishes still suppresses that response.

Fixes #732

Verification

Head 7b52dafee (includes a merge of main at 3d2e831).

  • vendor/bin/phpunit tests/Unit/Server — 1766 tests, 5101 assertions, 1 failure: StdioTransportTest::testIdleInputWakesOnArrival, a transport latency budget (45 ms) that this machine misses at 56–90 ms. tests/Unit/Server/Transport/StdioTransport.php is untouched by this change; the test also fails intermittently on reruns.
  • Focused: ProtocolTest + ProtocolSessionLockTest + StdioSuspendedFibersTest (131 tests) and StreamableHttpTransportTest (45 tests) all pass.
  • make cs and make phpstan are clean; make deptrac reports no violations.
  • Four new ProtocolTest cases cover the rework: a cancellation in one session leaves another session's request with the same id alone, a foreign cancellation does not cancel a later request that reuses the id, a resumed request leaves no in-flight mark in storage, and a cancellation recorded during the resume suppresses the response. The first, third and fourth fail on the previous head.
  • tests/Integration cannot run here: the fixture servers are spawned with a path containing spaces, so they exit with code 126 in this workspace. Unit, static analysis and style cover this diff; CI runs the integration, interop and conformance suites.

AI assistance disclosure: AI was used to discover this opportunity and draft the change or text. The submission was checked against the prepared artifact and recorded verification evidence.

Drop a suspended handshake-era handler fiber when the client sends
notifications/cancelled, and do not answer the cancelled request.
Unknown, already-finished and un-cancellable ids are ignored.

Copilot AI 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.

🟡 Changes recommended

Unresolved cancellation flaws can bypass session isolation and overwrite concurrent workers’ session updates.

5 open issues
What changed in this PR

Adds handshake-era request cancellation to the PHP SDK server, addressing #732 by dropping suspended handlers without sending a response.

Changes:

  • Tracks in-flight requests and cancellation state in the protocol.
  • Adds a transport cancellation callback and checks in stdio and HTTP polling loops.
  • Adds regression tests and documents the transport interface breaking change.
File Description
tests/​Unit/​Server/​Transport/​StreamableHttpTransportTest.php Tests cancellation without an SSE response.
tests/​Unit/​Server/​Transport/​StdioSuspendedFibersTest.php Tests cancelled elicitation and unknown cancellation IDs.
tests/​Unit/​Server/​ProtocolTest.php Covers cancellation handling, validation and typed request IDs.
tests/​Unit/​Fixtures/​PollingLoopTransport.php Exposes cancellation-aware polling for protocol tests.
src/​Server/​Transport/​TransportInterface.php Declares the cancellation checker contract.
src/​Server/​Transport/​StreamableHttpTransport.php Checks cancellation during SSE processing.
src/​Server/​Transport/​StdioTransport.php Drops cancelled fibers during polling.
src/​Server/​Transport/​ManagesTransportCallbacks.php Stores and registers the cancellation checker.
src/​Server/​Transport/​BaseTransport.php Provides shared cancellation callback invocation.
src/​Server/​Protocol.php Tracks suspended requests and processes cancellation notifications.
CHANGELOG.md Records cancellation support and the interface breaking change.

Review effort: Balanced

Comment thread src/Server/Protocol.php Outdated
Comment on lines +670 to +671
$fiber = $this->fiberForIncomingRequest($requestId);
if (null === $fiber && !$this->hasInFlightIncomingRequest($session, $key)) {
Comment thread src/Server/Protocol.php Outdated
Comment on lines +724 to +726
if (!$session instanceof EphemeralSessionInterface) {
try {
$session->save();
Comment thread src/Server/Protocol.php Outdated
Comment on lines +519 to +520
$saveResumedSession($session);
$clearIncomingRequest($request->getId(), $session);
Comment thread src/Server/Protocol.php Outdated

$this->logger->info('Cancelled an in-flight request.', ['request_id' => $requestId]);

$this->cancelledRequestKeys[$key] = true;
Comment thread src/Server/Protocol.php Outdated
Comment on lines +789 to +791
foreach ($this->incomingRequestIds as $fiber => $id) {
if ($id === $requestId) {
unset($this->incomingRequestIds[$fiber]);
@chr-hertel chr-hertel added the Server Issues & PRs related to the Server component label Nov 16, 2026
…ion lock

A shared Protocol serves several sessions that may send the same request id, and
another worker may hold the suspended fiber. The cancellation bookkeeping used
the request id alone and reloaded the session outside its lock, so a token of
this change could drop another session's call or overwrite a concurrent save.

- Match suspended fibers and the cached cancellation by session id *and* request
  id, so a cancellation authenticated for one session cannot drop another's
  handler.
- Cache a cancellation in this process only for a fiber it owns; another
  worker's fiber is dropped through the marker stored in the session.
- Reload and clean up a cancelled request under the session lock. The handler is
  dropped even when the lock is busy, and the markers are cleared when a later
  request of that session reuses the id.
- Clear the in-flight marker before the resumed request's locked save, so
  storage does not keep a request that was already answered.
- Keep the fiber's identity and cancellation state until its transport checked
  whether a response may be sent, so a cancellation recorded while the resumed
  handler finishes still suppresses that response.
@ump45nose

Copy link
Copy Markdown
Author

Pushed 23e5186 (+ merge of main), which addresses the five findings from the automated review on 9e4546d:

  1. Session isolation (Protocol.php:671). Suspended fibers are now keyed by (session id, request id) in incomingRequestIds, and cancelledRequestKeys is a per-session map. A cancellation authenticated for session B can no longer find or drop session A's fiber that reused the id; isHandlerCancelled() also refuses a fiber whose owner session differs from the session the checker was called for.
  2. Locked cleanup (Protocol.php:726). Reading the cancellation marker and the cleanup (drop the awaited peer request, clear markers, save) now happen under the session lock (tryAcquireSessionLockForPoll() / releaseSessionLock()), so the reload cannot race another worker's save. When the lock is busy the handler is still dropped (a cancelled request must never answer) and the markers are cleared on id reuse.
  3. In-flight marker (Protocol.php:520). saveResumedSession() now takes the request id and forgets _mcp.in_flight_requests.<key> inside the locked section, before save(), so storage no longer keeps an answered request in flight.
  4. Foreign fibers (Protocol.php:681). cancelIncomingRequest() caches the cancellation locally only when it finds a fiber of this process; otherwise just the session marker is written. markIncomingRequestInFlight() also clears a cached cancellation for the reused id.
  5. Identity until the transport checks (Protocol.php:791). The resumed handler no longer calls clearIncomingRequest(); the fiber's mapping and cancellation state stay until isHandlerCancelled() consumes them, so a cancellation recorded while the resumed handler finishes still suppresses the response.

New ProtocolTest cases: testCancellationInAnotherSessionDoesNotDropAHandlerThatReusesTheId, testForeignCancellationIsNotCachedForAReusedRequestId, testResumedRequestClearsItsInFlightMarkFromTheSession, testCancellationDuringResumeSuppressesTheResponse. The 1st, 3rd and 4th fail on the previous head.

Verification is in the PR body: tests/Unit/Server 1766 tests / 5101 assertions with one pre-existing timing failure (StdioTransportTest::testIdleInputWakesOnArrival, 45 ms budget missed at 56–90 ms on this machine, untouched by the diff), make cs/make phpstan/make deptrac clean. tests/Integration cannot run in a workspace whose path contains spaces (fixture servers exit 126), so that suite is left to CI.

This branch has not been deployed

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

Labels

Server Issues & PRs related to the Server component

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Server] Handle notifications/cancelled on the handshake era

3 participants