Skip to content

fix: cancel in-flight requests when their session ends - #692

Merged
koic merged 1 commit into
modelcontextprotocol:mainfrom
yorzi:fix/mcp-cancellation-session-race
Nov 20, 2026
Merged

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

Conversation

@yorzi

@yorzi yorzi commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Cancels the requests still running in a Streamable HTTP session when the transport removes that session, so their handlers see server_context.cancelled? and their responses are suppressed, as for notifications/cancelled.

Motivation and Context

StreamableHTTPTransport removes a stateful session when the client terminates it with DELETE, when it passes session_idle_timeout, when its GET stream breaks without an event store, and when the transport is closed. Requests still running in that session were left running: their MCP::Cancellation was never flipped, so server_context.cancelled? stayed false, on_cancel hooks registered on server_context.cancellation never ran, and a long tool call kept working for a client that had gone. In JSON response mode its result was still written to the POST of a session that no longer existed. Only nested server-to-client waits were released, through the :session_closed that cleanup_session_unsafe pushes to them.

On main (4451525), a tool call held in flight while its session is deleted:

DELETE answered 200
handler finished, cancelled? = false
tools/call answered 200 {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"done"}],"isError":false}}

With this change:

DELETE answered 200
on_cancel fired: "Session terminated"
handler finished, cancelled? = true
tools/call answered 202 (empty body)

Each removal path now releases the session through one release_session, which closes its streams as before and then cancels its in-flight requests with ServerSession#cancel_all_incoming and the reason "Session terminated". Handlers observe it as they would notifications/cancelled, and their responses are suppressed the same way. The cancellations run once @mutex is released, as the stream closes already do: Cancellation#cancel fires its hooks synchronously, and a hook may call back into the transport, whose lock is not reentrant. The TypeScript SDK does the same in Protocol#_onclose, which aborts the handlers of every in-flight request when the transport closes.

The Cancellation docs page now describes this.

How Has This Been Tested?

New tests in test/mcp/server/transports/streamable_http_transport_test.rb hold a tool call in flight with Queue barriers rather than sleeps:

  • A DELETE cancels the request with the reason "Session terminated", and its POST is answered 202 with no body.
  • Terminating one session leaves the requests of another running, and they return their result.
  • close, the reaper, a request, a notification, a targeted notification, a broadcast, an initialize reclaiming an expired slot, and a failed GET stream write each cancel the requests of the session they remove.
  • The cancellation hooks run without the transport lock held.

All of them fail against main, and skipping the cancellation on any one removal path fails the matching case. bundle exec rake test (2704 runs, 0 failures) and bundle exec rake rubocop pass on Ruby 3.4.4.

Breaking Changes

A request still running when its session is removed no longer delivers its result. In JSON response mode its POST is answered 202 with no body, as for a request cancelled with notifications/cancelled. Over SSE the termination already closed the POST stream, so the result was lost before as well. This includes a request that outlives session_idle_timeout (30 minutes by default), since a session's idle time is counted from the start of its latest request.

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

  • The idle clock of a session runs from the start of its latest request, so a tool call longer than session_idle_timeout loses its session mid-call. With this change that call ends as cancelled instead of finishing for a session that no longer exists. Should a session with requests in flight be exempt from expiry instead? I left the expiry rule as it is.
  • A request that fetched its session just before a concurrent DELETE, and registers itself only after the cancellation, still runs to completion. Closing that window would mean marking the ServerSession terminated so that later registrations start cancelled. I kept it out of this change.

## Motivation and Context

`StreamableHTTPTransport` removes a stateful session when the client terminates it with `DELETE`, when it passes
`session_idle_timeout`, when its GET stream breaks without an event store, and when the transport is closed. Requests
still running in that session were left running: their `MCP::Cancellation` was never flipped, so
`server_context.cancelled?` stayed false, `on_cancel` hooks registered on `server_context.cancellation` never ran, and
a long tool call kept working for a client that had gone. In JSON response mode its result was still written to the
POST of a session that no longer existed. Only nested server-to-client waits were released, through the
`:session_closed` that `cleanup_session_unsafe` pushes to them.

Each removal path now releases the session through one `release_session`, which closes its streams as before and then
cancels its in-flight requests with `ServerSession#cancel_all_incoming` and the reason `"Session terminated"`. Handlers
observe it as they would `notifications/cancelled`, and their responses are suppressed the same way. The cancellations
run once `@mutex` is released, as the stream closes already do: `Cancellation#cancel` fires its hooks synchronously,
and a hook may call back into the transport, whose lock is not reentrant. The TypeScript SDK does the same in
`Protocol#_onclose`, which aborts the handlers of every in-flight request when the transport closes.

## How Has This Been Tested?

New tests in `test/mcp/server/transports/streamable_http_transport_test.rb` hold a tool call in flight with `Queue`
barriers. They check that a `DELETE` cancels the request with the reason `"Session terminated"` and its POST is
answered 202 with no body; that terminating one session leaves the requests of another running to their result; that
`close`, the reaper, a request, a notification, a targeted notification, a broadcast, an `initialize` reclaiming an
expired slot, and a failed GET stream write each cancel the requests of the session they remove; and that the hooks
run without the transport lock held. All of them fail against the previous library, and skipping the cancellation on
any one removal path fails the matching case.

## Breaking Changes

A request still running when its session is removed no longer delivers its result. In JSON response mode its POST is
answered 202 with no body, as for a request cancelled with `notifications/cancelled`. Over SSE the termination already
closed the POST stream, so the result was lost before as well. This includes a request that outlives
`session_idle_timeout` (30 minutes by default), since a session's idle time is counted from the start of its latest
request.
@koic
koic merged commit e181cca into modelcontextprotocol:main Nov 20, 2026
13 checks passed
@koic

koic commented Nov 20, 2026

Copy link
Copy Markdown
Member

To your first note under "Additional context": yes, a session with requests in flight should be exempt from idle expiry. That follows in #695, which also adjusts the tests and the docs here that expire a session with a request in flight.

koic added a commit that referenced this pull request Nov 20, 2026
## Motivation and Context

`StreamableHTTPTransport` counted a session's idle time from the start of its latest request, so a request that ran
longer than `session_idle_timeout` lost its session while the client was still waiting for the response.
Removing the session closes its streams, which dropped the response over SSE, and since #692 it also cancels
the requests in flight, so in JSON response mode the POST was answered 202 with no body instead of the result.

A session is now idle only while none of its requests is running, and its idle time counts from the later of
the last activity that touched it and the end of its last request. `ServerSession` records when a request leaves
the in-flight registry, and the transport reads that together with whether any request is left.

With that, a session that expires has no request to cancel: the cancellation #692 added applies when the client ends
the session with `DELETE`, when its GET stream breaks without an event store, and when the transport is closed.
The tests of #692 that expired a session with a request in flight now assert that it stays, and the docs say so.

## How Has This Been Tested?

`test/mcp/server/transports/streamable_http_transport_test.rb`; the test that lets the reaper, a request,
a notification, a broadcast and an `initialize` check a session whose request outlived the timeout fails
on the previous library, where the request is cancelled.

## Breaking Changes

None. A session whose request outlives `session_idle_timeout` is kept until the request ends.
koic pushed a commit that referenced this pull request Nov 21, 2026
## 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 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 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.
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