ruby-sdk/docs/_client/cancellation.md
Koichi ITO 88831b46f6 Move the Documentation From README.md to the Documentation Site
Move the documentation that had grown to 3000+ lines in README.md onto https://ruby.sdk.modelcontextprotocol.io
and slim the README down to a quick start and feature overview, following the Python SDK layout:

- Add 21 server pages as the docs/_server/ collection (overview plus transports, discovery, tools, prompts, resources,
  roots, sampling, elicitation, multi round-trip results, notifications, notification subscriptions, cancellation, progress,
  ping, completions, logging, pagination, server context, configuration, and custom methods), 8 client pages as
  the docs/_client/ collection (overview, transports, lifecycle, multi round-trip results, cancellation, ping, pagination,
  and authorization), and 3 extension pages as the docs/_extensions/ collection (overview, capability extensions, and MCP Apps,
  following the Extensions Overview recommendation that SDK documentation list the supported extensions) -
  one page per topic, ordered to match the sidebar of the 2026-07-28 specification, with the client-side APIs
  (pinging, cancelling, and paginating from MCP::Client) documented under Building Clients
- Add top-level Examples and Protocol Versions pages after Installation, linking the runnable examples in examples/
  and summarizing the supported protocol versions, the era model, and client negotiation
- Render the three sections as just-the-docs collections, which list every page beneath a plain category heading in
  the sidebar with no folding, and serve every page at an extensionless URL under /server/, /client/, and /extensions/,
  matching the sibling SDK documentation sites
- Replace docs/building-servers.md and docs/building-clients.md with redirects to the new section overview pages via
  jekyll-redirect-from, redirect the previously published /installation.html to its extensionless URL, fold their content
  that was missing from README.md into the new pages, and update the Tool argument keys reference comment in lib/mcp/server.rb to
  the relocated Tools page
- Reduce README.md to the badges, a compact feature overview in the Python SDK style, installation instructions, a stdio
  server and client quick start, and a License section, using absolute URLs for the remaining repository links
  so they resolve on rubygems.org
- Adapt formatting where GitHub rendering habits break on the site: convert the numbered "three ways to define" lists into headings,
  since kramdown restarts numbering at 1 when code blocks split list items, convert GitHub-style alerts into just-the-docs callouts
  with the SEP-2260 server-to-client association note raised to a red warning, merge the duplicated Exception Reporting
  and Configuration Block Data sections into the Configuration page, and relocate the Streamable HTTP settings that were nested under
  the Logging section into the Transports page
- Refresh the migrated content against the current implementation: correct stale claims and broken samples the README carried,
  note on each session-era feature how it relates to the modern lifecycle of MCP 2026-07-28, and point spec links at the latest revision,
  keeping deliberate 2025-11-25 pins for pages the modern revision removed
- Style the site after the Rails API documentation palette (red links and accents on neutral surfaces) with matching
  light and dark color schemes, center the sidebar and content as one block, add a Previous/Next footer pager following
  the sidebar order, open external links in a new tab, and serve the MCP logo as the favicon

Every code block and heading from the previous README was verified to have a home in the new docs pages or the slimmed README before
the reduction; a few samples were corrected rather than copied, as noted above.
2026-08-21 13:24:04 +09:00

4.4 KiB

layout title nav_order
default Cancellation 5

Cancellation

MCP::Client lets the caller cancel a request it has already issued, per the MCP notifications/cancelled utility. The recommended pattern is to pass an MCP::Cancellation token into the request method, run the request on a worker thread, and call cancellation.cancel(reason:) from another thread. The cancelling thread sends notifications/cancelled to the server, and the calling thread is woken up with MCP::CancelledError:

client = MCP::Client.new(transport: transport)
cancellation = MCP::Cancellation.new

Thread.new do
  client.call_tool(name: "slow_tool", arguments: {}, cancellation: cancellation)
rescue MCP::CancelledError
  # cleanup
end

# Later, from another thread:
cancellation.cancel(reason: "user pressed cancel")

All request methods (tools, list_tools, resources, list_resources, resource_templates, list_resource_templates, prompts, list_prompts, call_tool, read_resource, get_prompt, complete, discover, ping) accept the cancellation: keyword. Request ids are managed internally, so the token is the only thing a caller needs to cancel a request.

{: .note }

When a cancel wins the race, the SDK's worker thread that is blocked on the underlying I/O is not force-killed; it stays blocked until the transport actually returns (or the user closes the transport). This matches the server-side StreamableHTTPTransport#send_request trade-off. For Client::HTTP the leak resolves as soon as the server sends any response; for Client::Stdio you may need to call client.transport.close to free the thread if the server stops responding entirely. The cancel-dispatch thread waits for the worker's send-boundary signal (&on_sent from send_request) before issuing notifications/cancelled, so the cancel is held until the worker has at least committed to writing the request; while the worker is wedged the cancel notification is deferred along with it.

{: .note }

On a modern connection the cancel notification cannot reach the in-flight request: correlating the two is a session mechanic of the handshake lifecycle, and modern requests are sessionless single POST exchanges. The local effect is unchanged - the calling thread still raises MCP::CancelledError - but the server runs the request to completion.

Wire-order guarantees

Client::Stdio serializes the request write and any subsequent notifications/cancelled write through a single @write_mutex, so the server is guaranteed to read the request line before the cancel line.

Client::HTTP cannot offer the same wire-arrival guarantee. Faraday's synchronous post does not expose a post-write / pre-response hook, so the SDK yields just before the request POST is dispatched. After the yield, the cancel-dispatch thread issues a separate notifications/cancelled POST on its own connection, and the two POSTs may overlap on the network. The spec is satisfied either way: the sender has already issued the request and still believes it to be in-progress when issuing the cancel (MCP cancellation spec), and on the receiver side, "receivers MAY ignore a cancellation notification whose requestId is unknown" covers the case where the cancel POST happens to arrive first. The calling thread raises MCP::CancelledError regardless of network ordering.

Custom transports

Custom transports that want to support cancellation: must implement send_notification(notification:) so notifications/cancelled can be delivered. They should also accept the optional block passed to send_request(request:, &on_sent) and call it once the request bytes have been handed off to the wire (under a write-side mutex for stdio-style transports, immediately before the synchronous round-trip for HTTP-style transports). The cancel-dispatch thread waits on this signal before sending notifications/cancelled. Transports that do not invoke the block fall back to waiting for the worker thread to terminate, which preserves wire-order at the cost of delaying the cancel notification until the request has fully completed.

Server Side

How servers observe cancellation in their handlers is documented on the server Cancellation page.