fix(server): expose request cancellation on MCPServer context

Closed
MO
3mo ago
+37-1

Fixes #3389.

Problem

The high-level MCPServer Context does not expose the cancellation event available in the underlying dispatch context. Tool handlers therefore cannot observe cancellation or perform cooperative cleanup through the public API.

Changes

  • Add cancel_requested to ServerRequestContext.
  • Forward the dispatcher's existing cancellation event when constructing the request context.
  • Expose cancel_requested on the high-level Context.
  • Preserve the existing error when context is accessed outside a request.
  • Add regression tests for cancellation access and access outside a request.

Testing

  • All 168 tests passed:
    python -m pytest tests/server/mcpserver/test_server.py -v --inline-snapshot=disable
  • Ruff linting passed.
  • Ruff formatting checks passed.

AI assistance disclosure: I used AI to help investigate and implement this change. I reviewed the implementation and verified all tests myself.