Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ This is the official Ruby SDK for the Model Context Protocol (MCP), implementing
- `rake test` - Run all tests
- `rake rubocop` - Run linter
- `rake` - Run tests and linting (default task)
- `bundle exec rake conformance` - Run the MCP conformance suite (see conformance/README.md)
- `ruby -I lib -I test test/path/to/specific_test.rb` - Run single test file
- `gem build mcp.gemspec` - Build the gem

Expand All @@ -34,6 +35,14 @@ This is the official Ruby SDK for the Model Context Protocol (MCP), implementing
- Keep dependencies minimal
- Use lowercase HTTP response header names (e.g. `mcp-session-id`); the Rack 3 SPEC requires this, and the MCP spec's `Mcp-Session-Id` casing is prose convention only

## Documentation

- User-facing documentation lives in `docs/`, one page per topic, published at https://ruby.sdk.modelcontextprotocol.io (deploys only when a release is published)
- Pages live in the `docs/_server/`, `docs/_client/`, and `docs/_extensions/` collections
- Keep README.md slim: quick start and pointers only; document features on the relevant docs page
- Internal links are absolute and extensionless (e.g. `/server/tools/`); front matter is followed by a blank line before the h1
- Callout tiers: `.note` (supplementary), `.important` (spec constraints), `.warning` (deprecated features)

## Commit message conventions

- Use conventional commit format when possible
Expand Down
3,050 changes: 50 additions & 3,000 deletions README.md

Large diffs are not rendered by default.

260 changes: 260 additions & 0 deletions docs/_client/authorization.md

Large diffs are not rendered by default.

71 changes: 71 additions & 0 deletions docs/_client/cancellation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
---
layout: default
title: Cancellation
nav_order: 5
---

# Cancellation

`MCP::Client` lets the caller cancel a request it has already issued,
per the [MCP `notifications/cancelled` utility](https://modelcontextprotocol.io/specification/latest/basic/patterns/cancellation).
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`:

```ruby
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](/client/lifecycle/) 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](https://modelcontextprotocol.io/specification/latest/basic/patterns/cancellation)),
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](/server/cancellation/) page.
46 changes: 46 additions & 0 deletions docs/_client/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
layout: default
title: Overview
nav_order: 1
permalink: /client/
redirect_from:
- /building-clients.html
- /building-clients/
---

# Building an MCP Client

The `MCP::Client` class provides an interface for interacting with MCP servers.

This class supports:

- Lifecycle negotiation and connection via `MCP::Client#connect`, adopting the modern lifecycle
when the server serves it; see [Lifecycle](/client/lifecycle/)
- Server discovery via the `server/discover` method (`MCP::Client#discover`); see [Explicit Discovery](/client/lifecycle/#explicit-discovery)
- Liveness check via the `ping` method (`MCP::Client#ping`)
- Tool listing via the `tools/list` method (`MCP::Client#tools`)
- Tool invocation via the `tools/call` method (`MCP::Client#call_tool`)
- Resource listing via the `resources/list` method (`MCP::Client#resources`)
- Resource template listing via the `resources/templates/list` method (`MCP::Client#resource_templates`)
- Resource reading via the `resources/read` method (`MCP::Client#read_resource`)
- Prompt listing via the `prompts/list` method (`MCP::Client#prompts`)
- Prompt retrieval via the `prompts/get` method (`MCP::Client#get_prompt`)
- Completion requests via the `completion/complete` method (`MCP::Client#complete`); see [Completions](/server/completions/)
- Automatic driving of multi round-trip `input_required` results once `on_elicitation`, `on_sampling`,
or `on_roots` handlers are registered; see [Multi-Round-Trip Results](/client/multi-round-trip-results/)
- Cancellation of in-flight requests via the `cancellation:` keyword; see [Cancellation](/client/cancellation/)
- Cursor-based page iteration on the `list_*` methods and whole-collection fetching with
the `max_pages` guard; see [Pagination](/client/pagination/)
- Automatic JSON-RPC 2.0 message formatting
- UUID request ID generation

Clients are initialized with a [transport layer](/client/transports/) instance that handles the low-level communication mechanics.
Authorization is handled by the transport layer; see [Authorization](/client/authorization/).

## Tool Objects

The client provides a wrapper class for tools returned by the server:

- `MCP::Client::Tool` - Represents a single tool with its metadata

This class provides easy access to tool properties like name, description, input schema, and output schema.
78 changes: 78 additions & 0 deletions docs/_client/lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
layout: default
title: Lifecycle
nav_order: 3
---

# Lifecycle

Before sending requests, a client establishes its lifecycle with the server: the classic `initialize` handshake
on legacy protocol versions, or the sessionless modern lifecycle of MCP 2026-07-28.
This page covers `MCP::Client#connect` and how it negotiates between the two.

## Handshake

Call `MCP::Client#connect` to perform the MCP [initialization handshake](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#initialization) before sending any other requests. The client sends an `initialize` request through the transport, followed by the required `notifications/initialized` notification, and caches the server's `InitializeResult` (protocol version, capabilities, server info, instructions):

```ruby
client.connect
# => { "protocolVersion" => "2025-11-25", "capabilities" => {...}, "serverInfo" => {...} }

client.connected? # => true
client.server_info # => cached InitializeResult
```

`connect` accepts optional `client_info:`, `protocol_version:`, and `capabilities:` keyword arguments. It is idempotent: a second call returns the cached result without contacting the server. After `close`, state is cleared and `connect` will handshake again.

This applies to both the Stdio and HTTP transports described on the [Transports](/client/transports/) page.

By default `connect` [negotiates the lifecycle](#lifecycle-negotiation) first and performs this handshake
only when the server does not serve the modern lifecycle, or when `mode: :legacy` or a legacy `protocol_version:` forces it.

## Lifecycle Negotiation

`MCP::Client#connect` selects the protocol lifecycle automatically by default: on the bundled
`MCP::Client::HTTP` and `MCP::Client::Stdio` transports it probes [`server/discover`](/server/discovery/) first and adopts
the stateless modern lifecycle (MCP 2026-07-28, SEP-2575) when the server serves it, falling back to
the classic `initialize` handshake otherwise. Custom transports whose `connect` does not declare
a `mode:` keyword always receive the classic call shape, unchanged.

```ruby
client.connect # negotiate automatically (default)
client.connect(mode: :modern) # require the modern lifecycle; fails on legacy-only servers
client.connect(mode: :legacy) # force the classic initialize handshake
client.connect(protocol_version: "2025-11-25") # an explicit legacy version pins the handshake, no probe
```

Prefer `mode: :legacy` for spawn-per-invocation CLI tools (the probe adds a round trip per process)
and when using server-initiated requests (`on_elicitation` / `on_sampling`), which exist only on
the legacy lifecycle.

Because the raw `connect` return value and `MCP::Client#server_info` mirror the wire result,
their shape depends on the negotiated lifecycle: `InitializeResult` (`protocolVersion`,
top-level `serverInfo`) on legacy, `DiscoverResult` (`supportedVersions`, `ttlMs`/`cacheScope`)
on modern. Code that should work against both lifecycles can use the era-independent readers instead:

```ruby
client.protocol_version # negotiated or adopted version, either lifecycle
client.server_capabilities # capabilities Hash, either lifecycle
client.instructions # instructions text, either lifecycle
client.server_implementation # server name/version; nil when a modern server does not identify itself
```

Troubleshooting: if `server_info["protocolVersion"]` starts returning `nil` after a server you connect to was upgraded,
the server now serves the modern lifecycle and the automatic negotiation adopted it.
Pass `mode: :legacy` for an immediate return to the previous behavior, or switch to the readers above for a permanent fix.

## Explicit Discovery

`MCP::Client#discover` sends `server/discover` directly: sessionless capability discovery
that works before (or instead of) `connect`. It returns an `MCP::Client::DiscoverResult` struct
exposing `supported_versions`, `capabilities`, `server_info`, `instructions`, and
the `ttl_ms` / `cache_scope` cache hints; see the server [Discovery](/server/discovery/) page
for the wire shapes.

```ruby
result = client.discover
result.supported_versions # => ["2026-07-28"]
```
60 changes: 60 additions & 0 deletions docs/_client/multi-round-trip-results.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
---
layout: default
title: Multi-Round-Trip Results
nav_order: 4
---

# Multi-Round-Trip Results

MCP 2026-07-28 replaces in-flight server-to-client requests with Multi Round-Trip Requests (SEP-2322): instead of issuing `sampling/createMessage`, `roots/list`,
or `elicitation/create` while a request is being processed, a server may answer with a result whose `resultType` is `"input_required"`, carrying an `inputRequests` map
and an opaque `requestState`; the client fulfills the requests and re-issues the original request with `inputResponses` and the echoed `requestState`.

## Automatic Driving

The Ruby client drives such results automatically: once a handler is registered through `on_elicitation`, `on_sampling`, or `on_roots`, the `call_tool`, `get_prompt`,
and `read_resource` methods fulfill the embedded requests and re-issue the original request with `inputResponses` plus the echoed `requestState`, capped at `input_required_max_rounds`
(10 by default, matching the TypeScript and Python SDKs).

```ruby
client = MCP::Client.new(transport: transport)
client.connect(capabilities: { elicitation: { form: {} } })

client.on_elicitation do |params|
{ action: "accept", content: { name: "Alice" } }
end

# The input_required round trips are driven automatically; this returns the final result.
response = client.call_tool(name: "collect_name", arguments: {})
```

Declare the capabilities matching the registered handlers on `connect`: a server embeds only the request kinds
the client declared.

## Manual Driving

Without a matching handler, `MCP::Client::InputRequiredError` is raised instead of returning the result as if it were final;
the error exposes `input_requests`, `request_state`, and the raw `result` for manual driving via the `input_responses:` and `request_state:` keywords:

```ruby
begin
client.call_tool(name: "collect_name", arguments: {})
rescue MCP::Client::InputRequiredError => error
answers = error.input_requests.transform_values { |request| answer_for(request) }

client.call_tool(
name: "collect_name",
arguments: {},
input_responses: answers,
request_state: error.request_state,
)
end
```

`MCP::ResultType::COMPLETE` and `MCP::ResultType::INPUT_REQUIRED` are provided for forward compatibility.
Servers on legacy protocol versions never send `resultType`, so existing behavior is unchanged.

## Server Side

Authoring `input_required` results with `InputRequiredResult`, securing `requestState`, `resultType` stamping, and the legacy fulfillment
shim that serves pre-2026 clients are documented on the server [Multi-Round-Trip Results](/server/multi-round-trip-results/) page.
80 changes: 80 additions & 0 deletions docs/_client/pagination.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
layout: default
title: Pagination
nav_order: 7
---

# Pagination

Servers may paginate `tools/list`, `prompts/list`, `resources/list`, and `resources/templates/list` responses
per the [MCP pagination utility](https://modelcontextprotocol.io/specification/latest/server/utilities/pagination).
Cursor tokens are opaque to clients: the server decides page size, and the client follows `nextCursor` until the server omits it.

## Iterating Pages

`MCP::Client` exposes `list_tools`, `list_prompts`, `list_resources`, and `list_resource_templates`.
**Each call issues exactly one `*/list` JSON-RPC request and returns exactly one page** - not the full collection.
The returned result object (`MCP::Client::ListToolsResult` etc.) exposes the page items and the next cursor
as method accessors; a `meta` accessor also mirrors the response's `_meta` field:

```ruby
client = MCP::Client.new(transport: transport)

cursor = nil
loop do
page = client.list_tools(cursor: cursor)
page.tools.each { |tool| process(tool) }
cursor = page.next_cursor
break unless cursor
end
```

The same pattern applies to `list_prompts` (`page.prompts`), `list_resources` (`page.resources`), and
`list_resource_templates` (`page.resource_templates`). `next_cursor` is `nil` on the final page.

Because a single call returns a single page, how many items come back depends on the server's `page_size` configuration:

| Server `page_size` | `client.list_tools(cursor: nil)` |
|--------------------|---------------------------------------------------------------------|
| Not set (default) | Returns every item in one response. `next_cursor` is `nil`. |
| Set to `N` | Returns the first `N` items. `next_cursor` is set for continuation. |

If your application needs the complete collection regardless of how the server is configured, either loop on
`next_cursor` as shown above, or use the whole-collection methods described below.

## Fetching the Complete Collection

`client.tools`, `client.resources`, `client.resource_templates`, and `client.prompts` auto-iterate
through all pages and return a plain array of items, guaranteeing the full collection regardless
of the server's `page_size` setting. When a server paginates, they issue multiple JSON-RPC round
trips per call. Two guards keep that loop finite: it stops when the server returns a `nextCursor`
it has already sent, and it stops after `max_pages` pages.

```ruby
tools = client.tools # => Array<MCP::Client::Tool> of every tool on the server.
```

`MCP::Client.new` accepts an optional `max_pages:` keyword that caps how many pages these methods
will walk. It defaults to `1_000`; a server that keeps offering a fresh `nextCursor` past that
point raises `MCP::Client::PaginationLimitError` rather than being followed indefinitely. Raise it
if you legitimately expect more pages than that.

Use these when you want the complete list; use `list_tools(cursor:)` etc. when you need
fine-grained iteration (e.g. to stream-process pages without loading everything into memory).

## Cache Hints

Per SEP-2549, list and read results can carry cache hints telling clients how long a result stays fresh (`ttlMs`)
and whether shared intermediaries may cache it (`cacheScope`); see
[List Result Caching](/server/pagination/#list-result-caching) on the server page for how they are emitted.
On the client, the values are surfaced on the paginated result structs as `ttl_ms` and `cache_scope`:

```ruby
page = client.list_tools
page.ttl_ms # => 60000 (nil when the server sent no hint)
page.cache_scope # => "private"
```

## Server Side

Enabling pagination with `page_size:` is documented on the server [Pagination](/server/pagination/) page.
Loading