mcp 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -2,12 +2,21 @@
2
2
 
3
3
  The official Ruby SDK for Model Context Protocol servers and clients.
4
4
 
5
+ Detailed guides are available at https://ruby.sdk.modelcontextprotocol.io.
6
+
7
+ ## Features
8
+
9
+ - Build [MCP servers](https://ruby.sdk.modelcontextprotocol.io/server/) that expose tools, prompts, and resources to any MCP host
10
+ - Build [MCP clients](https://ruby.sdk.modelcontextprotocol.io/client/) that connect to any MCP server, with automatic lifecycle negotiation and OAuth 2.1 authorization
11
+ - Speak every standard transport: stdio and Streamable HTTP (including SSE), with a Rails integration
12
+ - Cover the full protocol surface: server-to-client requests, multi round-trip results, notifications, progress, logging, cancellation, completions, and pagination
13
+
5
14
  ## Installation
6
15
 
7
16
  Add this line to your application's Gemfile:
8
17
 
9
18
  ```ruby
10
- gem 'mcp'
19
+ gem "mcp"
11
20
  ```
12
21
 
13
22
  And then execute:
@@ -24,51 +33,14 @@ $ gem install mcp
24
33
 
25
34
  You may need to add additional dependencies depending on which features you wish to access.
26
35
 
27
- ## Building an MCP Server
28
-
29
- The `MCP::Server` class is the core component that handles JSON-RPC requests and responses.
30
- It implements the Model Context Protocol specification, handling model context requests and responses.
31
-
32
- ### Key Features
33
-
34
- - Implements JSON-RPC 2.0 message handling
35
- - Supports protocol initialization and capability negotiation
36
- - Manages tool registration and invocation
37
- - Supports prompt registration and execution
38
- - Supports resource registration and retrieval
39
- - Supports stdio & Streamable HTTP (including SSE) transports
40
- - Supports notifications for list changes (tools, prompts, resources)
41
- - Supports roots (server-to-client filesystem boundary queries)
42
- - Supports sampling (server-to-client LLM completion requests)
43
- - Supports cursor-based pagination for list operations
44
- - Supports cancellation of in-flight requests on both server and client (notifications/cancelled)
45
-
46
- ### Supported Methods
47
-
48
- - `initialize` - Initializes the protocol and returns server capabilities
49
- - `server/discover` - Sessionless capability discovery (MCP 2026-07-28 draft, SEP-2575): returns `supportedVersions`, `capabilities`, `serverInfo`,
50
- and `instructions`, and responds before `initialize` and without an `Mcp-Session-Id`
51
- - `ping` - Simple health check
52
- - `logging/setLevel` - Configures the minimum log level for the server
53
- - `tools/list` - Lists all registered tools and their schemas
54
- - `tools/call` - Invokes a specific tool with provided arguments
55
- - `prompts/list` - Lists all registered prompts and their schemas
56
- - `prompts/get` - Retrieves a specific prompt by name
57
- - `resources/list` - Lists all registered resources and their schemas
58
- - `resources/read` - Retrieves a specific resource by name
59
- - `resources/templates/list` - Lists all registered resource templates and their schemas
60
- - `resources/subscribe` - Subscribes to updates for a specific resource
61
- - `resources/unsubscribe` - Unsubscribes from updates for a specific resource
62
- - `completion/complete` - Returns autocompletion suggestions for prompt arguments and resource URIs
63
- - `roots/list` - Requests filesystem roots from the client (server-to-client)
64
- - `sampling/createMessage` - Requests LLM completion from the client (server-to-client)
65
- - `elicitation/create` - Requests user input from the client (server-to-client)
36
+ ## Quick Start
66
37
 
67
- ### Usage
38
+ The following minimal programs show both sides of the protocol: a server that exposes a single tool,
39
+ and a client that spawns such a server and drives it over stdio.
68
40
 
69
- #### Stdio Transport
41
+ ### MCP Server
70
42
 
71
- If you want to build a local command-line application, you can use the stdio transport:
43
+ A minimal server defines a tool and serves it over the stdio transport:
72
44
 
73
45
  ```ruby
74
46
  require "mcp"
@@ -104,2711 +76,64 @@ transport = MCP::Server::Transports::StdioTransport.new(server)
104
76
  transport.open
105
77
  ```
106
78
 
107
- `StdioTransport.new` accepts an optional `max_line_bytes:` keyword that caps the byte length of a single newline-delimited request frame. A frame that reaches this limit without a newline is rejected and the connection is closed, preventing unbounded memory growth from a peer that never emits a newline. It defaults to `4 * 1024 * 1024` (4 MiB).
108
-
109
- You can run this script and then type in requests to the server at the command line.
79
+ Save the script as `server.rb`, run it, and send JSON-RPC requests via stdin:
110
80
 
111
81
  ```console
112
- $ ruby examples/stdio_server.rb
82
+ $ ruby server.rb
113
83
  {"jsonrpc":"2.0","id":"1","method":"ping"}
114
84
  {"jsonrpc":"2.0","id":"2","method":"tools/list"}
115
85
  {"jsonrpc":"2.0","id":"3","method":"tools/call","params":{"name":"example_tool","arguments":{"message":"Hello"}}}
116
86
  ```
117
87
 
118
- #### Streamable HTTP Transport
119
-
120
- `MCP::Server::Transports::StreamableHTTPTransport` is a standard Rack app, so it can be mounted in any Rack-compatible framework.
121
- The following examples show two common integration styles in Rails.
122
-
123
- > [!IMPORTANT]
124
- > `MCP::Server::Transports::StreamableHTTPTransport` stores session and SSE stream state in memory,
125
- > so it must run in a single process. Use a single-process server (e.g., Puma with `workers 0`).
126
- > Multi-process configurations (Unicorn, or Puma with `workers > 0`) fork separate processes that
127
- > do not share memory, which breaks session management and SSE connections.
128
- >
129
- > When running multiple server instances behind a load balancer, configure your load balancer to use
130
- > sticky sessions (session affinity) so that requests with the same `Mcp-Session-Id` header are always
131
- > routed to the same instance.
132
- >
133
- > Stateless mode (`stateless: true`) does not use sessions and works with any server configuration.
134
-
135
- > [!IMPORTANT]
136
- > Per MCP 2025-11-25, `StreamableHTTPTransport` validates the `Host` and `Origin` headers by default to
137
- > prevent DNS rebinding attacks against locally bound servers, rejecting unauthorized values with HTTP 403.
138
- > `Host` is allowed for the loopback defaults (`127.0.0.1`, `::1`, `localhost`), and an `Origin` header,
139
- > when present, must be same-origin or explicitly allow-listed. Non-browser clients that send no `Origin`
140
- > header are unaffected.
141
- >
142
- > Deployments behind a reverse proxy or bound to a non-loopback interface must widen the allow lists:
143
- >
144
- > ```ruby
145
- > transport = MCP::Server::Transports::StreamableHTTPTransport.new(
146
- > server,
147
- > allowed_hosts: ["mcp.example.com"],
148
- > allowed_origins: ["https://app.example.com"],
149
- > )
150
- > ```
151
- >
152
- > An `allowed_hosts:` entry matches either the bare host name (any port) or the full `host:port` value,
153
- > so both `"mcp.example.com"` and `"mcp.example.com:8443"` work. Pass `dns_rebinding_protection: false`
154
- > to disable the check entirely (e.g., when an upstream proxy or middleware already validates `Host`/`Origin`).
155
-
156
- ##### Rails (mount)
157
-
158
- `StreamableHTTPTransport` is a Rack app that can be mounted directly in Rails routes:
159
-
160
- ```ruby
161
- # config/routes.rb
162
- server = MCP::Server.new(
163
- name: "my_server",
164
- title: "Example Server Display Name",
165
- version: "1.0.0",
166
- instructions: "Use the tools of this server as a last resort",
167
- tools: [SomeTool, AnotherTool],
168
- prompts: [MyPrompt],
169
- )
170
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server)
171
-
172
- Rails.application.routes.draw do
173
- mount transport => "/mcp"
174
- end
175
- ```
176
-
177
- `mount` directs all HTTP methods on `/mcp` to the transport. `StreamableHTTPTransport` internally dispatches
178
- `POST` (client-to-server JSON-RPC messages, with responses optionally streamed via SSE),
179
- `GET` (optional standalone SSE stream for server-to-client messages), and `DELETE` (session termination) per
180
- the [MCP Streamable HTTP transport spec](https://modelcontextprotocol.io/specification/latest/basic/transports#streamable-http),
181
- so no additional route configuration is needed.
182
-
183
- A complete runnable application using this approach is available in [`examples/rails`](examples/rails).
184
-
185
- ##### Rails (controller)
186
-
187
- While the mount approach creates a single server at boot time, the controller approach creates a new server per request.
188
- This allows you to customize tools, prompts, or configuration based on the request (e.g., different tools per route).
189
-
190
- `StreamableHTTPTransport#handle_request` returns proper HTTP status codes (e.g., 202 Accepted for notifications):
191
-
192
- ```ruby
193
- class McpController < ActionController::API
194
- def create
195
- server = MCP::Server.new(
196
- name: "my_server",
197
- title: "Example Server Display Name",
198
- version: "1.0.0",
199
- instructions: "Use the tools of this server as a last resort",
200
- tools: [SomeTool, AnotherTool],
201
- prompts: [MyPrompt],
202
- server_context: { user_id: current_user.id },
203
- )
204
- # Since the `MCP-Session-Id` is not shared across requests, `stateless: true` is set.
205
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true)
206
- status, headers, body = transport.handle_request(request)
207
-
208
- render(json: body.first, status: status, headers: headers)
209
- end
210
- end
211
- ```
212
-
213
- ### Configuration
214
-
215
- The gem can be configured using the `MCP.configure` block:
216
-
217
- ```ruby
218
- MCP.configure do |config|
219
- config.exception_reporter = ->(exception, server_context) {
220
- # Your exception reporting logic here
221
- # For example with Bugsnag:
222
- Bugsnag.notify(exception) do |report|
223
- report.add_metadata(:model_context_protocol, server_context)
224
- end
225
- }
226
-
227
- config.around_request = ->(data, &request_handler) {
228
- logger.info("Start: #{data[:method]}")
229
- request_handler.call
230
- logger.info("Done: #{data[:method]}, tool: #{data[:tool_name]}")
231
- }
232
- end
233
- ```
234
-
235
- or by creating an explicit configuration and passing it into the server.
236
- This is useful for systems where an application hosts more than one MCP server but
237
- they might require different configurations.
238
-
239
- ```ruby
240
- configuration = MCP::Configuration.new
241
- configuration.exception_reporter = ->(exception, server_context) {
242
- # Your exception reporting logic here
243
- # For example with Bugsnag:
244
- Bugsnag.notify(exception) do |report|
245
- report.add_metadata(:model_context_protocol, server_context)
246
- end
247
- }
248
-
249
- configuration.around_request = ->(data, &request_handler) {
250
- logger.info("Start: #{data[:method]}")
251
- request_handler.call
252
- logger.info("Done: #{data[:method]}, tool: #{data[:tool_name]}")
253
- }
254
-
255
- server = MCP::Server.new(
256
- # ... all other options
257
- configuration:,
258
- )
259
- ```
260
-
261
- ### Capability Extensions
262
-
263
- Per SEP-2133, both clients and servers can declare protocol extensions under the `extensions` member of their capabilities.
264
- Keys are extension identifiers using the reverse-DNS prefix convention (e.g. `"io.modelcontextprotocol/tasks"`, `"com.example/feature"`);
265
- values are extension-defined configuration objects, with `{}` meaning "supported with no settings".
266
-
267
- On the server, declare extensions through the `capabilities` keyword, either as a plain hash or via the `MCP::Server::Capabilities` builder:
268
-
269
- ```ruby
270
- capabilities = MCP::Server::Capabilities.new
271
- capabilities.support_tools
272
- capabilities.support_extensions("com.example/feature" => { enabled: true })
273
-
274
- server = MCP::Server.new(name: "my_server", capabilities: capabilities)
275
- ```
276
-
277
- The declared extensions appear in the `initialize` result's `capabilities.extensions`. Extensions the client declared during `initialize` are
278
- readable via `server.client_capabilities[:extensions]` (or `session.client_capabilities[:extensions]` for per-session transports).
279
-
280
- On the client, pass extensions through `connect`:
281
-
282
- ```ruby
283
- client.connect(capabilities: { extensions: { "com.example/feature" => {} } })
284
- ```
88
+ The same server can also run over Streamable HTTP, including mounted inside a Rails application;
89
+ see [Server Transports](https://ruby.sdk.modelcontextprotocol.io/server/transports/).
285
90
 
286
- ### MCP Apps (SEP-1865)
91
+ ### MCP Client
287
92
 
288
- MCP Apps is a Final extension (negotiated via the Capability Extensions mechanism above) that lets a server ship interactive
289
- HTML user interfaces which the host renders for tool results. On the server side the extension is a thin convention,
290
- and `MCP::Apps` provides the vocabulary and helpers:
93
+ A minimal client spawns a stdio server as a subprocess, connects, and lists and calls its tools:
291
94
 
292
95
  ```ruby
293
- capabilities = MCP::Server::Capabilities.new
294
- capabilities.support_tools
295
- capabilities.support_resources
296
- capabilities.support_extensions(MCP::Apps.capability) # { "io.modelcontextprotocol/ui" => { mimeTypes: [...] } }
297
-
298
- server = MCP::Server.new(
299
- name: "weather_server",
300
- capabilities: capabilities,
301
- # UI templates are ordinary resources with a `ui://` URI and the `text/html;profile=mcp-app` MIME type.
302
- resources: [MCP::Apps.ui_resource(uri: "ui://weather-server/dashboard", name: "weather_dashboard")],
96
+ stdio_transport = MCP::Client::Stdio.new(
97
+ command: "bundle",
98
+ args: ["exec", "ruby", "path/to/server.rb"],
99
+ env: { "API_KEY" => "my_secret_key" },
100
+ read_timeout: 30
303
101
  )
102
+ client = MCP::Client.new(transport: stdio_transport)
304
103
 
305
- server.resources_read_handler do |params|
306
- [{ uri: params[:uri], mimeType: MCP::Apps::RESOURCE_MIME_TYPE, text: "<html>...</html>" }]
307
- end
104
+ # Perform the MCP initialization handshake before sending any requests.
105
+ client.connect
308
106
 
309
- # Link the tool to its template via `_meta.ui.resourceUri` (pass `legacy: true` to also
310
- # emit the older flat `"ui/resourceUri"` alias for hosts that predate the Final spec).
311
- server.define_tool(
312
- name: "get_weather",
313
- meta: MCP::Apps.tool_meta(resource_uri: "ui://weather-server/dashboard"),
314
- ) do |server_context:|
315
- # The extension is optional: always return a meaningful text result, and use
316
- # `MCP::Apps.client_supports?` when UI-capable clients should get richer structured content.
317
- MCP::Apps.client_supports?(server.client_capabilities) # => true when the host declared the extension
318
- MCP::Tool::Response.new([{ type: "text", text: "Sunny, 22 degrees Celsius" }])
107
+ # List available tools.
108
+ tools = client.tools
109
+ tools.each do |tool|
110
+ puts "Tool: #{tool.name} - #{tool.description}"
319
111
  end
320
- ```
321
-
322
- Everything else the extension defines (the sandboxed iframe, the `ui/*` postMessage bridge, consent for UI-initiated actions)
323
- is the HOST's responsibility; a server only ever receives ordinary `resources/read` and `tools/call` requests.
324
- See the [MCP Apps specification](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx).
325
-
326
- ### Server Context and Configuration Block Data
327
-
328
- #### `server_context`
329
112
 
330
- The `server_context` is a user-defined hash that is passed into the server instance and made available to tool and prompt calls.
331
- It can be used to provide contextual information such as authentication state, user IDs, or request-specific data.
332
-
333
- **Type:**
334
-
335
- ```ruby
336
- server_context: { [String, Symbol] => Any }
337
- ```
338
-
339
- **Example:**
340
-
341
- ```ruby
342
- server = MCP::Server.new(
343
- name: "my_server",
344
- server_context: { user_id: current_user.id, request_id: request.uuid }
113
+ # Call a specific tool.
114
+ response = client.call_tool(
115
+ tool: tools.first,
116
+ arguments: { message: "Hello, world!" }
345
117
  )
346
- ```
347
-
348
- This hash is then passed as the `server_context` keyword argument to tool and prompt calls.
349
- Note that exception and instrumentation callbacks do not receive this user-defined hash.
350
- See the relevant sections below for the arguments they receive.
351
-
352
- #### Request-specific `_meta` Parameter
353
-
354
- The MCP protocol supports a special [`_meta` parameter](https://modelcontextprotocol.io/specification/2025-06-18/basic#general-fields) in requests that allows clients to pass request-specific metadata. The server automatically extracts this parameter and makes it available to tools and prompts as a nested field within the `server_context`.
355
-
356
- > [!NOTE]
357
- > `_meta` is only merged when `server_context` is a `Hash` (or `nil`, in which case a new `{ _meta: ... }` hash is synthesized).
358
- > If you assign a non-`Hash` value to `server_context`, `_meta` is not merged and tools will not see it
359
- > under `server_context[:_meta]`. Keep `server_context` as a `Hash` if your tools need access to `_meta`.
360
-
361
- **Access Pattern:**
362
-
363
- When a client includes `_meta` in the request params, it becomes available as `server_context[:_meta]`:
364
-
365
- ```ruby
366
- class MyTool < MCP::Tool
367
- def self.call(message:, server_context:)
368
- # Access provider-specific metadata
369
- session_id = server_context.dig(:_meta, :session_id)
370
- request_id = server_context.dig(:_meta, :request_id)
371
-
372
- # Access server's original context
373
- user_id = server_context.dig(:user_id)
374
-
375
- MCP::Tool::Response.new([{
376
- type: "text",
377
- text: "Processing for user #{user_id} in session #{session_id}"
378
- }])
379
- end
380
- end
381
- ```
382
-
383
- **Client Request Example:**
384
-
385
- ```json
386
- {
387
- "jsonrpc": "2.0",
388
- "id": 1,
389
- "method": "tools/call",
390
- "params": {
391
- "name": "my_tool",
392
- "arguments": { "message": "Hello" },
393
- "_meta": {
394
- "session_id": "abc123",
395
- "request_id": "req_456"
396
- }
397
- }
398
- }
399
- ```
400
-
401
- **Distributed Tracing (W3C Trace Context):**
402
-
403
- Per SEP-414, the keys `traceparent`, `tracestate`, and `baggage` are reserved un-prefixed `_meta` keys for propagating
404
- [W3C Trace Context](https://www.w3.org/TR/trace-context/) across MCP requests. The SDK guarantees these keys pass through
405
- incoming request `_meta` untouched, and exposes their names as constants on `MCP::TraceContext` (`TRACEPARENT_META_KEY`,
406
- `TRACESTATE_META_KEY`, `BAGGAGE_META_KEY`, and `META_KEYS`). The SDK does not depend on OpenTelemetry; bridge the values
407
- to your tracing system yourself:
408
-
409
- ```ruby
410
- class TracedTool < MCP::Tool
411
- def self.call(message:, server_context:)
412
- traceparent = server_context.dig(:_meta, :traceparent)
413
- # Hand traceparent/tracestate/baggage to your tracing library
414
- # (e.g. the opentelemetry-ruby gems) to continue the caller's trace.
415
-
416
- MCP::Tool::Response.new([{ type: "text", text: "ok" }])
417
- end
418
- end
419
- ```
420
-
421
- On the client side, every request method (`call_tool`, `read_resource`, `get_prompt`, `complete`, `ping`, and the `list_*` methods)
422
- accepts a `meta:` keyword to inject these keys into the outgoing request, so trace context can flow on every request:
423
-
424
- ```ruby
425
- meta = { MCP::TraceContext::TRACEPARENT_META_KEY => "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" }
426
-
427
- client.call_tool(tool: tool, arguments: { message: "Hello" }, meta: meta)
428
- client.read_resource(uri: "file:///report.txt", meta: meta)
429
- ```
430
-
431
- #### Configuration Block Data
432
-
433
- ##### Exception Reporter
434
-
435
- The exception reporter receives:
436
-
437
- - `exception`: The Ruby exception object that was raised
438
- - `server_context`: A hash describing where the failure occurred (e.g., `{ request: <raw JSON-RPC request> }`
439
- for request handling, `{ notification: "tools_list_changed" }` for notification delivery).
440
- This is not the user-defined `server_context` passed to `Server.new`.
441
-
442
- **Signature:**
443
-
444
- ```ruby
445
- exception_reporter = ->(exception, server_context) { ... }
446
- ```
447
-
448
- ##### Around Request
449
-
450
- The `around_request` hook wraps request handling, allowing you to execute code before and after each request.
451
- This is useful for Application Performance Monitoring (APM) tracing, logging, or other observability needs.
452
-
453
- The hook receives a `data` hash and a `request_handler` block. You must call `request_handler.call` to execute the request:
454
-
455
- **Signature:**
456
-
457
- ```ruby
458
- around_request = ->(data, &request_handler) { request_handler.call }
459
- ```
460
-
461
- **`data` availability by timing:**
462
-
463
- - Before `request_handler.call`: `method`
464
- - After `request_handler.call`: `tool_name`, `tool_arguments`, `prompt_name`, `resource_uri`, `error`, `client`
465
- - Not available inside `around_request`: `duration` (added after `around_request` returns)
466
-
467
- > [!NOTE]
468
- > `tool_name`, `prompt_name` and `resource_uri` may only be populated for the corresponding request methods
469
- > (`tools/call`, `prompts/get`, `resources/read`), and may not be set depending on how the request is handled
470
- > (for example, `prompt_name` is not recorded when the prompt is not found).
471
- > `duration` is added after `around_request` returns, so it is not visible from within the hook.
472
-
473
- **Example:**
474
-
475
- ```ruby
476
- MCP.configure do |config|
477
- config.around_request = ->(data, &request_handler) {
478
- logger.info("Start: #{data[:method]}")
479
- request_handler.call
480
- logger.info("Done: #{data[:method]}, tool: #{data[:tool_name]}")
481
- }
482
- end
483
- ```
484
-
485
- ##### Instrumentation Callback (soft-deprecated)
486
-
487
- > [!NOTE]
488
- > `instrumentation_callback` is soft-deprecated. Use `around_request` instead.
489
- >
490
- > To migrate, wrap the call in `begin/ensure` so the callback still runs when the request fails:
491
- >
492
- > ```ruby
493
- > # Before
494
- > config.instrumentation_callback = ->(data) { log(data) }
495
- >
496
- > # After
497
- > config.around_request = ->(data, &request_handler) do
498
- > request_handler.call
499
- > ensure
500
- > log(data)
501
- > end
502
- > ```
503
- >
504
- > Note that `data[:duration]` is not available inside `around_request`.
505
- > If you need it, measure elapsed time yourself within the hook, or keep using `instrumentation_callback`.
506
-
507
- The instrumentation callback is called after each request finishes, whether successfully or with an error.
508
- It receives a hash with the following possible keys:
509
-
510
- - `method`: (String) The protocol method called (e.g., "ping", "tools/list")
511
- - `tool_name`: (String, optional) The name of the tool called
512
- - `tool_arguments`: (Hash, optional) The arguments passed to the tool
513
- - `prompt_name`: (String, optional) The name of the prompt called
514
- - `resource_uri`: (String, optional) The URI of the resource called
515
- - `error`: (String, optional) Error code if a lookup failed
516
- - `duration`: (Float) Duration of the call in seconds
517
- - `client`: (Hash, optional) Client information with `name` and `version` keys, from the initialize request
518
-
519
- **Signature:**
520
-
521
- ```ruby
522
- instrumentation_callback = ->(data) { ... }
523
- ```
524
-
525
- ### Server Protocol Version
526
-
527
- The server's protocol version can be overridden using the `protocol_version` keyword argument:
528
-
529
- ```ruby
530
- configuration = MCP::Configuration.new(protocol_version: "2024-11-05")
531
- MCP::Server.new(name: "test_server", configuration: configuration)
532
- ```
533
-
534
- If no protocol version is specified, the latest stable version will be applied by default.
535
- The latest stable version includes new features from the [draft version](https://modelcontextprotocol.io/specification/draft).
536
-
537
- This will make all new server instances use the specified protocol version instead of the default version. The protocol version can be reset to the default by setting it to `nil`:
538
-
539
- ```ruby
540
- MCP::Configuration.new(protocol_version: nil)
541
- ```
542
-
543
- If an invalid `protocol_version` value is set, an `ArgumentError` is raised.
544
-
545
- Be sure to check the [MCP spec](https://modelcontextprotocol.io/specification/versioning) for the protocol version to understand the supported features for the version being set.
546
-
547
- ### Exception Reporting
548
-
549
- The exception reporter receives two arguments:
550
-
551
- - `exception`: The Ruby exception object that was raised
552
- - `server_context`: A hash containing contextual information about where the error occurred
553
-
554
- The `server_context` hash includes:
555
-
556
- - For request handling failures: `{ request: { ... } }` (the raw JSON-RPC request hash)
557
- - For notification delivery failures: `{ notification: "tools_list_changed" }` (or the relevant notification name)
558
-
559
- When an exception occurs:
560
-
561
- 1. The exception is reported via the configured reporter
562
- 2. For tool calls, a generic error response is returned to the client: `{ error: "Internal error occurred", isError: true }`
563
- 3. For other requests, the exception is re-raised after reporting
564
-
565
- If no exception reporter is configured, a default no-op reporter is used that silently ignores exceptions.
566
-
567
- ### Tools
568
-
569
- MCP spec includes [Tools](https://modelcontextprotocol.io/specification/latest/server/tools) which provide functionality to LLM apps.
570
-
571
- This gem provides a `MCP::Tool` class that can be used to create tools in three ways:
572
-
573
- 1. As a class definition:
574
-
575
- ```ruby
576
- class MyTool < MCP::Tool
577
- title "My Tool"
578
- description "This tool performs specific functionality..."
579
- input_schema(
580
- properties: {
581
- message: { type: "string" },
582
- },
583
- required: ["message"]
584
- )
585
- output_schema(
586
- properties: {
587
- result: { type: "string" },
588
- success: { type: "boolean" },
589
- timestamp: { type: "string", format: "date-time" }
590
- },
591
- required: ["result", "success", "timestamp"]
592
- )
593
- annotations(
594
- read_only_hint: true,
595
- destructive_hint: false,
596
- idempotent_hint: true,
597
- open_world_hint: false,
598
- title: "My Tool"
599
- )
600
-
601
- def self.call(message:, server_context:)
602
- MCP::Tool::Response.new([{ type: "text", text: "OK" }])
603
- end
604
- end
605
118
 
606
- tool = MyTool
607
- ```
608
-
609
- 2. By using the `MCP::Tool.define` method with a block:
610
-
611
- ```ruby
612
- tool = MCP::Tool.define(
613
- name: "my_tool",
614
- title: "My Tool",
615
- description: "This tool performs specific functionality...",
616
- annotations: {
617
- read_only_hint: true,
618
- title: "My Tool"
619
- }
620
- ) do |args, server_context:|
621
- MCP::Tool::Response.new([{ type: "text", text: "OK" }])
622
- end
623
- ```
624
-
625
- 3. By using the `MCP::Server#define_tool` method with a block:
626
-
627
- ```ruby
628
- server = MCP::Server.new
629
- server.define_tool(
630
- name: "my_tool",
631
- description: "This tool performs specific functionality...",
632
- annotations: {
633
- title: "My Tool",
634
- read_only_hint: true
635
- }
636
- ) do |args, server_context:|
637
- Tool::Response.new([{ type: "text", text: "OK" }])
638
- end
639
- ```
640
-
641
- The server_context parameter is the server_context passed into the server and can be used to pass per request information,
642
- e.g. around authentication state.
643
-
644
- Tool arguments arrive as a `Hash` with symbol keys at every nesting level, because the transports parse JSON with `symbolize_names: true`.
645
- Read nested objects with symbol keys (`payload[:subject]`, not `payload["subject"]`).
646
- See [Tool argument keys](docs/building-servers.md#tool-argument-keys) for details and a testing tip.
647
-
648
- ### Tool Annotations
649
-
650
- Tools can include annotations that provide additional metadata about their behavior. The following annotations are supported:
651
-
652
- - `destructive_hint`: Indicates if the tool performs destructive operations. Defaults to true
653
- - `idempotent_hint`: Indicates if the tool's operations are idempotent. Defaults to false
654
- - `open_world_hint`: Indicates if the tool operates in an open world context. Defaults to true
655
- - `read_only_hint`: Indicates if the tool only reads data (doesn't modify state). Defaults to false
656
- - `title`: A human-readable title for the tool
657
-
658
- Annotations can be set either through the class definition using the `annotations` class method or when defining a tool using the `define` method.
659
-
660
- > [!NOTE]
661
- > This **Tool Annotations** feature is supported starting from `protocol_version: '2025-03-26'`.
662
-
663
- ### Tool Output Schemas
664
-
665
- Tools can optionally define an `output_schema` to specify the expected structure of their results. This works similarly to how `input_schema` is defined and can be used in three ways:
666
-
667
- 1. **Class definition with output_schema:**
668
-
669
- ```ruby
670
- class WeatherTool < MCP::Tool
671
- tool_name "get_weather"
672
- description "Get current weather for a location"
673
-
674
- input_schema(
675
- properties: {
676
- location: { type: "string" },
677
- units: { type: "string", enum: ["celsius", "fahrenheit"] }
678
- },
679
- required: ["location"]
680
- )
681
-
682
- output_schema(
683
- properties: {
684
- temperature: { type: "number" },
685
- condition: { type: "string" },
686
- humidity: { type: "integer" }
687
- },
688
- required: ["temperature", "condition", "humidity"]
689
- )
690
-
691
- def self.call(location:, units: "celsius", server_context:)
692
- # Call weather API and structure the response
693
- api_response = WeatherAPI.fetch(location, units)
694
- weather_data = {
695
- temperature: api_response.temp,
696
- condition: api_response.description,
697
- humidity: api_response.humidity_percent
698
- }
699
-
700
- output_schema.validate_result(weather_data)
701
-
702
- MCP::Tool::Response.new([{
703
- type: "text",
704
- text: weather_data.to_json
705
- }])
706
- end
707
- end
708
- ```
709
-
710
- 2. **Using Tool.define with output_schema:**
711
-
712
- ```ruby
713
- tool = MCP::Tool.define(
714
- name: "calculate_stats",
715
- description: "Calculate statistics for a dataset",
716
- input_schema: {
717
- properties: {
718
- numbers: { type: "array", items: { type: "number" } }
719
- },
720
- required: ["numbers"]
721
- },
722
- output_schema: {
723
- properties: {
724
- mean: { type: "number" },
725
- median: { type: "number" },
726
- count: { type: "integer" }
727
- },
728
- required: ["mean", "median", "count"]
729
- }
730
- ) do |args, server_context:|
731
- # Calculate statistics and validate against schema
732
- MCP::Tool::Response.new([{ type: "text", text: "Statistics calculated" }])
733
- end
119
+ # Close the transport when done.
120
+ stdio_transport.close
734
121
  ```
735
122
 
736
- 3. **Using OutputSchema objects:**
123
+ The same client can connect to Streamable HTTP servers with `MCP::Client::HTTP`;
124
+ see [Client Transports](https://ruby.sdk.modelcontextprotocol.io/client/transports/).
737
125
 
738
- ```ruby
739
- class DataTool < MCP::Tool
740
- output_schema MCP::Tool::OutputSchema.new(
741
- properties: {
742
- success: { type: "boolean" },
743
- data: { type: "object" }
744
- },
745
- required: ["success"]
746
- )
747
- end
748
- ```
126
+ ## Examples
749
127
 
750
- Output schema may also describe an array of objects:
128
+ Runnable examples are available in [`examples/`](https://github.com/modelcontextprotocol/ruby-sdk/tree/main/examples),
129
+ including a complete Rails application in [`examples/rails`](https://github.com/modelcontextprotocol/ruby-sdk/tree/main/examples/rails).
751
130
 
752
- ```ruby
753
- class WeatherTool < MCP::Tool
754
- output_schema(
755
- type: "array",
756
- items: {
757
- properties: {
758
- temperature: { type: "number" },
759
- condition: { type: "string" },
760
- humidity: { type: "integer" }
761
- },
762
- required: ["temperature", "condition", "humidity"]
763
- }
764
- )
765
- end
766
- ```
131
+ ## Documentation
767
132
 
768
- Please note: in this case, you must provide `type: "array"`. The default type for output schemas is `object`,
769
- applied only when the schema declares no root keyword (`type`, `$ref`, `oneOf`, `anyOf`, `allOf`, `not`, `if`, `const`, `enum`).
133
+ - [SDK guides](https://ruby.sdk.modelcontextprotocol.io)
134
+ - [SDK API documentation](https://rubydoc.info/gems/mcp)
135
+ - [Model Context Protocol documentation](https://modelcontextprotocol.io)
770
136
 
771
- Per SEP-2106, an output schema may be any valid JSON Schema 2020-12 document, including a primitive root
772
- (`{ type: "string" }`) or a root-level composition:
137
+ ## License
773
138
 
774
- ```ruby
775
- class FlexibleTool < MCP::Tool
776
- output_schema(
777
- oneOf: [
778
- { type: "string" },
779
- { type: "array", items: { type: "number" } }
780
- ]
781
- )
782
- end
783
- ```
784
-
785
- Input schemas keep `type: "object"` at the root but accept the full 2020-12 vocabulary below it
786
- (`$defs`/`$ref`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`). Two resource bounds apply to
787
- all tool schemas: only same-document `$ref`s (starting with `#`) are accepted, and documents are
788
- capped at `MCP::Tool::Schema::MAX_SCHEMA_DEPTH` nesting levels and `MCP::Tool::Schema::MAX_SUBSCHEMA_COUNT` subschema objects;
789
- violations raise `ArgumentError` at construction time.
790
-
791
- MCP spec for the [Output Schema](https://modelcontextprotocol.io/specification/latest/server/tools#output-schema) specifies that:
792
-
793
- - **Server Validation**: Servers MUST provide structured results that conform to the output schema
794
- - **Client Validation**: Clients SHOULD validate structured results against the output schema
795
- - **Better Integration**: Enables strict schema validation, type information, and improved developer experience
796
- - **Backward Compatibility**: Tools returning structured content SHOULD also include serialized JSON in a TextContent block
797
-
798
- The output schema follows standard JSON Schema format and helps ensure consistent data exchange between MCP servers and clients.
799
-
800
- By default, server-side validation of tool results against `output_schema` is disabled for backwards compatibility. To validate successful tool responses, enable `validate_tool_call_results`:
801
-
802
- ```ruby
803
- configuration = MCP::Configuration.new(validate_tool_call_results: true)
804
- server = MCP::Server.new(
805
- name: "example_server",
806
- tools: [WeatherTool],
807
- configuration: configuration
808
- )
809
- ```
810
-
811
- When enabled, successful tool responses for tools with an `output_schema` must include `structured_content` that conforms to the schema. Error responses are not validated against the output schema.
812
-
813
- ### Tool Responses with Structured Content
814
-
815
- Tools can return structured data alongside text content using the `structured_content` parameter.
816
-
817
- The structured content will be included in the JSON-RPC response as the `structuredContent` field.
818
-
819
- Per SEP-2106, `structured_content` may be any JSON value, not only an object. When a tool returns a non-object value (e.g. an array)
820
- without providing any content blocks, the server automatically mirrors it into `content` as serialized JSON text so older clients
821
- that only read `content` still receive the data.
822
-
823
- ```ruby
824
- class WeatherTool < MCP::Tool
825
- description "Get current weather and return structured data"
826
-
827
- def self.call(location:, units: "celsius", server_context:)
828
- # Call weather API and structure the response
829
- api_response = WeatherAPI.fetch(location, units)
830
- weather_data = {
831
- temperature: api_response.temp,
832
- condition: api_response.description,
833
- humidity: api_response.humidity_percent
834
- }
835
-
836
- output_schema.validate_result(weather_data)
837
-
838
- MCP::Tool::Response.new(
839
- [{
840
- type: "text",
841
- text: weather_data.to_json
842
- }],
843
- structured_content: weather_data
844
- )
845
- end
846
- end
847
- ```
848
-
849
- ### Tool Responses with Errors
850
-
851
- Tools can return error information alongside text content using the `error` parameter.
852
-
853
- The error will be included in the JSON-RPC response as the `isError` field.
854
-
855
- ```ruby
856
- class WeatherTool < MCP::Tool
857
- description "Get current weather and return structured data"
858
-
859
- def self.call(server_context:)
860
- # Do something here
861
- content = {}
862
-
863
- MCP::Tool::Response.new(
864
- [{
865
- type: "text",
866
- text: content.to_json
867
- }],
868
- structured_content: content,
869
- error: true
870
- )
871
- end
872
- end
873
- ```
874
-
875
- ### Tool Responses with Image, Audio, and Embedded Resources
876
-
877
- Tool responses are not limited to text. The `MCP::Content` module provides `Image`, `Audio`, and `EmbeddedResource` content types,
878
- which serialize to the `image`, `audio`, and `resource` content blocks defined by the MCP spec. Image and audio data is passed as
879
- a base64-encoded string together with its MIME type:
880
-
881
- ```ruby
882
- class ChartTool < MCP::Tool
883
- description "Render a chart as a PNG image"
884
-
885
- def self.call(server_context:)
886
- MCP::Tool::Response.new([
887
- MCP::Content::Text.new("Here is the rendered chart:").to_h,
888
- MCP::Content::Image.new(Base64.strict_encode64(render_chart_png), "image/png").to_h,
889
- ])
890
- end
891
- end
892
-
893
- class SpeechTool < MCP::Tool
894
- description "Synthesize speech audio"
895
-
896
- def self.call(server_context:)
897
- MCP::Tool::Response.new([
898
- MCP::Content::Audio.new(Base64.strict_encode64(synthesize_wav), "audio/wav").to_h,
899
- ])
900
- end
901
- end
902
- ```
903
-
904
- An embedded resource wraps `MCP::Resource::TextContents` or `MCP::Resource::BlobContents`, allowing a tool to return resource contents inline:
905
-
906
- ```ruby
907
- class ReportTool < MCP::Tool
908
- description "Return a report as an embedded resource"
909
-
910
- def self.call(server_context:)
911
- contents = MCP::Resource::TextContents.new(
912
- uri: "report://monthly",
913
- mime_type: "application/json",
914
- text: { total: 42 }.to_json,
915
- )
916
-
917
- MCP::Tool::Response.new([MCP::Content::EmbeddedResource.new(contents).to_h])
918
- end
919
- end
920
- ```
921
-
922
- ### Prompts
923
-
924
- MCP spec includes [Prompts](https://modelcontextprotocol.io/specification/latest/server/prompts), which enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs.
925
-
926
- The `MCP::Prompt` class provides three ways to create prompts:
927
-
928
- 1. As a class definition with metadata:
929
-
930
- ```ruby
931
- class MyPrompt < MCP::Prompt
932
- prompt_name "my_prompt" # Optional - defaults to underscored class name
933
- title "My Prompt"
934
- description "This prompt performs specific functionality..."
935
- arguments [
936
- MCP::Prompt::Argument.new(
937
- name: "message",
938
- title: "Message Title",
939
- description: "Input message",
940
- required: true
941
- )
942
- ]
943
- meta({ version: "1.0", category: "example" })
944
-
945
- class << self
946
- def template(args, server_context:)
947
- MCP::Prompt::Result.new(
948
- description: "Response description",
949
- messages: [
950
- MCP::Prompt::Message.new(
951
- role: "user",
952
- content: MCP::Content::Text.new("User message")
953
- ),
954
- MCP::Prompt::Message.new(
955
- role: "assistant",
956
- content: MCP::Content::Text.new(args["message"])
957
- )
958
- ]
959
- )
960
- end
961
- end
962
- end
963
-
964
- prompt = MyPrompt
965
- ```
966
-
967
- 2. Using the `MCP::Prompt.define` method:
968
-
969
- ```ruby
970
- prompt = MCP::Prompt.define(
971
- name: "my_prompt",
972
- title: "My Prompt",
973
- description: "This prompt performs specific functionality...",
974
- arguments: [
975
- MCP::Prompt::Argument.new(
976
- name: "message",
977
- title: "Message Title",
978
- description: "Input message",
979
- required: true
980
- )
981
- ],
982
- meta: { version: "1.0", category: "example" }
983
- ) do |args, server_context:|
984
- MCP::Prompt::Result.new(
985
- description: "Response description",
986
- messages: [
987
- MCP::Prompt::Message.new(
988
- role: "user",
989
- content: MCP::Content::Text.new("User message")
990
- ),
991
- MCP::Prompt::Message.new(
992
- role: "assistant",
993
- content: MCP::Content::Text.new(args["message"])
994
- )
995
- ]
996
- )
997
- end
998
- ```
999
-
1000
- 3. Using the `MCP::Server#define_prompt` method:
1001
-
1002
- ```ruby
1003
- server = MCP::Server.new
1004
- server.define_prompt(
1005
- name: "my_prompt",
1006
- description: "This prompt performs specific functionality...",
1007
- arguments: [
1008
- Prompt::Argument.new(
1009
- name: "message",
1010
- title: "Message Title",
1011
- description: "Input message",
1012
- required: true
1013
- )
1014
- ],
1015
- meta: { version: "1.0", category: "example" }
1016
- ) do |args, server_context:|
1017
- Prompt::Result.new(
1018
- description: "Response description",
1019
- messages: [
1020
- Prompt::Message.new(
1021
- role: "user",
1022
- content: Content::Text.new("User message")
1023
- ),
1024
- Prompt::Message.new(
1025
- role: "assistant",
1026
- content: Content::Text.new(args["message"])
1027
- )
1028
- ]
1029
- )
1030
- end
1031
- ```
1032
-
1033
- The server_context parameter is the server_context passed into the server and can be used to pass per request information,
1034
- e.g. around authentication state or user preferences.
1035
-
1036
- ### Key Components
1037
-
1038
- - `MCP::Prompt::Argument` - Defines input parameters for the prompt template with name, title, description, and required flag
1039
- - `MCP::Prompt::Message` - Represents a message in the conversation with a role and content
1040
- - `MCP::Prompt::Result` - The output of a prompt template containing description and messages
1041
- - `MCP::Content::Text` - Text content for messages
1042
-
1043
- ### Usage
1044
-
1045
- Register prompts with the MCP server:
1046
-
1047
- ```ruby
1048
- server = MCP::Server.new(
1049
- name: "my_server",
1050
- prompts: [MyPrompt],
1051
- server_context: { user_id: current_user.id },
1052
- )
1053
- ```
1054
-
1055
- The server will handle prompt listing and execution through the MCP protocol methods:
1056
-
1057
- - `prompts/list` - Lists all registered prompts and their schemas
1058
- - `prompts/get` - Retrieves and executes a specific prompt with arguments
1059
-
1060
- ### Prompts with Image and Embedded Resource Content
1061
-
1062
- Prompt messages are not limited to text. The same `MCP::Content` types used in tool responses can be used as message content,
1063
- letting a prompt template include images or inline resource contents. Unlike tool responses, the content object is passed directly rather than as a hash;
1064
- `MCP::Prompt::Message` serializes it when the prompt result is returned:
1065
-
1066
- ```ruby
1067
- class CodeReviewPrompt < MCP::Prompt
1068
- prompt_name "code_review"
1069
- description "Review a source file with an accompanying diagram"
1070
- arguments [
1071
- MCP::Prompt::Argument.new(name: "file_uri", description: "URI of the file to review", required: true),
1072
- ]
1073
-
1074
- class << self
1075
- def template(args, server_context:)
1076
- MCP::Prompt::Result.new(
1077
- messages: [
1078
- MCP::Prompt::Message.new(
1079
- role: "user",
1080
- content: MCP::Content::EmbeddedResource.new(
1081
- MCP::Resource::TextContents.new(
1082
- uri: args["file_uri"],
1083
- mime_type: "text/x-ruby",
1084
- text: read_source(args["file_uri"]),
1085
- ),
1086
- ),
1087
- ),
1088
- MCP::Prompt::Message.new(
1089
- role: "user",
1090
- content: MCP::Content::Image.new(architecture_diagram_base64, "image/png"),
1091
- ),
1092
- MCP::Prompt::Message.new(
1093
- role: "user",
1094
- content: MCP::Content::Text.new("Please review the code above, using the diagram for context."),
1095
- ),
1096
- ],
1097
- )
1098
- end
1099
- end
1100
- end
1101
- ```
1102
-
1103
- ### Resources
1104
-
1105
- MCP spec includes [Resources](https://modelcontextprotocol.io/specification/latest/server/resources).
1106
-
1107
- ### Reading Resources
1108
-
1109
- Like tools and prompts, resources can be defined in three ways.
1110
-
1111
- 1. As a class that inherits from `MCP::Resource`, implementing `contents` to serve the resource body:
1112
-
1113
- ```ruby
1114
- class MyResource < MCP::Resource
1115
- uri "https://example.com/my_resource"
1116
- resource_name "my-resource"
1117
- title "My Resource"
1118
- description "Lorem ipsum dolor sit amet"
1119
- mime_type "text/html"
1120
-
1121
- class << self
1122
- def contents
1123
- [MCP::Resource::TextContents.new(
1124
- uri: uri,
1125
- mime_type: mime_type,
1126
- text: "Hello from example resource!"
1127
- )]
1128
- end
1129
- end
1130
- end
1131
-
1132
- server = MCP::Server.new(
1133
- name: "my_server",
1134
- resources: [MyResource],
1135
- )
1136
- ```
1137
-
1138
- `resources/read` requests are routed automatically: when the requested URI matches a registered
1139
- class-based resource, its `contents` method is called. `contents` may return an array of
1140
- `MCP::Resource::TextContents` / `MCP::Resource::BlobContents` objects (or plain hashes), or a single one.
1141
- Like tools, `contents` can opt in to a `server_context:` keyword argument to receive per-request context.
1142
-
1143
- When class-based resources or resource templates are registered and a `resources/read` request
1144
- does not match any of them, the server responds with the standard JSON-RPC Invalid Params error
1145
- (`-32602`) carrying the requested URI in the error `data` member, per SEP-2164.
1146
-
1147
- 2. With the `MCP::Resource.define` method, whose block implements `contents`:
1148
-
1149
- ```ruby
1150
- resource = MCP::Resource.define(
1151
- uri: "https://example.com/my_resource",
1152
- name: "my-resource",
1153
- mime_type: "text/html",
1154
- ) do
1155
- [MCP::Resource::TextContents.new(uri: uri, mime_type: mime_type, text: "Hello!")]
1156
- end
1157
- ```
1158
-
1159
- 3. Using the `MCP::Server#define_resource` method:
1160
-
1161
- ```ruby
1162
- server = MCP::Server.new(name: "my_server")
1163
- server.define_resource(
1164
- uri: "https://example.com/my_resource",
1165
- name: "my-resource",
1166
- mime_type: "text/html",
1167
- ) do
1168
- [MCP::Resource::TextContents.new(uri: "https://example.com/my_resource", mime_type: "text/html", text: "Hello!")]
1169
- end
1170
- ```
1171
-
1172
- Alternatively, resources can be registered as plain data objects with `MCP::Resource.new`,
1173
- in which case the server only lists them:
1174
-
1175
- ```ruby
1176
- resource = MCP::Resource.new(
1177
- uri: "https://example.com/my_resource",
1178
- name: "my-resource",
1179
- title: "My Resource",
1180
- description: "Lorem ipsum dolor sit amet",
1181
- mime_type: "text/html",
1182
- )
1183
-
1184
- server = MCP::Server.new(
1185
- name: "my_server",
1186
- resources: [resource],
1187
- )
1188
- ```
1189
-
1190
- With plain data resources, the server must register a handler for the `resources/read` method to
1191
- retrieve a resource dynamically.
1192
-
1193
- ```ruby
1194
- server.resources_read_handler do |params|
1195
- [{
1196
- uri: params[:uri],
1197
- mimeType: "text/plain",
1198
- text: "Hello from example resource! URI: #{params[:uri]}"
1199
- }]
1200
- end
1201
- ```
1202
-
1203
- otherwise `resources/read` requests will be a no-op. Note that a `resources_read_handler` fully replaces
1204
- the default `resources/read` handling, including the automatic routing to class-based resources described above.
1205
-
1206
- For unknown URIs, raise `MCP::Server::ResourceNotFoundError` from the handler.
1207
- Per SEP-2164, the server then responds with the standard JSON-RPC Invalid Params error (`-32602`)
1208
- carrying the requested URI in the error `data` member:
1209
-
1210
- ```ruby
1211
- server.resources_read_handler do |params|
1212
- resource = lookup(params[:uri])
1213
- raise MCP::Server::ResourceNotFoundError.new(params[:uri], params) unless resource
1214
-
1215
- [{ uri: params[:uri], mimeType: resource.mime_type, text: resource.body }]
1216
- end
1217
- ```
1218
-
1219
- ### Reading Binary Resources
1220
-
1221
- For binary resources, respond with a base64-encoded `blob` field instead of `text`.
1222
- The `MCP::Resource::TextContents` and `MCP::Resource::BlobContents` classes build the two contents shapes defined by the spec:
1223
-
1224
- ```ruby
1225
- server.resources_read_handler do |params|
1226
- case params[:uri]
1227
- when "file:///logo.png"
1228
- [
1229
- MCP::Resource::BlobContents.new(
1230
- uri: params[:uri],
1231
- mime_type: "image/png",
1232
- data: Base64.strict_encode64(File.binread("logo.png")),
1233
- ).to_h,
1234
- ]
1235
- else
1236
- [
1237
- MCP::Resource::TextContents.new(
1238
- uri: params[:uri],
1239
- mime_type: "text/plain",
1240
- text: "Hello from example resource!",
1241
- ).to_h,
1242
- ]
1243
- end
1244
- end
1245
- ```
1246
-
1247
- ### Resource Templates
1248
-
1249
- Resource templates follow the same pattern. Class-based templates declare a `uri_template` and
1250
- receive the variables extracted from the requested URI as keyword arguments to `contents`:
1251
-
1252
- ```ruby
1253
- class UserProfileTemplate < MCP::ResourceTemplate
1254
- uri_template "users://{user_id}/profile"
1255
- resource_template_name "user-profile"
1256
- title "User Profile"
1257
- description "Profile data for a user"
1258
- mime_type "application/json"
1259
-
1260
- class << self
1261
- def contents(user_id:)
1262
- [MCP::Resource::TextContents.new(
1263
- uri: "users://#{user_id}/profile",
1264
- mime_type: mime_type,
1265
- text: { id: user_id }.to_json
1266
- )]
1267
- end
1268
- end
1269
- end
1270
-
1271
- server = MCP::Server.new(
1272
- name: "my_server",
1273
- resource_templates: [UserProfileTemplate],
1274
- )
1275
- ```
1276
-
1277
- A `resources/read` request for `users://42/profile` calls `UserProfileTemplate.contents(user_id: "42")`.
1278
- An exact match against a registered resource takes precedence over template matching.
1279
- `contents` can also opt in to a `server_context:` keyword argument.
1280
-
1281
- URI template matching supports simple [RFC 6570](https://www.rfc-editor.org/rfc/rfc6570) level 1 `{variable}` expressions only:
1282
-
1283
- - Operator expressions such as `{+path}`, `{#fragment}`, or `{?query}` are treated as literal text and never match an expanded URI.
1284
- - A variable matches one or more characters excluding `/`.
1285
- - Extracted values are not percent-decoded.
1286
-
1287
- The `MCP::ResourceTemplate.define` and `MCP::Server#define_resource_template` methods are also available,
1288
- mirroring the resource variants:
1289
-
1290
- ```ruby
1291
- server.define_resource_template(
1292
- uri_template: "users://{user_id}/profile",
1293
- name: "user-profile",
1294
- mime_type: "application/json",
1295
- ) do |user_id:|
1296
- [MCP::Resource::TextContents.new(
1297
- uri: "users://#{user_id}/profile",
1298
- mime_type: "application/json",
1299
- text: { id: user_id }.to_json
1300
- )]
1301
- end
1302
- ```
1303
-
1304
- Resource templates can also be registered as plain data objects with `MCP::ResourceTemplate.new`,
1305
- in which case reads must be served by a `resources_read_handler`:
1306
-
1307
- ```ruby
1308
- resource_template = MCP::ResourceTemplate.new(
1309
- uri_template: "https://example.com/my_resource_template",
1310
- name: "my-resource-template",
1311
- title: "My Resource Template",
1312
- description: "Lorem ipsum dolor sit amet",
1313
- mime_type: "text/html",
1314
- )
1315
-
1316
- server = MCP::Server.new(
1317
- name: "my_server",
1318
- resource_templates: [resource_template],
1319
- )
1320
- ```
1321
-
1322
- Registered templates are listed through the `resources/templates/list` protocol method.
1323
- To serve reads for URIs that match a template, extract the variable parts of the URI in your `resources_read_handler`:
1324
-
1325
- ```ruby
1326
- resource_template = MCP::ResourceTemplate.new(
1327
- uri_template: "file:///items/{item_id}",
1328
- name: "item",
1329
- mime_type: "application/json",
1330
- )
1331
-
1332
- server = MCP::Server.new(name: "my_server", resource_templates: [resource_template])
1333
-
1334
- server.resources_read_handler do |params|
1335
- if (match = params[:uri].match(%r{\Afile:///items/(?<item_id>[^/]+)\z}))
1336
- [{
1337
- uri: params[:uri],
1338
- mimeType: "application/json",
1339
- text: { id: match[:item_id] }.to_json,
1340
- }]
1341
- else
1342
- raise MCP::Server::ResourceNotFoundError.new(params[:uri], params)
1343
- end
1344
- end
1345
- ```
1346
-
1347
- ### Roots
1348
-
1349
- The Model Context Protocol allows servers to request filesystem roots from clients through the `roots/list` method.
1350
- Roots define the boundaries of where a server can operate, providing a list of directories and files the client has made available.
1351
-
1352
- **Key Concepts:**
1353
-
1354
- - **Server-to-Client Request**: Like sampling, roots listing is initiated by the server
1355
- - **Client Capability**: Clients must declare `roots` capability during initialization
1356
- - **Change Notifications**: Clients that support `roots.listChanged` send `notifications/roots/list_changed` when roots change
1357
-
1358
- > [!NOTE]
1359
- > Per SEP-2260, server-to-client requests (`roots/list`, `sampling/createMessage`, `elicitation/create`) must be associated with
1360
- > an originating client request (`ping` is exempt). Use the `server_context` passed to your handler, which stamps the association
1361
- > automatically and routes the request onto the originating POST stream on the Streamable HTTP transport. Calling the corresponding
1362
- > `ServerSession` methods without `related_request_id:` still works but emits a deprecation warning.
1363
-
1364
- **Using Roots in Tools:**
1365
-
1366
- Tools that accept a `server_context:` parameter can call `list_roots` on it.
1367
- The request is automatically routed to the correct client session:
1368
-
1369
- ```ruby
1370
- class FileSearchTool < MCP::Tool
1371
- description "Search files within the client's project roots"
1372
- input_schema(
1373
- properties: {
1374
- query: { type: "string" }
1375
- },
1376
- required: ["query"]
1377
- )
1378
-
1379
- def self.call(query:, server_context:)
1380
- roots = server_context.list_roots
1381
- root_uris = roots[:roots].map { |root| root[:uri] }
1382
-
1383
- MCP::Tool::Response.new([{
1384
- type: "text",
1385
- text: "Searching in roots: #{root_uris.join(", ")}"
1386
- }])
1387
- end
1388
- end
1389
- ```
1390
-
1391
- Result contains an array of root objects:
1392
-
1393
- ```ruby
1394
- {
1395
- roots: [
1396
- { uri: "file:///home/user/projects/myproject", name: "My Project" },
1397
- { uri: "file:///home/user/repos/backend", name: "Backend Repository" }
1398
- ]
1399
- }
1400
- ```
1401
-
1402
- **Handling Root Changes:**
1403
-
1404
- Register a callback to be notified when the client's roots change:
1405
-
1406
- ```ruby
1407
- server.roots_list_changed_handler do
1408
- puts "Client's roots have changed, tools will see updated roots on next call."
1409
- end
1410
- ```
1411
-
1412
- **Error Handling:**
1413
-
1414
- - Raises `RuntimeError` if client does not support `roots` capability
1415
- - Raises `StandardError` if client returns an error response
1416
-
1417
- ### Resource Subscriptions
1418
-
1419
- Resource subscriptions allow clients to monitor specific resources for changes.
1420
- When a subscribed resource is updated, the server sends a notification to the client.
1421
-
1422
- The SDK does not track subscription state internally.
1423
- Server developers register handlers and manage their own subscription state.
1424
- Three methods are provided:
1425
-
1426
- - `Server#resources_subscribe_handler` - registers a handler for `resources/subscribe` requests
1427
- - `Server#resources_unsubscribe_handler` - registers a handler for `resources/unsubscribe` requests
1428
- - `ServerContext#notify_resources_updated` - sends a `notifications/resources/updated` notification to the subscribing client
1429
-
1430
- ```ruby
1431
- subscribed_uris = Set.new
1432
-
1433
- server = MCP::Server.new(
1434
- name: "my_server",
1435
- resources: [my_resource],
1436
- capabilities: { resources: { subscribe: true } },
1437
- )
1438
-
1439
- server.resources_subscribe_handler do |params|
1440
- subscribed_uris.add(params[:uri].to_s)
1441
- end
1442
-
1443
- server.resources_unsubscribe_handler do |params|
1444
- subscribed_uris.delete(params[:uri].to_s)
1445
- end
1446
-
1447
- server.define_tool(name: "update_resource") do |server_context:, **args|
1448
- if subscribed_uris.include?("test://my-resource")
1449
- server_context.notify_resources_updated(uri: "test://my-resource")
1450
- end
1451
- MCP::Tool::Response.new([MCP::Content::Text.new("Resource updated").to_h])
1452
- end
1453
- ```
1454
-
1455
- ### Sampling
1456
-
1457
- The Model Context Protocol allows servers to request LLM completions from clients through the `sampling/createMessage` method.
1458
- This enables servers to leverage the client's LLM capabilities without needing direct access to AI models.
1459
-
1460
- **Key Concepts:**
1461
-
1462
- - **Server-to-Client Request**: Unlike typical MCP methods (client to server), sampling is initiated by the server
1463
- - **Client Capability**: Clients must declare `sampling` capability during initialization
1464
- - **Tool Support**: When using tools in sampling requests, clients must declare `sampling.tools` capability
1465
- - **Human-in-the-Loop**: Clients can implement user approval before forwarding requests to LLMs
1466
-
1467
- **Using Sampling in Tools:**
1468
-
1469
- Tools that accept a `server_context:` parameter can call `create_sampling_message` on it.
1470
- The request is automatically routed to the correct client session:
1471
-
1472
- ```ruby
1473
- class SummarizeTool < MCP::Tool
1474
- description "Summarize text using LLM"
1475
- input_schema(
1476
- properties: {
1477
- text: { type: "string" }
1478
- },
1479
- required: ["text"]
1480
- )
1481
-
1482
- def self.call(text:, server_context:)
1483
- result = server_context.create_sampling_message(
1484
- messages: [
1485
- { role: "user", content: { type: "text", text: "Please summarize: #{text}" } }
1486
- ],
1487
- max_tokens: 500
1488
- )
1489
-
1490
- MCP::Tool::Response.new([{
1491
- type: "text",
1492
- text: result[:content][:text]
1493
- }])
1494
- end
1495
- end
1496
-
1497
- server = MCP::Server.new(name: "my_server", tools: [SummarizeTool])
1498
- ```
1499
-
1500
- **Parameters:**
1501
-
1502
- Required:
1503
-
1504
- - `messages:` (Array) - Array of message objects with `role` and `content`
1505
- - `max_tokens:` (Integer) - Maximum tokens in the response
1506
-
1507
- Optional:
1508
-
1509
- - `system_prompt:` (String) - System prompt for the LLM
1510
- - `model_preferences:` (Hash) - Model selection preferences (e.g., `{ intelligencePriority: 0.8 }`)
1511
- - `include_context:` (String) - Context inclusion: `"none"`, `"thisServer"`, or `"allServers"` (soft-deprecated)
1512
- - `temperature:` (Float) - Sampling temperature
1513
- - `stop_sequences:` (Array) - Sequences that stop generation
1514
- - `metadata:` (Hash) - Additional metadata
1515
- - `tools:` (Array) - Tools available to the LLM (requires `sampling.tools` capability)
1516
- - `tool_choice:` (Hash) - Tool selection mode (e.g., `{ mode: "auto" }`)
1517
-
1518
- **Error Handling:**
1519
-
1520
- - Raises `RuntimeError` if client does not support `sampling` capability
1521
- - Raises `RuntimeError` if `tools` are used but client lacks `sampling.tools` capability
1522
- - Raises `StandardError` if client returns an error response
1523
-
1524
- ### Notifications
1525
-
1526
- The server supports sending notifications to clients when lists of tools, prompts, or resources change. This enables real-time updates without polling.
1527
-
1528
- #### Notification Methods
1529
-
1530
- The server provides the following notification methods:
1531
-
1532
- - `notify_tools_list_changed` - Send a notification when the tools list changes
1533
- - `notify_prompts_list_changed` - Send a notification when the prompts list changes
1534
- - `notify_resources_list_changed` - Send a notification when the resources list changes
1535
- - `notify_log_message` - Send a structured logging notification message
1536
-
1537
- #### Session Scoping
1538
-
1539
- When using Streamable HTTP transport with multiple clients, each client connection gets its own session. Notifications are scoped as follows:
1540
-
1541
- - **`report_progress`** and **`notify_log_message`** called via `server_context` inside a tool handler are automatically sent only to the requesting client.
1542
- No extra configuration is needed.
1543
- - **`notify_tools_list_changed`**, **`notify_prompts_list_changed`**, and **`notify_resources_list_changed`** are always broadcast to all connected clients,
1544
- as they represent server-wide state changes. These should be called on the `server` instance directly.
1545
-
1546
- #### Notification Format
1547
-
1548
- Notifications follow the JSON-RPC 2.0 specification and use these method names:
1549
-
1550
- - `notifications/tools/list_changed`
1551
- - `notifications/prompts/list_changed`
1552
- - `notifications/resources/list_changed`
1553
- - `notifications/cancelled`
1554
- - `notifications/progress`
1555
- - `notifications/message`
1556
-
1557
- ### Cancellation
1558
-
1559
- The MCP Ruby SDK supports server-side handling of the
1560
- [MCP `notifications/cancelled` utility](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation).
1561
- When a client sends `notifications/cancelled` for an in-flight request, the server stops
1562
- processing cooperatively and suppresses the JSON-RPC response for that request.
1563
-
1564
- Cancellation is cooperative: the SDK does not forcibly terminate tool code. Instead,
1565
- a `MCP::Cancellation` token is threaded through `server_context`, and long-running tools
1566
- poll it to exit early. When a tool returns after cancellation has been observed,
1567
- the server suppresses the JSON-RPC response, matching the spec. The `initialize` request
1568
- is never cancellable per the spec.
1569
-
1570
- Client-initiated cancellation is also supported: see [Client-Side: Cancelling an In-Flight Request](#client-side-cancelling-an-in-flight-request) below.
1571
-
1572
- #### Server-Side: Handlers that Check for Cancellation
1573
-
1574
- Any handler that opts in to `server_context:` - tools (`Tool.call`), prompt templates,
1575
- `resources_read_handler`, `completion_handler`, `resources_subscribe_handler`,
1576
- `resources_unsubscribe_handler`, and `define_custom_method` blocks - receives
1577
- an `MCP::ServerContext` wired to the in-flight request's cancellation token.
1578
- Handlers check `cancelled?` in their work loop, or call `raise_if_cancelled!` to raise
1579
- `MCP::CancelledError` at a safe point:
1580
-
1581
- ```ruby
1582
- class LongRunningTool < MCP::Tool
1583
- description "A tool that supports cancellation"
1584
- input_schema(properties: { count: { type: "integer" } }, required: ["count"])
1585
-
1586
- def self.call(count:, server_context:)
1587
- count.times do |i|
1588
- # Exit early if the client has sent `notifications/cancelled`.
1589
- break if server_context.cancelled?
1590
-
1591
- do_work(i)
1592
- end
1593
-
1594
- MCP::Tool::Response.new([{ type: "text", text: "Done" }])
1595
- end
1596
- end
1597
- ```
1598
-
1599
- Alternatively, raise at the next safe point with `raise_if_cancelled!`:
1600
-
1601
- ```ruby
1602
- def self.call(count:, server_context:)
1603
- count.times do |i|
1604
- server_context.raise_if_cancelled!
1605
-
1606
- do_work(i)
1607
- end
1608
-
1609
- MCP::Tool::Response.new([{ type: "text", text: "Done" }])
1610
- end
1611
- ```
1612
-
1613
- When a handler observes cancellation (either by returning early with `cancelled?` or
1614
- by raising `MCP::CancelledError` via `raise_if_cancelled!`), the server drops the response and
1615
- no JSON-RPC result is sent to the client.
1616
-
1617
- The same pattern works for other handler types:
1618
-
1619
- ```ruby
1620
- # resources/read
1621
- server.resources_read_handler do |params, server_context:|
1622
- server_context.raise_if_cancelled!
1623
- # read the resource
1624
- end
1625
-
1626
- # completion/complete
1627
- server.completion_handler do |params, server_context:|
1628
- server_context.raise_if_cancelled!
1629
- # compute completions
1630
- end
1631
-
1632
- # custom method
1633
- server.define_custom_method(method_name: "custom/slow") do |params, server_context:|
1634
- server_context.raise_if_cancelled!
1635
- # do work
1636
- end
1637
-
1638
- # prompts (via Prompt subclass)
1639
- class SlowPrompt < MCP::Prompt
1640
- prompt_name "slow_prompt"
1641
-
1642
- def self.template(args, server_context:)
1643
- server_context.raise_if_cancelled!
1644
- MCP::Prompt::Result.new(messages: [])
1645
- end
1646
- end
1647
- ```
1648
-
1649
- Handlers that do not declare a `server_context:` keyword continue to work unchanged -
1650
- the opt-in detection only wraps the context when the block signature asks for it.
1651
-
1652
- #### Nested Server-to-Client Requests Are Cancelled Automatically
1653
-
1654
- When a tool handler is waiting on a nested server-to-client request
1655
- (`server_context.create_sampling_message`, `create_form_elicitation`, or
1656
- `create_url_elicitation`), cancelling the parent tool call automatically raises
1657
- `MCP::CancelledError` from the nested call, so the tool does not need to wrap it
1658
- in its own `cancelled?` checks:
1659
-
1660
- ```ruby
1661
- def self.call(server_context:)
1662
- result = server_context.create_sampling_message(messages: messages, max_tokens: 100)
1663
- # If the parent tools/call is cancelled while waiting above, MCP::CancelledError
1664
- # is raised here and the tool can let it propagate or clean up as needed.
1665
- MCP::Tool::Response.new([{ type: "text", text: result[:content][:text] }])
1666
- rescue MCP::CancelledError
1667
- # Optional: run cleanup. Re-raising (or letting it propagate) is fine; the server
1668
- # will still suppress the JSON-RPC response per the MCP spec.
1669
- raise
1670
- end
1671
- ```
1672
-
1673
- Nested cancellation propagation is supported on `StreamableHTTPTransport` only.
1674
- `StdioTransport` is single-threaded and blocks on `$stdin.gets`, so a nested
1675
- `server_context.create_sampling_message` inside a tool runs to completion even if
1676
- the parent `tools/call` is cancelled. The parent tool itself still observes cancellation
1677
- via `server_context.cancelled?` between nested calls.
1678
-
1679
- #### Client-Side: Cancelling an In-Flight Request
1680
-
1681
- `MCP::Client` lets the caller cancel a request it has already issued. The recommended pattern is to pass
1682
- an `MCP::Cancellation` token into the request method, run the request on a worker thread, and call
1683
- `cancellation.cancel(reason:)` from another thread. The cancelling thread sends `notifications/cancelled` to
1684
- the server, and the calling thread is woken up with `MCP::CancelledError`:
1685
-
1686
- ```ruby
1687
- client = MCP::Client.new(transport: transport)
1688
- cancellation = MCP::Cancellation.new
1689
-
1690
- Thread.new do
1691
- client.call_tool(name: "slow_tool", arguments: {}, cancellation: cancellation)
1692
- rescue MCP::CancelledError
1693
- # cleanup
1694
- end
1695
-
1696
- # Later, from another thread:
1697
- cancellation.cancel(reason: "user pressed cancel")
1698
- ```
1699
-
1700
- All request methods (`tools`, `list_tools`, `resources`, `list_resources`, `resource_templates`, `list_resource_templates`,
1701
- `prompts`, `list_prompts`, `call_tool`, `read_resource`, `get_prompt`, `complete`, `ping`) accept the `cancellation:` keyword.
1702
- Request ids are managed internally, so the token is the only thing a caller needs to cancel a request.
1703
-
1704
- > [!NOTE]
1705
- > When a cancel wins the race, the SDK's worker thread that is blocked on the underlying I/O is *not* force-killed;
1706
- > it stays blocked until the transport actually returns (or the user closes the transport). This matches the server-side
1707
- > `StreamableHTTPTransport#send_request` trade-off. For `StreamableHTTPTransport#send_request` trade-off. For `Client::HTTP`
1708
- > the leak resolves as soon as the server sends any response; for `Client::Stdio` you may need to call `client.transport.close`
1709
- > to free the thread if the server stops responding entirely. The cancel-dispatch thread waits for the worker's send-boundary signal
1710
- > (`&on_sent` from `send_request`) before issuing `notifications/cancelled`, so the cancel is held until the worker has at
1711
- > least committed to writing the request; while the worker is wedged the cancel notification is deferred along with it.
1712
-
1713
- ##### Wire-order guarantees
1714
-
1715
- `Client::Stdio` serializes the request write and any subsequent `notifications/cancelled` write through a single `@write_mutex`,
1716
- so the server is guaranteed to read the request line before the cancel line.
1717
-
1718
- `Client::HTTP` cannot offer the same wire-arrival guarantee. Faraday's synchronous `post` does not expose a post-write / pre-response hook,
1719
- so the SDK yields just before the request POST is dispatched. After the yield, the cancel-dispatch thread issues a separate `notifications/cancelled` POST
1720
- 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
1721
- still believes it to be in-progress when issuing the cancel ([MCP cancellation spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation)),
1722
- and on the receiver side, "receivers MAY ignore a cancellation notification whose `requestId` is unknown" covers the case where the cancel POST
1723
- happens to arrive first. The calling thread raises `MCP::CancelledError` regardless of network ordering.
1724
-
1725
- ##### Custom transports
1726
-
1727
- Custom transports that want to support `cancellation:` must implement `send_notification(notification:)` so `notifications/cancelled` can be delivered.
1728
- 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
1729
- (under a write-side mutex for stdio-style transports, immediately before the synchronous round-trip for HTTP-style transports).
1730
- The cancel-dispatch thread waits on this signal before sending `notifications/cancelled`. Transports that do not invoke the block fall back to waiting for
1731
- the worker thread to terminate, which preserves wire-order at the cost of delaying the cancel notification until the request has fully completed.
1732
-
1733
- ### Ping
1734
-
1735
- The MCP Ruby SDK supports the
1736
- [MCP `ping` utility](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/ping),
1737
- which allows either side of the connection to verify that the peer is still responsive.
1738
- A `ping` request has no parameters, and the receiver MUST respond promptly with an empty result.
1739
-
1740
- #### Server-Side
1741
-
1742
- Servers respond to incoming `ping` requests automatically - no setup is required.
1743
- Any `MCP::Server` instance replies with an empty result.
1744
-
1745
- Servers can also send `ping` requests to the client via `ServerSession#ping`.
1746
- Inside a tool handler that receives `server_context:`, call `ping` on it:
1747
-
1748
- ```ruby
1749
- class HealthCheckTool < MCP::Tool
1750
- description "Verifies the client is still responsive"
1751
-
1752
- def self.call(server_context:)
1753
- server_context.ping # => {} on success
1754
-
1755
- MCP::Tool::Response.new([{ type: "text", text: "client is alive" }])
1756
- end
1757
- end
1758
- ```
1759
-
1760
- `#ping` raises `MCP::Server::ValidationError` when the client returns a `result`
1761
- that is not a Hash. Transport-level errors (e.g., the client returning a JSON-RPC error)
1762
- propagate as exceptions raised by the transport layer.
1763
-
1764
- #### Client-Side
1765
-
1766
- `MCP::Client` exposes `ping` to send a ping to the server:
1767
-
1768
- ```ruby
1769
- client = MCP::Client.new(transport: transport)
1770
- client.ping # => {} on success
1771
- ```
1772
-
1773
- `#ping` raises `MCP::Client::ServerError` when the server returns a JSON-RPC error.
1774
- It raises `MCP::Client::ValidationError` when the response `result` is missing or
1775
- is not a Hash (matching the spec requirement that `result` be an object).
1776
- Transport-level errors (for example, `MCP::Client::Stdio`'s `read_timeout:` firing)
1777
- propagate as exceptions raised by the transport layer.
1778
-
1779
- ### Progress
1780
-
1781
- The MCP Ruby SDK supports progress tracking for long-running tool operations,
1782
- following the [MCP Progress specification](https://modelcontextprotocol.io/specification/latest/server/utilities/progress).
1783
-
1784
- #### How Progress Works
1785
-
1786
- 1. **Client Request**: The client sends a `progressToken` in the `_meta` field when calling a tool
1787
- 2. **Server Notification**: The server sends `notifications/progress` messages back to the client during tool execution
1788
- 3. **Tool Integration**: Tools call `server_context.report_progress` to report incremental progress
1789
-
1790
- #### Server-Side: Tool with Progress
1791
-
1792
- Tools that accept a `server_context:` parameter can call `report_progress` on it.
1793
- The server automatically wraps the context in an `MCP::ServerContext` instance that provides this method:
1794
-
1795
- ```ruby
1796
- class LongRunningTool < MCP::Tool
1797
- description "A tool that reports progress during execution"
1798
- input_schema(
1799
- properties: {
1800
- count: { type: "integer" },
1801
- },
1802
- required: ["count"]
1803
- )
1804
-
1805
- def self.call(count:, server_context:)
1806
- count.times do |i|
1807
- # Do work here.
1808
- server_context.report_progress(i + 1, total: count, message: "Processing item #{i + 1}")
1809
- end
1810
-
1811
- MCP::Tool::Response.new([{ type: "text", text: "Done" }])
1812
- end
1813
- end
1814
- ```
1815
-
1816
- The `server_context.report_progress` method accepts:
1817
-
1818
- - `progress` (required) — current progress value (numeric)
1819
- - `total:` (optional) — total expected value, so clients can display a percentage
1820
- - `message:` (optional) — human-readable status message
1821
-
1822
- **Key Features:**
1823
-
1824
- - Tools report progress via `server_context.report_progress`
1825
- - `report_progress` is a no-op when no `progressToken` was provided by the client
1826
- - Supports both numeric and string progress tokens
1827
-
1828
- ### Completions
1829
-
1830
- MCP spec includes [Completions](https://modelcontextprotocol.io/specification/latest/server/utilities/completion),
1831
- which enable servers to provide autocompletion suggestions for prompt arguments and resource URIs.
1832
-
1833
- To enable completions, declare the `completions` capability and register a handler:
1834
-
1835
- ```ruby
1836
- server = MCP::Server.new(
1837
- name: "my_server",
1838
- prompts: [CodeReviewPrompt],
1839
- resource_templates: [FileTemplate],
1840
- capabilities: { completions: {} },
1841
- )
1842
-
1843
- server.completion_handler do |params|
1844
- ref = params[:ref]
1845
- argument = params[:argument]
1846
- value = argument[:value]
1847
-
1848
- case ref[:type]
1849
- when "ref/prompt"
1850
- values = case argument[:name]
1851
- when "language"
1852
- ["python", "pytorch", "pyside"].select { |v| v.start_with?(value) }
1853
- else
1854
- []
1855
- end
1856
- { completion: { values: values, hasMore: false } }
1857
- when "ref/resource"
1858
- { completion: { values: [], hasMore: false } }
1859
- end
1860
- end
1861
- ```
1862
-
1863
- The handler receives a `params` hash with:
1864
-
1865
- - `ref` - The reference (`{ type: "ref/prompt", name: "..." }` or `{ type: "ref/resource", uri: "..." }`)
1866
- - `argument` - The argument being completed (`{ name: "...", value: "..." }`)
1867
- - `context` (optional) - Previously resolved arguments (`{ arguments: { ... } }`)
1868
-
1869
- The handler must return a hash with a `completion` key containing `values` (array of strings), and optionally `total` and `hasMore`.
1870
- The SDK automatically enforces the 100-item limit per the MCP specification.
1871
-
1872
- The server validates that the referenced prompt, resource, or resource template is registered before calling the handler.
1873
- Requests for unknown references return an error.
1874
-
1875
- ### Elicitation
1876
-
1877
- The MCP Ruby SDK supports [elicitation](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation),
1878
- which allows servers to request additional information from users through the client during tool execution.
1879
-
1880
- Elicitation is a **server-to-client request**. The server sends a request and blocks until the user responds via the client.
1881
-
1882
- #### Capabilities
1883
-
1884
- Clients must declare the `elicitation` capability during initialization. The server checks this before sending any elicitation request
1885
- and raises a `RuntimeError` if the client does not support it.
1886
-
1887
- For URL mode support, the client must also declare `elicitation.url` capability.
1888
-
1889
- #### Using Elicitation in Tools
1890
-
1891
- Tools that accept a `server_context:` parameter can call `create_form_elicitation` on it:
1892
-
1893
- ```ruby
1894
- server.define_tool(name: "collect_info", description: "Collect user info") do |server_context:|
1895
- result = server_context.create_form_elicitation(
1896
- message: "Please provide your name",
1897
- requested_schema: {
1898
- type: "object",
1899
- properties: { name: { type: "string" } },
1900
- required: ["name"],
1901
- },
1902
- )
1903
-
1904
- MCP::Tool::Response.new([{ type: "text", text: "Hello, #{result[:content][:name]}" }])
1905
- end
1906
- ```
1907
-
1908
- #### Form Mode
1909
-
1910
- Form mode collects structured data from the user directly through the MCP client:
1911
-
1912
- ```ruby
1913
- server.define_tool(name: "collect_contact", description: "Collect contact info") do |server_context:|
1914
- result = server_context.create_form_elicitation(
1915
- message: "Please provide your contact information",
1916
- requested_schema: {
1917
- type: "object",
1918
- properties: {
1919
- name: { type: "string", description: "Your full name" },
1920
- email: { type: "string", format: "email", description: "Your email address" },
1921
- },
1922
- required: ["name", "email"],
1923
- },
1924
- )
1925
-
1926
- text = case result[:action]
1927
- when "accept"
1928
- "Hello, #{result[:content][:name]} (#{result[:content][:email]})"
1929
- when "decline"
1930
- "User declined"
1931
- when "cancel"
1932
- "User cancelled"
1933
- end
1934
-
1935
- MCP::Tool::Response.new([{ type: "text", text: text }])
1936
- end
1937
- ```
1938
-
1939
- The `requested_schema` must be a flat object schema: a top-level `type: "object"` whose `properties` are limited to
1940
- primitive types (`string`, `number`, `integer`, `boolean`). Nested objects and arrays are not allowed, which keeps
1941
- the schema simple enough for clients to render as a form. Per the MCP specification, the client validates
1942
- the user's input against this schema before returning it, so the `content` of an `accept` response matches the requested shape.
1943
-
1944
- #### Default Values and Enums
1945
-
1946
- Properties may declare a `default` value (SEP-1034), which clients use to pre-fill the form.
1947
- String properties may declare `enum` values, optionally with human-readable `enumNames` (SEP-1330), which clients render as a choice list:
1948
-
1949
- ```ruby
1950
- server.define_tool(name: "configure_deploy", description: "Configure a deployment") do |server_context:|
1951
- result = server_context.create_form_elicitation(
1952
- message: "Configure the deployment",
1953
- requested_schema: {
1954
- type: "object",
1955
- properties: {
1956
- replicas: { type: "integer", default: 3 },
1957
- verbose: { type: "boolean", default: false },
1958
- environment: {
1959
- type: "string",
1960
- enum: ["dev", "staging", "prod"],
1961
- enumNames: ["Development", "Staging", "Production"],
1962
- default: "dev",
1963
- },
1964
- },
1965
- required: ["environment"],
1966
- },
1967
- )
1968
-
1969
- MCP::Tool::Response.new([{ type: "text", text: "Deploying to #{result[:content][:environment]}" }])
1970
- end
1971
- ```
1972
-
1973
- #### URL Mode
1974
-
1975
- URL mode directs the user to an external URL for out-of-band interactions such as OAuth flows:
1976
-
1977
- ```ruby
1978
- server.define_tool(name: "authorize_github", description: "Authorize GitHub") do |server_context:|
1979
- elicitation_id = SecureRandom.uuid
1980
-
1981
- result = server_context.create_url_elicitation(
1982
- message: "Please authorize access to your GitHub account",
1983
- url: "https://example.com/oauth/authorize?elicitation_id=#{elicitation_id}",
1984
- elicitation_id: elicitation_id,
1985
- )
1986
-
1987
- server_context.notify_elicitation_complete(elicitation_id: elicitation_id)
1988
-
1989
- MCP::Tool::Response.new([{ type: "text", text: "Authorization complete" }])
1990
- end
1991
- ```
1992
-
1993
- #### URLElicitationRequiredError
1994
-
1995
- When a tool cannot proceed until an out-of-band elicitation is completed, raise `MCP::Server::URLElicitationRequiredError`.
1996
- This returns a JSON-RPC error with code `-32042` to the client:
1997
-
1998
- ```ruby
1999
- server.define_tool(name: "access_github", description: "Access GitHub") do |server_context:|
2000
- raise MCP::Server::URLElicitationRequiredError.new([
2001
- {
2002
- mode: "url",
2003
- elicitationId: SecureRandom.uuid,
2004
- url: "https://example.com/oauth/authorize",
2005
- message: "GitHub authorization is required.",
2006
- },
2007
- ])
2008
- end
2009
- ```
2010
-
2011
- ### Logging
2012
-
2013
- The MCP Ruby SDK supports structured logging through the `notify_log_message` method, following the [MCP Logging specification](https://modelcontextprotocol.io/specification/latest/server/utilities/logging).
2014
-
2015
- The `notifications/message` notification is used for structured logging between client and server.
2016
-
2017
- #### Log Levels
2018
-
2019
- The SDK supports 8 log levels with increasing severity:
2020
-
2021
- - `debug` - Detailed debugging information
2022
- - `info` - General informational messages
2023
- - `notice` - Normal but significant events
2024
- - `warning` - Warning conditions
2025
- - `error` - Error conditions
2026
- - `critical` - Critical conditions
2027
- - `alert` - Action must be taken immediately
2028
- - `emergency` - System is unusable
2029
-
2030
- #### How Logging Works
2031
-
2032
- 1. **Client Configuration**: The client sends a `logging/setLevel` request to configure the minimum log level
2033
- 2. **Server Filtering**: The server only sends log messages at the configured level or higher severity
2034
- 3. **Notification Delivery**: Log messages are sent as `notifications/message` to the client
2035
-
2036
- For example, if the client sets the level to `"error"` (severity 4), the server will send messages with levels: `error`, `critical`, `alert`, and `emergency`.
2037
-
2038
- For more details, see the [MCP Logging specification](https://modelcontextprotocol.io/specification/latest/server/utilities/logging).
2039
-
2040
- **Usage Example:**
2041
-
2042
- ```ruby
2043
- server = MCP::Server.new(name: "my_server")
2044
- transport = MCP::Server::Transports::StdioTransport.new(server)
2045
-
2046
- # The client first configures the logging level (on the client side):
2047
- transport.send_request(
2048
- request: {
2049
- jsonrpc: "2.0",
2050
- method: "logging/setLevel",
2051
- params: { level: "info" },
2052
- id: session_id # Unique request ID within the session
2053
- }
2054
- )
2055
-
2056
- # Send log messages at different severity levels
2057
- server.notify_log_message(
2058
- data: { message: "Application started successfully" },
2059
- level: "info"
2060
- )
2061
-
2062
- server.notify_log_message(
2063
- data: { message: "Configuration file not found, using defaults" },
2064
- level: "warning"
2065
- )
2066
-
2067
- server.notify_log_message(
2068
- data: {
2069
- error: "Database connection failed",
2070
- details: { host: "localhost", port: 5432 }
2071
- },
2072
- level: "error",
2073
- logger: "DatabaseLogger" # Optional logger name
2074
- )
2075
- ```
2076
-
2077
- **Key Features:**
2078
-
2079
- - Supports 8 log levels (debug, info, notice, warning, error, critical, alert, emergency) based on https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging#log-levels
2080
- - Server has capability `logging` to send log messages
2081
- - Messages are only sent if a transport is configured
2082
- - Messages are filtered based on the client's configured log level
2083
- - If the log level hasn't been set by the client, no messages will be sent
2084
-
2085
- #### Transport Support
2086
-
2087
- - **stdio**: Notifications are sent as JSON-RPC 2.0 messages to stdout
2088
- - **Streamable HTTP**: Notifications are sent as JSON-RPC 2.0 messages over HTTP with streaming (chunked transfer or SSE)
2089
-
2090
- #### Usage Example
2091
-
2092
- ```ruby
2093
- server = MCP::Server.new(name: "my_server")
2094
-
2095
- # Default Streamable HTTP - session oriented
2096
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server)
2097
-
2098
- # When tools change, notify clients
2099
- server.define_tool(name: "new_tool") { |**args| { result: "ok" } }
2100
- server.notify_tools_list_changed
2101
- ```
2102
-
2103
- You can use Stateless Streamable HTTP, where notifications are not supported and all calls are request/response interactions.
2104
- This mode allows for easy multi-node deployment.
2105
- Set `stateless: true` in `MCP::Server::Transports::StreamableHTTPTransport.new` (`stateless` defaults to `false`):
2106
-
2107
- ```ruby
2108
- # Stateless Streamable HTTP - session-less
2109
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true)
2110
- ```
2111
-
2112
- In stateless mode, each POST is fully self-contained per SEP-2567: no `Mcp-Session-Id` is issued or required,
2113
- handlers run against an ephemeral per-request session (so client identity never leaks across requests or onto the shared server),
2114
- and repeated `initialize` requests are permitted. Request-scoped notifications such as progress and log messages are skipped
2115
- (there is no stream to deliver them), while server-to-client requests (`sampling/createMessage`, `roots/list`, `elicitation/create`) raise an error.
2116
-
2117
- You can enable JSON response mode, where the server returns `application/json` instead of `text/event-stream`.
2118
- Set `enable_json_response: true` in `MCP::Server::Transports::StreamableHTTPTransport.new`:
2119
-
2120
- ```ruby
2121
- # JSON response mode
2122
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, enable_json_response: true)
2123
- ```
2124
-
2125
- In JSON response mode, the POST response is a single JSON object, so server-to-client messages
2126
- that need to arrive during request processing are not supported:
2127
- request-scoped notifications (`progress`, `log`) are silently dropped, and all server-to-client requests
2128
- (`sampling/createMessage`, `roots/list`, `elicitation/create`) raise an error.
2129
- Session-scoped standalone notifications (`resources/updated`, `elicitation/complete`) and
2130
- broadcast notifications (`tools/list_changed`, etc.) still flow to clients connected to the GET SSE stream.
2131
- This mode is suitable for simple tool servers that do not need server-initiated requests.
2132
-
2133
- By default, stateful sessions are bounded so an `initialize` flood cannot retain sessions until memory is exhausted:
2134
- they expire after `session_idle_timeout` seconds of inactivity (default 1800, i.e. 30 minutes) and the concurrent
2135
- session count is capped at `max_sessions` (default 10000). A session's idle timer is reset by activity that touches it
2136
- (a GET, or a regular-request POST), and expired sessions are collected by a background reaper roughly once a minute,
2137
- so cleanup lags inactivity by up to that interval. At the cap, the transport first reclaims any already-expired slots
2138
- and then, if still full, rejects a new `initialize` with HTTP 503 (it does not evict an existing session).
2139
-
2140
- ```ruby
2141
- # Tune the limits
2142
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, session_idle_timeout: 900, max_sessions: 5000)
2143
-
2144
- # Opt out of expiry and/or the cap (not recommended on internet-facing deployments)
2145
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, session_idle_timeout: nil, max_sessions: nil)
2146
- ```
2147
-
2148
- Stateless mode (`stateless: true`) retains no sessions, so neither limit applies to it.
2149
-
2150
- #### Session Ownership
2151
-
2152
- `StreamableHTTPTransport` issues a random `SecureRandom.uuid` session ID and validates incoming requests by session
2153
- existence and idle timeout only. It does not bind a session to a user, because the transport never receives
2154
- an authenticated identity on its own. A caller that obtains a valid session ID could therefore act on that session,
2155
- so binding a session to a user is the deploying application's responsibility (the MCP spec frames this as a SHOULD).
2156
-
2157
- The primary control is the `session_request_validator`. It is called as `->(request, session_id) { true | false }`
2158
- on every non-`initialize` POST, GET, and DELETE against an existing session (including notification and response POSTs,
2159
- so a stolen session ID cannot, for example, POST `notifications/cancelled` against a victim's request). A falsy return
2160
- rejects the request with HTTP 403. Use it to compare the request's authenticated principal against the one recorded
2161
- when the session was created:
2162
-
2163
- ```ruby
2164
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(
2165
- server,
2166
- session_request_validator: ->(request, session_id) { owns_session?(request, session_id) },
2167
- )
2168
- ```
2169
-
2170
- Without a validator the transport does not enforce ownership. As a limited defense in depth (not authentication),
2171
- it also records the `Origin` header at `initialize` and rejects a later request whose `Origin` differs, but only
2172
- when both are present - a non-browser client that omits `Origin` (e.g. `curl` or a script) is not stopped by this check.
2173
- Enforcing ownership against a determined attacker requires supplying the validator with an authenticated principal.
2174
-
2175
- #### Request Size Limits
2176
-
2177
- `StreamableHTTPTransport` bounds how many bytes a single POST body may allocate, so a peer cannot exhaust memory
2178
- with one oversized message. A body larger than `max_request_bytes` (default 4 MiB) is rejected with HTTP 413,
2179
- and JSON nesting depth is capped. The 4 MiB default comfortably fits a typical JSON-RPC message (a 4 MiB JSON
2180
- string decodes to roughly 3 MiB of base64 payload) and matches the TypeScript SDK's 4 MB default; raise it only
2181
- if you exchange unusually large payloads:
2182
-
2183
- ```ruby
2184
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, max_request_bytes: 8 * 1024 * 1024)
2185
- ```
2186
-
2187
- ### Pagination
2188
-
2189
- The MCP Ruby SDK supports [pagination](https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/pagination)
2190
- for list operations that may return large result sets. Pagination uses string cursor tokens carrying a zero-based offset,
2191
- treated as opaque by clients: the server decides page size, and the client follows `nextCursor` until the server omits it.
2192
-
2193
- Pagination applies to `tools/list`, `prompts/list`, `resources/list`, and `resources/templates/list`.
2194
-
2195
- #### Server-Side: Enabling Pagination
2196
-
2197
- Pass `page_size:` to `MCP::Server.new` to split list responses into pages. When `page_size` is omitted (the default),
2198
- list responses contain all items in a single response, preserving the pre-pagination behavior.
2199
-
2200
- ```ruby
2201
- server = MCP::Server.new(
2202
- name: "my_server",
2203
- tools: tools,
2204
- page_size: 50,
2205
- )
2206
- ```
2207
-
2208
- When `page_size` is set, list responses include a `nextCursor` field whenever more pages are available:
2209
-
2210
- ```json
2211
- {
2212
- "jsonrpc": "2.0",
2213
- "id": 1,
2214
- "result": {
2215
- "tools": [
2216
- { "name": "example_tool" }
2217
- ],
2218
- "nextCursor": "50"
2219
- }
2220
- }
2221
- ```
2222
-
2223
- Invalid cursors (e.g. non-numeric, negative, or out-of-range) are rejected with JSON-RPC error code `-32602 (Invalid params)` per the MCP specification.
2224
-
2225
- #### Client-Side: Iterating Pages
2226
-
2227
- `MCP::Client` exposes `list_tools`, `list_prompts`, `list_resources`, and `list_resource_templates`.
2228
- **Each call issues exactly one `*/list` JSON-RPC request and returns exactly one page** — not the full collection.
2229
- The returned result object (`MCP::Client::ListToolsResult` etc.) exposes the page items and the next cursor as method accessors:
2230
-
2231
- ```ruby
2232
- client = MCP::Client.new(transport: transport)
2233
-
2234
- cursor = nil
2235
- loop do
2236
- page = client.list_tools(cursor: cursor)
2237
- page.tools.each { |tool| process(tool) }
2238
- cursor = page.next_cursor
2239
- break unless cursor
2240
- end
2241
- ```
2242
-
2243
- The same pattern applies to `list_prompts` (`page.prompts`), `list_resources` (`page.resources`), and
2244
- `list_resource_templates` (`page.resource_templates`). `next_cursor` is `nil` on the final page.
2245
-
2246
- Because a single call returns a single page, how many items come back depends on the server's `page_size` configuration:
2247
-
2248
- | Server `page_size` | `client.list_tools(cursor: nil)` |
2249
- |--------------------|---------------------------------------------------------------------|
2250
- | Not set (default) | Returns every item in one response. `next_cursor` is `nil`. |
2251
- | Set to `N` | Returns the first `N` items. `next_cursor` is set for continuation. |
2252
-
2253
- If your application needs the complete collection regardless of how the server is configured, either loop on
2254
- `next_cursor` as shown above, or use the whole-collection methods described below.
2255
-
2256
- #### Fetching the Complete Collection
2257
-
2258
- `client.tools`, `client.resources`, `client.resource_templates`, and `client.prompts` auto-iterate
2259
- through all pages and return a plain array of items, guaranteeing the full collection regardless
2260
- of the server's `page_size` setting. When a server paginates, they issue multiple JSON-RPC round
2261
- trips per call and break out of the pagination loop if the server returns the same `nextCursor`
2262
- twice in a row as a safety measure.
2263
-
2264
- ```ruby
2265
- tools = client.tools # => Array<MCP::Client::Tool> of every tool on the server.
2266
- ```
2267
-
2268
- Use these when you want the complete list; use `list_tools(cursor:)` etc. when you need
2269
- fine-grained iteration (e.g. to stream-process pages without loading everything into memory).
2270
-
2271
- #### List Result Caching (`ttlMs` / `cacheScope`)
2272
-
2273
- Per SEP-2549, list and read results can carry cache hints telling clients how long a result stays fresh (`ttlMs`, max-age semantics in milliseconds;
2274
- `0` means do not cache) and whether shared intermediaries may cache it (`cacheScope`: `"public"` or `"private"`).
2275
-
2276
- Emission is opt-in: pass `ttl_ms:` and/or `cache_scope:` to `MCP::Server.new` and both fields are added to `tools/list`, `prompts/list`, `resources/list`,
2277
- `resources/templates/list`, and `resources/read` results (a missing field is filled with the defaults `ttlMs: 0` / `cacheScope: "public"`).
2278
- When neither is set, responses are serialized exactly as before.
2279
-
2280
- ```ruby
2281
- server = MCP::Server.new(
2282
- name: "my_server",
2283
- tools: tools,
2284
- ttl_ms: 60_000, # results stay fresh for one minute
2285
- cache_scope: "private", # only the requesting client may cache them
2286
- )
2287
- ```
2288
-
2289
- A `resources_read_handler` can override the hints per result by returning a full result hash instead of bare contents:
2290
-
2291
- ```ruby
2292
- server.resources_read_handler do |params|
2293
- { contents: [{ uri: params[:uri], mimeType: "text/plain", text: "..." }], ttlMs: 5_000 }
2294
- end
2295
- ```
2296
-
2297
- On the client, the values are surfaced on the paginated result structs as `ttl_ms` and `cache_scope`:
2298
-
2299
- ```ruby
2300
- page = client.list_tools
2301
- page.ttl_ms # => 60000 (nil when the server sent no hint)
2302
- page.cache_scope # => "private"
2303
- ```
2304
-
2305
- ### Advanced
2306
-
2307
- #### Custom Methods
2308
-
2309
- The server allows you to define custom JSON-RPC methods beyond the standard MCP protocol methods using the `define_custom_method` method:
2310
-
2311
- ```ruby
2312
- server = MCP::Server.new(name: "my_server")
2313
-
2314
- # Define a custom method that returns a result
2315
- server.define_custom_method(method_name: "add") do |params|
2316
- params[:a] + params[:b]
2317
- end
2318
-
2319
- # Define a custom notification method (returns nil)
2320
- server.define_custom_method(method_name: "notify") do |params|
2321
- # Process notification
2322
- nil
2323
- end
2324
- ```
2325
-
2326
- **Key Features:**
2327
-
2328
- - Accepts any method name as a string
2329
- - Block receives the request parameters as a hash
2330
- - Can handle both regular methods (with responses) and notifications
2331
- - Prevents overriding existing MCP protocol methods
2332
- - Supports instrumentation callbacks for monitoring
2333
-
2334
- **Usage Example:**
2335
-
2336
- ```ruby
2337
- # Client request
2338
- {
2339
- "jsonrpc": "2.0",
2340
- "id": 1,
2341
- "method": "add",
2342
- "params": { "a": 5, "b": 3 }
2343
- }
2344
-
2345
- # Server response
2346
- {
2347
- "jsonrpc": "2.0",
2348
- "id": 1,
2349
- "result": 8
2350
- }
2351
- ```
2352
-
2353
- **Error Handling:**
2354
-
2355
- - Raises `MCP::Server::MethodAlreadyDefinedError` if trying to override an existing method
2356
- - Supports the same exception reporting and instrumentation as standard methods
2357
-
2358
- ## Building an MCP Client
2359
-
2360
- The `MCP::Client` class provides an interface for interacting with MCP servers.
2361
-
2362
- This class supports:
2363
-
2364
- - Liveness check via the `ping` method (`MCP::Client#ping`)
2365
- - Tool listing via the `tools/list` method (`MCP::Client#tools`)
2366
- - Tool invocation via the `tools/call` method (`MCP::Client#call_tool`)
2367
- - Resource listing via the `resources/list` method (`MCP::Client#resources`)
2368
- - Resource template listing via the `resources/templates/list` method (`MCP::Client#resource_templates`)
2369
- - Resource reading via the `resources/read` method (`MCP::Client#read_resource`)
2370
- - Prompt listing via the `prompts/list` method (`MCP::Client#prompts`)
2371
- - Prompt retrieval via the `prompts/get` method (`MCP::Client#get_prompt`)
2372
- - Completion requests via the `completion/complete` method (`MCP::Client#complete`)
2373
- - Automatic JSON-RPC 2.0 message formatting
2374
- - UUID request ID generation
2375
-
2376
- Clients are initialized with a transport layer instance that handles the low-level communication mechanics.
2377
- Authorization is handled by the transport layer.
2378
-
2379
- ## Transport Layer Interface
2380
-
2381
- If the transport layer you need is not included in the gem, you can build and pass your own instances so long as they conform to the following interface:
2382
-
2383
- ```ruby
2384
- class CustomTransport
2385
- # Sends a JSON-RPC request to the server and returns the raw response.
2386
- #
2387
- # @param request [Hash] A complete JSON-RPC request object.
2388
- # https://www.jsonrpc.org/specification#request_object
2389
- # @return [Hash] A hash modeling a JSON-RPC response object.
2390
- # https://www.jsonrpc.org/specification#response_object
2391
- def send_request(request:)
2392
- # Your transport-specific logic here
2393
- # - HTTP: POST to endpoint with JSON body
2394
- # - WebSocket: Send message over WebSocket
2395
- # - stdio: Write to stdout, read from stdin
2396
- # - etc.
2397
- end
2398
- end
2399
- ```
2400
-
2401
- ### Stdio Transport Layer
2402
-
2403
- Use the `MCP::Client::Stdio` transport to interact with MCP servers running as subprocesses over standard input/output.
2404
-
2405
- `MCP::Client::Stdio.new` accepts the following keyword arguments:
2406
-
2407
- | Parameter | Required | Description |
2408
- |---|---|---|
2409
- | `command:` | Yes | The command to spawn the server process (e.g., `"ruby"`, `"bundle"`, `"npx"`). |
2410
- | `args:` | No | An array of arguments passed to the command. Defaults to `[]`. |
2411
- | `env:` | No | A hash of environment variables to set for the server process. Defaults to `nil`. |
2412
- | `read_timeout:` | No | Timeout in seconds for waiting for a server response. Defaults to `nil` (no timeout). |
2413
- | `max_line_bytes:` | No | Maximum byte length of a single newline-delimited response frame. A frame that reaches this limit without a newline is rejected as a transport error, preventing unbounded memory growth from a server that never emits a newline. Defaults to `4 * 1024 * 1024` (4 MiB). |
2414
-
2415
- Example usage:
2416
-
2417
- ```ruby
2418
- stdio_transport = MCP::Client::Stdio.new(
2419
- command: "bundle",
2420
- args: ["exec", "ruby", "path/to/server.rb"],
2421
- env: { "API_KEY" => "my_secret_key" },
2422
- read_timeout: 30
2423
- )
2424
- client = MCP::Client.new(transport: stdio_transport)
2425
-
2426
- # Perform the MCP initialization handshake before sending any requests.
2427
- client.connect
2428
-
2429
- # List available tools.
2430
- tools = client.tools
2431
- tools.each do |tool|
2432
- puts "Tool: #{tool.name} - #{tool.description}"
2433
- end
2434
-
2435
- # Call a specific tool.
2436
- response = client.call_tool(
2437
- tool: tools.first,
2438
- arguments: { message: "Hello, world!" }
2439
- )
2440
-
2441
- # Close the transport when done.
2442
- stdio_transport.close
2443
- ```
2444
-
2445
- The stdio transport automatically handles:
2446
-
2447
- - Spawning the server process with `Open3.popen3`
2448
- - MCP protocol initialization handshake (`initialize` request + `notifications/initialized`)
2449
- - JSON-RPC 2.0 message framing over newline-delimited JSON
2450
-
2451
- ### HTTP Transport Layer
2452
-
2453
- Use the `MCP::Client::HTTP` transport to interact with MCP servers using simple HTTP requests.
2454
-
2455
- You'll need to add `faraday` as a dependency in order to use the HTTP transport layer. Add `event_stream_parser` as well if the server uses SSE (`text/event-stream`) responses:
2456
-
2457
- ```ruby
2458
- gem 'mcp'
2459
- gem 'faraday', '>= 2.0'
2460
- gem 'event_stream_parser', '>= 1.0' # optional, required only for SSE responses
2461
- ```
2462
-
2463
- Example usage:
2464
-
2465
- ```ruby
2466
- http_transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp")
2467
- client = MCP::Client.new(transport: http_transport)
2468
-
2469
- # Perform the MCP initialization handshake before sending any requests.
2470
- client.connect
2471
-
2472
- # List available tools
2473
- tools = client.tools
2474
- tools.each do |tool|
2475
- puts <<~TOOL_INFORMATION
2476
- Tool: #{tool.name}
2477
- Description: #{tool.description}
2478
- Input Schema: #{tool.input_schema}
2479
- TOOL_INFORMATION
2480
- end
2481
-
2482
- # Call a specific tool
2483
- response = client.call_tool(
2484
- tool: tools.first,
2485
- arguments: { message: "Hello, world!" }
2486
- )
2487
-
2488
- # Call a tool with progress tracking.
2489
- response = client.call_tool(
2490
- tool: tools.first,
2491
- arguments: { count: 10 },
2492
- progress_token: "my-progress-token"
2493
- )
2494
- ```
2495
-
2496
- The server will send `notifications/progress` back to the client during execution.
2497
-
2498
- `MCP::Client::HTTP.new` accepts an optional `max_message_bytes:` keyword that caps the bytes buffered in memory for a single message from the server -
2499
- an SSE event or a JSON response body. A message that reaches this limit before completing is rejected as a transport error, preventing unbounded memory growth from
2500
- a server that never terminates an SSE event. It defaults to `4 * 1024 * 1024` (4 MiB); raise it if your server returns larger responses.
2501
-
2502
- #### Server-to-Client Requests (Elicitation)
2503
-
2504
- Servers can send requests back to the client while one of the client's own requests is in flight - for example,
2505
- [`elicitation/create`](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation) to ask the user for additional input during a tool call.
2506
- Register a handler and advertise the capability on `connect` to respond to them:
2507
-
2508
- ```ruby
2509
- client.connect(capabilities: { elicitation: {} })
2510
-
2511
- client.on_elicitation do |params|
2512
- {
2513
- action: "accept",
2514
- # Fill fields omitted by the user with the schema's `default` values (SEP-1034)
2515
- content: MCP::Client::Elicitation.apply_defaults(params["requestedSchema"]),
2516
- }
2517
- end
2518
- ```
2519
-
2520
- Registering a handler opens a standalone HTTP GET SSE stream on a background thread
2521
- ([listening for messages from the server](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#listening-for-messages-from-the-server)),
2522
- since servers deliver requests that are not tied to a client request on that stream. Server requests with no registered handler are answered with
2523
- a JSON-RPC `-32601` (method not found) error. To handle methods other than `elicitation/create`, register directly on the transport with
2524
- `http_transport.on_server_request("method/name") { |params| ... }`.
2525
-
2526
- #### Server-to-Client Requests (Sampling)
2527
-
2528
- Servers can also request an LLM completion from the client with [`sampling/createMessage`](https://modelcontextprotocol.io/specification/2025-11-25/client/sampling),
2529
- letting a server leverage the client's model access without its own API keys.
2530
-
2531
- > MCP Sampling is deprecated as of protocol version `2026-07-28` (SEP-2577), while remaining fully supported under `2025-11-25`.
2532
- > Register this handler to interoperate with servers that still send sampling requests during the deprecation window;
2533
- > new servers should call LLM provider APIs directly.
2534
-
2535
- Register a handler and advertise the capability on `connect`:
2536
-
2537
- ```ruby
2538
- client.connect(capabilities: { sampling: {} })
2539
-
2540
- client.on_sampling do |params|
2541
- completion = my_llm.complete(params["messages"], max_tokens: params["maxTokens"])
2542
- {
2543
- role: "assistant",
2544
- content: { type: "text", text: completion.text },
2545
- model: completion.model,
2546
- stopReason: "endTurn",
2547
- }
2548
- end
2549
- ```
2550
-
2551
- For trust and safety, the spec recommends a human in the loop able to review, edit, or reject the request and the generated response.
2552
- To reject a request, raise `MCP::Client::ServerRequestError` with the spec's user-rejection code `-1`:
2553
-
2554
- ```ruby
2555
- client.on_sampling do |params|
2556
- raise MCP::Client::ServerRequestError.new("User rejected sampling request", code: -1) unless approved?(params)
2557
-
2558
- generate_completion(params)
2559
- end
2560
- ```
2561
-
2562
- Use `capabilities: { sampling: { tools: {} } }` to receive tool-enabled sampling requests. Like elicitation, this uses the same standalone GET SSE listening stream.
2563
-
2564
- #### HTTP Authorization
2565
-
2566
- By default, the HTTP transport layer provides no authentication to the server, but you can provide custom headers if you need authentication. For example, to use Bearer token authentication:
2567
-
2568
- ```ruby
2569
- http_transport = MCP::Client::HTTP.new(
2570
- url: "https://api.example.com/mcp",
2571
- headers: {
2572
- "Authorization" => "Bearer my_token"
2573
- }
2574
- )
2575
-
2576
- client = MCP::Client.new(transport: http_transport)
2577
- client.tools # will make the call using Bearer auth
2578
- ```
2579
-
2580
- You can add any custom headers needed for your authentication scheme, or for any other purpose. The client will include these headers on every request.
2581
-
2582
- #### OAuth 2.1 Authorization
2583
-
2584
- When an MCP server enforces the [MCP Authorization spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization),
2585
- pass an `MCP::Client::OAuth::Provider` to the transport instead of a static `Authorization` header. The transport will:
2586
-
2587
- - Send `Authorization: Bearer <access_token>` on every request when a token is available.
2588
- - On a `401 Unauthorized`, parse the `WWW-Authenticate` header, discover the authorization server (Protected Resource Metadata + RFC 8414 Authorization Server Metadata),
2589
- perform Dynamic Client Registration if needed, run the OAuth 2.1 Authorization Code flow with PKCE (S256), and retry the failed request with the acquired token.
2590
- - Fall back to the legacy 2025-03-26 discovery when the server publishes no Protected Resource Metadata, matching the TypeScript and Python SDKs: the MCP server's origin acts
2591
- as the authorization base URL, its metadata is fetched from `<origin>/.well-known/oauth-authorization-server` without the RFC 8414 issuer byte-match (which the legacy spec predates),
2592
- and when even that is absent the spec's default endpoints `/authorize`, `/token`, and `/register` at the origin are used with PKCE S256 assumed.
2593
- - On subsequent 401s with a saved `refresh_token`, exchange it at the token endpoint before falling back to the full interactive flow (RFC 6749 Section 6).
2594
- - On a `403 Forbidden` whose `WWW-Authenticate` header carries `error="insufficient_scope"` (OAuth 2.0 step-up, RFC 6750 Section 3.1 and the MCP scope-selection-strategy),
2595
- run a fresh authorization request for the union of the currently granted scope and the scope named in the challenge, then retry the failed request once.
2596
- The refresh path is bypassed because refreshing would re-issue the same scope set the server just rejected. A `403` without that challenge is surfaced unchanged.
2597
- - Request the `offline_access` scope when `client_metadata[:grant_types]` includes `refresh_token` and the authorization server advertises `offline_access` in its metadata
2598
- `scopes_supported` (SEP-2207). This is what lets the server issue the `refresh_token` used above. As an SDK-level safeguard, when the authorization server does not advertise
2599
- `offline_access` the scope is also stripped from any other source (challenge, PRM, or provider-supplied scope) so a server that does not support it never receives it.
2600
-
2601
- ```ruby
2602
- require "mcp"
2603
-
2604
- provider = MCP::Client::OAuth::Provider.new(
2605
- client_metadata: {
2606
- client_name: "My MCP App",
2607
- redirect_uris: ["http://localhost:3030/callback"],
2608
- grant_types: ["authorization_code", "refresh_token"],
2609
- response_types: ["code"],
2610
- token_endpoint_auth_method: "none",
2611
- },
2612
- redirect_uri: "http://localhost:3030/callback",
2613
- redirect_handler: ->(authorization_url) {
2614
- # Send the user to the authorization URL - typically `Launchy.open(authorization_url)`
2615
- # or a manual `puts authorization_url` in CLI tools.
2616
- },
2617
- callback_handler: -> {
2618
- # Capture the redirect (for example, by running a small HTTP listener on
2619
- # `redirect_uri`) and return [code, state] from the query string.
2620
- },
2621
- )
2622
-
2623
- transport = MCP::Client::HTTP.new(
2624
- url: "https://api.example.com/mcp",
2625
- oauth: provider,
2626
- )
2627
- client = MCP::Client.new(transport: transport)
2628
- client.connect # `initialize` is sent here; if the server replies 401 the OAuth flow runs and the handshake is retried with the acquired token
2629
- client.tools
2630
- ```
2631
-
2632
- Required keyword arguments to `Provider.new`:
2633
-
2634
- - `client_metadata`: Hash sent to the authorization server's Dynamic Client Registration endpoint. Must include `redirect_uris`, `grant_types`, `response_types`,
2635
- `token_endpoint_auth_method`. `redirect_uri` (below) must appear in this list, otherwise the constructor raises `Provider::UnregisteredRedirectURIError`.
2636
- When `application_type` is omitted, the SDK infers `"native"` or `"web"` from `redirect_uris` per SEP-837 before registering (loopback or custom-scheme URIs are native);
2637
- an explicit value always wins.
2638
- - `redirect_uri`: String. Must use HTTPS or be a loopback URL (`localhost`, `127.0.0.0/8`, `::1`); other values raise `Provider::InsecureRedirectURIError`.
2639
- - `redirect_handler`: Callable invoked with the fully-built authorization `URI`. Typically opens the user's browser.
2640
- - `callback_handler`: Callable that returns `[code, state]` or `[code, state, iss]` after the user is redirected back to `redirect_uri`. Returning the 3-element form
2641
- (with `iss` set to the RFC 9207 `iss` parameter from the redirect, or `nil` when absent) opts into SEP-2468 issuer validation: a present `iss` must match
2642
- the authorization server's issuer, and a missing one is rejected when the server advertises `authorization_response_iss_parameter_supported`.
2643
-
2644
- Optional keyword arguments:
2645
-
2646
- - `scope`: Space-separated scopes to request when the server's `WWW-Authenticate` does not specify one.
2647
- - `storage`: Object responding to `tokens`, `save_tokens(t)`, `client_information`, `save_client_information(info)`. Defaults to `MCP::Client::OAuth::InMemoryStorage`,
2648
- which keeps credentials in process memory only. Persisted `client_information` is stamped with an `"issuer"` member binding it to the authorization server that
2649
- issued it (SEP-2352): when the server's authorization server changes, the SDK discards the stale registration and its tokens and re-registers automatically
2650
- (portable CIMD `client_id`s are kept). Treat the hash as opaque and persist it as-is.
2651
- - `client_id_metadata_document_url`: URL where you publish a Client ID Metadata Document
2652
- (`draft-ietf-oauth-client-id-metadata-document` and the MCP authorization specification).
2653
- When the authorization server advertises `client_id_metadata_document_supported: true`,
2654
- the SDK uses this URL as the OAuth `client_id` and skips Dynamic Client Registration.
2655
- Spec-required: the URL MUST be `https://` with a non-root path and MUST NOT include a fragment,
2656
- userinfo, or `.`/`..` segments. The SDK additionally rejects query strings (the draft only marks
2657
- them SHOULD NOT include, but the SDK refuses to send any) for `client_id` stability.
2658
- Any of these failures raise `Provider::InvalidClientIDMetadataDocumentURLError`. The CIMD document
2659
- served at the URL is a separate JSON artifact from the `client_metadata` keyword above:
2660
- the DCR `client_metadata` MUST NOT include `client_id`, while the CIMD document MUST include
2661
- `client_id` set to the document URL, `client_name`, and `redirect_uris` covering `redirect_uri`.
2662
-
2663
- To persist credentials across restarts, supply your own storage:
2664
-
2665
- ```ruby
2666
- class FileTokenStorage
2667
- def initialize(path)
2668
- @path = path
2669
- end
2670
-
2671
- def tokens
2672
- read["tokens"]
2673
- end
2674
-
2675
- def save_tokens(value)
2676
- write("tokens" => value)
2677
- end
2678
-
2679
- def client_information
2680
- read["client"]
2681
- end
2682
-
2683
- def save_client_information(value)
2684
- write("client" => value)
2685
- end
2686
-
2687
- private
2688
-
2689
- def read
2690
- File.exist?(@path) ? JSON.parse(File.read(@path)) : {}
2691
- end
2692
-
2693
- def write(updates)
2694
- File.write(@path, JSON.dump(read.merge(updates)))
2695
- end
2696
- end
2697
-
2698
- provider = MCP::Client::OAuth::Provider.new(
2699
- # ... required keywords ...
2700
- storage: FileTokenStorage.new(File.expand_path("~/.config/my-app/oauth.json")),
2701
- )
2702
- ```
2703
-
2704
- ##### Client Credentials Grant
2705
-
2706
- For a confidential machine-to-machine client (no user, no browser redirect), use `MCP::Client::OAuth::ClientCredentialsProvider` instead of `Provider`.
2707
- The transport discovers the authorization server the same way, then exchanges the OAuth 2.1 `client_credentials` grant (RFC 6749 Section 4.4) at
2708
- the token endpoint. There is no authorization request, PKCE, or `offline_access`, because the grant does not issue a refresh token.
2709
-
2710
- ```ruby
2711
- provider = MCP::Client::OAuth::ClientCredentialsProvider.new(
2712
- client_id: "my-service",
2713
- client_secret: ENV.fetch("MCP_CLIENT_SECRET"),
2714
- # token_endpoint_auth_method: "client_secret_basic" (default) or "client_secret_post"
2715
- # scope: "mcp:read mcp:write" (optional; used when the server does not advertise scopes)
2716
- )
2717
-
2718
- transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp", oauth: provider)
2719
- ```
2720
-
2721
- Keyword arguments:
2722
-
2723
- - `client_id`, `client_secret`: Required. The grant is for confidential clients, so a credential is mandatory.
2724
- - `token_endpoint_auth_method`: `"client_secret_basic"` (default) or `"client_secret_post"`. `"none"` is rejected with `ClientCredentialsProvider::InvalidCredentialsError`.
2725
- - `scope`, `storage`: Optional, same meaning as on `Provider`.
2726
-
2727
- ##### Cross-App Access (JWT Bearer) Grant
2728
-
2729
- For enterprise MCP deployments where an identity provider (IdP) governs authorization (SEP-990), use `MCP::Client::OAuth::CrossAppAccessProvider` instead of `Provider`.
2730
- The client exchanges an IdP-issued ID token for an Identity Assertion Authorization Grant (ID-JAG) at the IdP via RFC 8693 token exchange, then presents the ID-JAG
2731
- to the MCP authorization server with the RFC 7523 `jwt-bearer` grant, authenticating with `client_secret_basic`. There is no authorization request, PKCE, DCR, or `offline_access`.
2732
- Mirrors `CrossAppAccessProvider` and `requestJwtAuthorizationGrant` in the TypeScript SDK.
2733
-
2734
- `MCP::Client::OAuth::IDJAGTokenExchange.request` performs the RFC 8693 exchange at the IdP token endpoint. Wrap it in a callable so the same provider can plug into
2735
- an enterprise secret store or a test double without changing the transport wiring.
2736
-
2737
- ```ruby
2738
- provider = MCP::Client::OAuth::CrossAppAccessProvider.new(
2739
- client_id: "my-mcp-client",
2740
- client_secret: ENV.fetch("MCP_CLIENT_SECRET"),
2741
- assertion_provider: ->(audience:, resource:) {
2742
- MCP::Client::OAuth::IDJAGTokenExchange.request(
2743
- token_endpoint: "https://idp.example.com/token",
2744
- id_token: ENV.fetch("IDP_ID_TOKEN"),
2745
- client_id: "my-idp-client",
2746
- audience: audience,
2747
- resource: resource,
2748
- )
2749
- },
2750
- # scope: "mcp:read mcp:write" (optional; used when neither WWW-Authenticate nor PRM specify one)
2751
- )
2752
-
2753
- transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp", oauth: provider)
2754
- ```
2755
-
2756
- Keyword arguments:
2757
-
2758
- - `client_id`, `client_secret`: Required. The `jwt-bearer` grant authenticates with `client_secret_basic` at the MCP authorization server.
2759
- - `assertion_provider`: Required. Callable invoked as `call(audience:, resource:)` and returning the ID-JAG assertion.
2760
- `audience` is the MCP authorization server's validated issuer identifier; `resource` is the canonical MCP server URL (RFC 8707).
2761
- Passing both through to `IDJAGTokenExchange.request` covers the common case.
2762
- - `scope`, `storage`: Optional, same meaning as on `Provider`.
2763
-
2764
- ##### Communication Security
2765
-
2766
- When `oauth:` is set, the MCP transport URL and every OAuth-facing URL (PRM, Authorization Server metadata, `authorization_endpoint`, `token_endpoint`, `registration_endpoint`,
2767
- `redirect_uri`) must use HTTPS or a loopback host. Non-loopback `http://` URLs are rejected at the SDK boundary so a bearer token is never sent over plain HTTP to a remote host.
2768
-
2769
- The transport also snapshots the canonicalized origin, path, and query string of the MCP URL at `initialize` time and re-checks them on every outgoing request through
2770
- a Faraday middleware that runs after any user-supplied customizer. That means any URL swap raises `MCP::Client::HTTP::InsecureURLError` before the request reaches the adapter,
2771
- whether the swap was triggered by
2772
- `instance_variable_set(:@url, ...)`, by a Faraday customizer rewriting `url_prefix`, or by a custom middleware rewriting `env.url` (including just `env.url.query`) at request time,
2773
- and whether the new URL is `http://` *or* `https://` to a different host or tenant.
2774
-
2775
- #### Customizing the Faraday Connection
2776
-
2777
- You can pass a block to `MCP::Client::HTTP.new` to customize the underlying Faraday connection.
2778
- The block is called after the default middleware is configured, so you can add middleware or swap the HTTP adapter:
2779
-
2780
- ```ruby
2781
- http_transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp") do |faraday|
2782
- faraday.use MyApp::Middleware::HttpRecorder
2783
- faraday.adapter :typhoeus
2784
- end
2785
- ```
2786
-
2787
- ### Tool Objects
2788
-
2789
- The client provides a wrapper class for tools returned by the server:
2790
-
2791
- - `MCP::Client::Tool` - Represents a single tool with its metadata
2792
-
2793
- This class provides easy access to tool properties like name, description, input schema, and output schema.
2794
-
2795
- ### Multi-Round-Trip Results (Experimental, SEP-2322)
2796
-
2797
- The MCP 2026-07-28 draft replaces in-flight server-to-client requests with Multi Round-Trip Requests: instead of issuing `sampling/createMessage`, `roots/list`,
2798
- 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
2799
- and an opaque `requestState`; the client fulfills the requests and re-issues the original request with `inputResponses` and the echoed `requestState`.
2800
-
2801
- The Ruby client recognizes such results and raises `MCP::Client::InputRequiredError` instead of returning them as if they were final. The error exposes `input_requests`, `request_state`,
2802
- and the raw `result`; automatic resumption is not implemented yet, so callers respond manually if they opt into the draft flow. `MCP::ResultType::COMPLETE` and `MCP::ResultType::INPUT_REQUIRED`
2803
- are provided for forward compatibility. Servers on stable protocol versions never send `resultType`, so existing behavior is unchanged.
2804
-
2805
- ## Conformance Testing
2806
-
2807
- The `conformance/` directory contains a test server and runner that validate the SDK against the MCP specification using [`@modelcontextprotocol/conformance`](https://github.com/modelcontextprotocol/conformance).
2808
-
2809
- See [conformance/README.md](conformance/README.md) for usage instructions.
2810
-
2811
- ## Documentation
2812
-
2813
- - [SDK API documentation](https://rubydoc.info/gems/mcp)
2814
- - [Model Context Protocol documentation](https://modelcontextprotocol.io)
139
+ This project is licensed under the Apache License 2.0 for new contributions, with existing code under MIT. See the [LICENSE](https://github.com/modelcontextprotocol/ruby-sdk/blob/main/LICENSE) file for details.