python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

[v2] Expose request cancellation on MCPServer tool Context

Open morluto opened this issue 3 months ago • 3 comments

What happened?

With mcp==2.1.0, a tool registered through the high-level mcp.server.mcpserver.MCPServer API receives mcp.server.mcpserver.Context. That context does not expose a public cancel_requested event, although the lower-level mcp.shared.context.BaseContext does.

from mcp.server.mcpserver.context import Context as MCPServerContext
from mcp.shared.context import BaseContext

assert not hasattr(MCPServerContext, "cancel_requested")
assert hasattr(BaseContext, "cancel_requested")

The server dispatcher processes notifications/cancelled and holds the event in its per-request dispatch context, but normal tool handlers cannot cooperatively observe it through the supported high-level context API. A handler that owns cleanup-sensitive work (for example, a bounded child process) must either rely only on task interruption or traverse private session/dispatch internals to relay cancellation.

Expected behavior

Expose the current request's cancellation event on the high-level tool context (for example, await ctx.cancel_requested.wait()), or document an equivalent supported API. It should allow a handler to trigger its own cooperative cleanup without using private SDK attributes.

If this is already addressed in a later release, a version pointer would also resolve the report; the reproduction above is against 2.1.0.

Reproduction steps

  1. Install mcp==2.1.0.
  2. Register an async tool with MCPServer that accepts its injected Context.
  3. Attempt to access ctx.cancel_requested; the attribute is absent.
  4. Compare with BaseContext.cancel_requested, which is present.

SDK version

mcp==2.1.0 (Python 3.12)

Area

Server / high-level MCPServer tool context API.

AI assistance disclosure: drafted with AI assistance; the reporter is responsible for this report.

morluto avatar Aug 25 '26 16:08 morluto

Hi @morluto I reproduced this on current main. The cancellation event already exists on DispatchContext, but _make_context() doesn't pass it to ServerRequestContext, so tools can't access it.

I put together #3390 to pass through the same event and expose ctx.cancel_requested. All 168 tests in test_server.py pass. Would this approach work for the public Context API?

AI-assisted. I reviewed the changes and ran the tests myself. :))

mohitrai810 avatar Aug 25 '26 17:08 mohitrai810

The plumbing already exists: the dispatcher parses notifications/cancelled and holds the event on the per-request dispatch context, and the high-level MCPServerContext is a thin wrapper around it. Exposing it is a passthrough (cancel_requested forwarded from the dispatch context), so the API gap is real but small. One design note for the SDK: cancellation is a notification, not a response, so the handler can never be "answered"; the only correct semantics are cooperative polling or task interruption, which is why exposing an awaitable event (like BaseContext already does) is the right shape.

For a bounded child process today, the robust pattern does not depend on the cancellation event at all: run the subprocess with asyncio.wait_for plus a hard timeout, and proc.terminate() in a finally block. That guarantees cleanup even when the client never sends cancellation (which happens: clients disconnect, time out, or crash before notifying). Structure the handler as:

try:
    proc = await asyncio.create_subprocess_exec(...)
    out = await asyncio.wait_for(proc.communicate(), timeout=120)
finally:
    if proc.returncode is None:
        proc.terminate()
        await proc.wait()

If you do want cooperative cleanup on the event: since the SDK cancels the handler task on cancellation for the transports that support it, catching asyncio.CancelledError (or using anyio CancelScope) and running cleanup there works today without private traversal; the exposed cancel_requested event is the nicer long-term API so handlers can distinguish "client asked me to stop" from "server is shutting down".

One caveat worth stating in the issue: cleanup should be idempotent, because a notification can arrive while the handler is already finishing. We standardize on wait_for + finally-terminate across the connectors in our MCP server at corpusiq.io precisely so cleanup never depends on the client doing the right thing.

Ben-Home avatar Aug 25 '26 17:08 Ben-Home

Thanks for raising this. I went with the second option from your report: #3625 adds a Cancellation page to the docs rather than an event on Context.

The SDK already cancels your handler when the client gives up, so the page shows how to clean up: a finally for async def tools, and anyio.from_thread.check_cancelled() for plain def ones. It also calls out two Streamable HTTP options where the handler isn't cancelled.

I left cancel_requested out because it's only set by a notifications/cancelled message. A Streamable HTTP client on the newest protocol version doesn't send one; it cancels by closing the stream.

If that doesn't fit your child-process case, feel free to open a new issue.

AI Disclaimer

maxisbey avatar Oct 02 '26 16:10 maxisbey