Skip to content

fix: cancel a request that reaches a session as it ends - #698

Merged
koic merged 1 commit into
modelcontextprotocol:mainfrom
yorzi:fix/mcp-session-teardown-registration-race
Nov 21, 2026
Merged

koic merged 1 commit into
modelcontextprotocol:mainfrom
yorzi:fix/mcp-session-teardown-registration-race

Conversation

@yorzi

@yorzi yorzi commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Follows #692: a request the transport handed to a session just before the session ended is no longer run uncancelled.

Motivation and Context

Since #692, ending a stateful Streamable HTTP session cancels the requests in flight in it. A request the transport has already handed to the session, but that Server has not registered yet, is missed: ServerSession#cancel_all_incoming cancels only what the registry holds (lib/mcp/server_session.rb:112), and the late request then registers with a fresh token (lib/mcp/server.rb:807), runs its handler with server_context.cancelled? false, and delivers its result to the terminated session.

Over SSE the window spans from handle_regular_request returning the response to the Rack server calling its body, which is where the request is dispatched (lib/mcp/server/transports/streamable_http_transport.rb:2537). A DELETE from another connection in that gap removes the session, the body finds no session to claim a stream in (:2518), and still runs the tool and writes its result. In JSON response mode the window is between the transport looking the session up (:2481) and the registration.

On main (c2ce3c1), through the Rack interface, with a DELETE between the tools/call response and its body:

tools/call answered 200, body not yet run
DELETE answered 200
tool ran, cancelled? = false
SSE body wrote: "data: {\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"done\"}],\"isError\":false}}\n\n"

With this change:

tools/call answered 200, body not yet run
DELETE answered 200
SSE body wrote: ""

cancel_all_incoming now also closes the registry under its lock: a request registered afterwards gets a token already cancelled with the same reason, which is not tracked. Server#handle_request does not start the handler of a request whose token is cancelled before it begins, records the cancellation in the instrumentation as the result path does, and sends no response, so a JSON-mode POST is answered 202 as for any cancelled request. Lock order is unchanged: only the registry lock is taken, and the cancellations still run outside it, so on_cancel hooks can call back into the transport as before.

The Cancellation docs page now says this.

How Has This Been Tested?

New tests in test/mcp/server/transports/streamable_http_transport_test.rb:

  • An SSE request whose session is terminated with DELETE between the response and its body does not run its tool and writes nothing.
  • A JSON-mode request held with a Queue barrier after the transport looked its session up, and before it registered, does not run its tool and is answered 202 when the session is terminated in that gap.

New tests in test/mcp/server_cancellation_test.rb:

  • A registration after cancel_all_incoming returns a token already cancelled with its reason, and it is not tracked.
  • Such a request does not run its handler, gets no response, and records the cancellation in the instrumentation.
  • cancel_all_incoming on one session leaves registration on another open.

The request tests fail against main. Dropping the registry closure, the cancellation of the late token, its reason, the untracked registration, the early return in Server, or its instrumentation each fails a test. On Ruby 3.4.4: bundle exec rake test (2719 runs, 0 failures, 3 skips), bundle exec rake rubocop (no offenses), and bundle exec rake conformance:test (baseline check passed for server and client).

Breaking Changes

None. A request that reaches a session as the transport ends it is not run. It previously ran uncancelled.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update

Checklist

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

Additional context

This merges cleanly with #695 and #697, and the full suite passes on main with all three applied. With #695 a session no longer expires while a request is in flight, but the window here is before the request is in flight, so it is not closed by it.

A request that reuses an in-flight id after the session ended now gets no response instead of Invalid Request, since the session has no client left to answer. Notifications on a terminated session are not tracked in the registry and are not affected. Only Ruby 3.4.4 was run locally; CI covers the rest of the matrix.

## Motivation and Context

Since modelcontextprotocol#692, ending a stateful Streamable HTTP session cancels the requests in flight in it. A request the transport has
already handed to the session but that `Server` has not yet registered is missed: `ServerSession#cancel_all_incoming`
cancels only what the registry holds, and the late request then registers with a fresh token, runs its handler with
`server_context.cancelled?` false, and delivers its result to the terminated session.

Over SSE the window spans from `handle_regular_request` returning the response to the Rack server calling its body,
which is where the request is dispatched. A `DELETE` from another connection in that gap removes the session, yet the
body still runs the tool and writes its result. In JSON response mode the window is between the transport looking the
session up and `Server#handle_request` registering the request.

`cancel_all_incoming` now also closes the registry under its lock: a request registered afterwards gets a token already
cancelled with the same reason, which is not tracked. `Server#handle_request` does not start the handler of a request
whose token is cancelled before it begins, records the cancellation in the instrumentation, and sends no response. Lock
order is unchanged: only the registry lock is taken, and the cancellations still run outside it.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb`: an SSE request whose session is terminated
with `DELETE` between the response and its body does not run its tool and writes nothing; a JSON-mode request held, with
a `Queue` barrier, after the transport looked its session up and before it registered, does not run its tool and is
answered 202 when the session is terminated in that gap. New tests in `test/mcp/server_cancellation_test.rb` check that
a registration after `cancel_all_incoming` returns a token already cancelled with its reason and not tracked, that such
a request does not run its handler, gets no response and records the cancellation, and that another session is not
affected.

The request tests fail against the previous library. Dropping the registry closure, the cancellation of the late token,
its reason, the untracked registration, the early return in `Server`, or its instrumentation each fails a test.

## Breaking Changes

None. A request that reaches a session as the transport ends it is not run. It previously ran uncancelled.
@koic
koic merged commit 7f9883b into modelcontextprotocol:main Nov 21, 2026
13 checks passed
koic pushed a commit that referenced this pull request Nov 22, 2026
## Motivation and Context

A stateful Streamable HTTP request checks its session in one `@mutex` section (`validate_and_touch_session`) and looks
the session's `ServerSession` up in another. A `DELETE` from another connection, or `close`, can remove the session
between the two. The lookup then finds nothing, and `dispatch_handle_json` falls back to the shared `Server`: the tool
runs with no session, so the termination that cancels the session's requests (#692, #698) never reaches it,
`server_context.cancelled?` stays false, and the request is answered 200 with its result in both response modes.
Notifications have the same split between `session_active?` and the lookup in `dispatch_notification`, so a custom
notification handler runs against the shared `Server` and the POST is answered 202.

A request or notification that names a session and finds none at the lookup is now answered 404 Session not found, the
answer it gets when the session is already gone at the check, and is not dispatched. Stateless requests and requests
sent without a session id are unchanged.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` hold a request with a `Queue` barrier right
after its session check passes, terminate the session with `DELETE`, then release it: a `tools/call` in SSE mode and in
JSON response mode is answered 404 and does not run its tool, and a custom notification is answered 404 and does not
run its handler. All three fail against the previous library. Dropping the request guard, the notification guard, or
the caller's use of the notification result each fails a test.

## Breaking Changes

None. A request that loses its session while being admitted is answered 404 instead of running without the session.

Fixes #704.
koic pushed a commit that referenced this pull request Nov 23, 2026
## Motivation and Context

When the Streamable HTTP transport removes a session, `cleanup_session_unsafe` wakes the threads waiting on the
session's server-to-client requests with `:session_closed`, and `release_session` then closes the session's GET and
POST streams before it cancels the session's requests. A close can block for up to `stream_write_timeout:` (10 seconds
by default) on a stalled peer, and the cancellation waits behind it. Two documented guarantees of the Cancellation page
fail meanwhile:

- A request that reaches the session as it ends (#698) is admitted and run: its tool runs with
  `server_context.cancelled?` false, and over SSE its result is written to its POST stream after the `DELETE`.
- A request waiting on a nested server-to-client request is woken with `:session_closed` before its own token is
  cancelled: the nested call raises "SSE session closed while waiting", the handler sees `cancelled?` false, and the
  request is recorded as an internal error instead of a cancellation. The wake-up runs first even without a stalled
  stream, so this outcome depends on thread scheduling.

`release_session` now cancels the session's requests first, then wakes the remaining waits with `:session_closed`, then
closes the streams. `cleanup_session_unsafe` collects the waits under the lock instead of waking them; no wait is added
for a session once it is removed. A nested request is now woken through its parent's cancellation hook, so it raises
`MCP::CancelledError` as it does for `notifications/cancelled`. Cancellations still run outside `@mutex`.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb`, with a GET stream whose close blocks until
released: an SSE request whose body runs while the `DELETE` is held up closing that stream does not run its tool and
writes nothing; a request waiting on an elicitation when its session is terminated sees `MCP::CancelledError` with
`cancelled?` true and is recorded as cancelled with the reason "Session terminated". Both fail against the previous
library. Closing the streams before cancelling fails both, waking the waits before cancelling fails the second, and
dropping the wake-up hangs the existing "send_request unblocks when session is cleaned up" test.

## Breaking Changes

None. `on_cancel` hooks of a terminated session's requests now run before its streams are closed rather than after.

Fixes #708.
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