mcp 0.25.0 → 1.4.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 requests, 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,2534 +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
- ### Prompts
876
-
877
- 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.
878
-
879
- The `MCP::Prompt` class provides three ways to create prompts:
880
-
881
- 1. As a class definition with metadata:
882
-
883
- ```ruby
884
- class MyPrompt < MCP::Prompt
885
- prompt_name "my_prompt" # Optional - defaults to underscored class name
886
- title "My Prompt"
887
- description "This prompt performs specific functionality..."
888
- arguments [
889
- MCP::Prompt::Argument.new(
890
- name: "message",
891
- title: "Message Title",
892
- description: "Input message",
893
- required: true
894
- )
895
- ]
896
- meta({ version: "1.0", category: "example" })
897
-
898
- class << self
899
- def template(args, server_context:)
900
- MCP::Prompt::Result.new(
901
- description: "Response description",
902
- messages: [
903
- MCP::Prompt::Message.new(
904
- role: "user",
905
- content: MCP::Content::Text.new("User message")
906
- ),
907
- MCP::Prompt::Message.new(
908
- role: "assistant",
909
- content: MCP::Content::Text.new(args["message"])
910
- )
911
- ]
912
- )
913
- end
914
- end
915
- end
916
-
917
- prompt = MyPrompt
918
- ```
919
-
920
- 2. Using the `MCP::Prompt.define` method:
921
-
922
- ```ruby
923
- prompt = MCP::Prompt.define(
924
- name: "my_prompt",
925
- title: "My Prompt",
926
- description: "This prompt performs specific functionality...",
927
- arguments: [
928
- MCP::Prompt::Argument.new(
929
- name: "message",
930
- title: "Message Title",
931
- description: "Input message",
932
- required: true
933
- )
934
- ],
935
- meta: { version: "1.0", category: "example" }
936
- ) do |args, server_context:|
937
- MCP::Prompt::Result.new(
938
- description: "Response description",
939
- messages: [
940
- MCP::Prompt::Message.new(
941
- role: "user",
942
- content: MCP::Content::Text.new("User message")
943
- ),
944
- MCP::Prompt::Message.new(
945
- role: "assistant",
946
- content: MCP::Content::Text.new(args["message"])
947
- )
948
- ]
949
- )
950
- end
951
- ```
952
-
953
- 3. Using the `MCP::Server#define_prompt` method:
954
-
955
- ```ruby
956
- server = MCP::Server.new
957
- server.define_prompt(
958
- name: "my_prompt",
959
- description: "This prompt performs specific functionality...",
960
- arguments: [
961
- Prompt::Argument.new(
962
- name: "message",
963
- title: "Message Title",
964
- description: "Input message",
965
- required: true
966
- )
967
- ],
968
- meta: { version: "1.0", category: "example" }
969
- ) do |args, server_context:|
970
- Prompt::Result.new(
971
- description: "Response description",
972
- messages: [
973
- Prompt::Message.new(
974
- role: "user",
975
- content: Content::Text.new("User message")
976
- ),
977
- Prompt::Message.new(
978
- role: "assistant",
979
- content: Content::Text.new(args["message"])
980
- )
981
- ]
982
- )
983
- end
984
- ```
985
-
986
- The server_context parameter is the server_context passed into the server and can be used to pass per request information,
987
- e.g. around authentication state or user preferences.
988
-
989
- ### Key Components
990
-
991
- - `MCP::Prompt::Argument` - Defines input parameters for the prompt template with name, title, description, and required flag
992
- - `MCP::Prompt::Message` - Represents a message in the conversation with a role and content
993
- - `MCP::Prompt::Result` - The output of a prompt template containing description and messages
994
- - `MCP::Content::Text` - Text content for messages
995
-
996
- ### Usage
997
-
998
- Register prompts with the MCP server:
999
-
1000
- ```ruby
1001
- server = MCP::Server.new(
1002
- name: "my_server",
1003
- prompts: [MyPrompt],
1004
- server_context: { user_id: current_user.id },
1005
- )
1006
- ```
1007
-
1008
- The server will handle prompt listing and execution through the MCP protocol methods:
1009
-
1010
- - `prompts/list` - Lists all registered prompts and their schemas
1011
- - `prompts/get` - Retrieves and executes a specific prompt with arguments
1012
-
1013
- ### Resources
1014
-
1015
- MCP spec includes [Resources](https://modelcontextprotocol.io/specification/latest/server/resources).
1016
-
1017
- ### Reading Resources
1018
-
1019
- Like tools and prompts, resources can be defined in three ways.
1020
-
1021
- 1. As a class that inherits from `MCP::Resource`, implementing `contents` to serve the resource body:
1022
-
1023
- ```ruby
1024
- class MyResource < MCP::Resource
1025
- uri "https://example.com/my_resource"
1026
- resource_name "my-resource"
1027
- title "My Resource"
1028
- description "Lorem ipsum dolor sit amet"
1029
- mime_type "text/html"
1030
-
1031
- class << self
1032
- def contents
1033
- [MCP::Resource::TextContents.new(
1034
- uri: uri,
1035
- mime_type: mime_type,
1036
- text: "Hello from example resource!"
1037
- )]
1038
- end
1039
- end
1040
- end
1041
-
1042
- server = MCP::Server.new(
1043
- name: "my_server",
1044
- resources: [MyResource],
1045
- )
1046
- ```
1047
-
1048
- `resources/read` requests are routed automatically: when the requested URI matches a registered
1049
- class-based resource, its `contents` method is called. `contents` may return an array of
1050
- `MCP::Resource::TextContents` / `MCP::Resource::BlobContents` objects (or plain hashes), or a single one.
1051
- Like tools, `contents` can opt in to a `server_context:` keyword argument to receive per-request context.
1052
-
1053
- When class-based resources or resource templates are registered and a `resources/read` request
1054
- does not match any of them, the server responds with the standard JSON-RPC Invalid Params error
1055
- (`-32602`) carrying the requested URI in the error `data` member, per SEP-2164.
1056
-
1057
- 2. With the `MCP::Resource.define` method, whose block implements `contents`:
1058
-
1059
- ```ruby
1060
- resource = MCP::Resource.define(
1061
- uri: "https://example.com/my_resource",
1062
- name: "my-resource",
1063
- mime_type: "text/html",
1064
- ) do
1065
- [MCP::Resource::TextContents.new(uri: uri, mime_type: mime_type, text: "Hello!")]
1066
- end
1067
- ```
1068
-
1069
- 3. Using the `MCP::Server#define_resource` method:
1070
-
1071
- ```ruby
1072
- server = MCP::Server.new(name: "my_server")
1073
- server.define_resource(
1074
- uri: "https://example.com/my_resource",
1075
- name: "my-resource",
1076
- mime_type: "text/html",
1077
- ) do
1078
- [MCP::Resource::TextContents.new(uri: "https://example.com/my_resource", mime_type: "text/html", text: "Hello!")]
1079
- end
1080
- ```
1081
-
1082
- Alternatively, resources can be registered as plain data objects with `MCP::Resource.new`,
1083
- in which case the server only lists them:
1084
-
1085
- ```ruby
1086
- resource = MCP::Resource.new(
1087
- uri: "https://example.com/my_resource",
1088
- name: "my-resource",
1089
- title: "My Resource",
1090
- description: "Lorem ipsum dolor sit amet",
1091
- mime_type: "text/html",
1092
- )
1093
-
1094
- server = MCP::Server.new(
1095
- name: "my_server",
1096
- resources: [resource],
1097
- )
1098
- ```
1099
-
1100
- With plain data resources, the server must register a handler for the `resources/read` method to
1101
- retrieve a resource dynamically.
1102
-
1103
- ```ruby
1104
- server.resources_read_handler do |params|
1105
- [{
1106
- uri: params[:uri],
1107
- mimeType: "text/plain",
1108
- text: "Hello from example resource! URI: #{params[:uri]}"
1109
- }]
1110
- end
1111
- ```
1112
-
1113
- otherwise `resources/read` requests will be a no-op. Note that a `resources_read_handler` fully replaces
1114
- the default `resources/read` handling, including the automatic routing to class-based resources described above.
1115
-
1116
- For unknown URIs, raise `MCP::Server::ResourceNotFoundError` from the handler.
1117
- Per SEP-2164, the server then responds with the standard JSON-RPC Invalid Params error (`-32602`)
1118
- carrying the requested URI in the error `data` member:
1119
-
1120
- ```ruby
1121
- server.resources_read_handler do |params|
1122
- resource = lookup(params[:uri])
1123
- raise MCP::Server::ResourceNotFoundError.new(params[:uri], params) unless resource
1124
-
1125
- [{ uri: params[:uri], mimeType: resource.mime_type, text: resource.body }]
1126
- end
1127
- ```
1128
-
1129
- ### Resource Templates
1130
-
1131
- Resource templates follow the same pattern. Class-based templates declare a `uri_template` and
1132
- receive the variables extracted from the requested URI as keyword arguments to `contents`:
1133
-
1134
- ```ruby
1135
- class UserProfileTemplate < MCP::ResourceTemplate
1136
- uri_template "users://{user_id}/profile"
1137
- resource_template_name "user-profile"
1138
- title "User Profile"
1139
- description "Profile data for a user"
1140
- mime_type "application/json"
1141
-
1142
- class << self
1143
- def contents(user_id:)
1144
- [MCP::Resource::TextContents.new(
1145
- uri: "users://#{user_id}/profile",
1146
- mime_type: mime_type,
1147
- text: { id: user_id }.to_json
1148
- )]
1149
- end
1150
- end
1151
- end
1152
-
1153
- server = MCP::Server.new(
1154
- name: "my_server",
1155
- resource_templates: [UserProfileTemplate],
1156
- )
1157
- ```
1158
-
1159
- A `resources/read` request for `users://42/profile` calls `UserProfileTemplate.contents(user_id: "42")`.
1160
- An exact match against a registered resource takes precedence over template matching.
1161
- `contents` can also opt in to a `server_context:` keyword argument.
1162
-
1163
- URI template matching supports simple [RFC 6570](https://www.rfc-editor.org/rfc/rfc6570) level 1 `{variable}` expressions only:
1164
-
1165
- - Operator expressions such as `{+path}`, `{#fragment}`, or `{?query}` are treated as literal text and never match an expanded URI.
1166
- - A variable matches one or more characters excluding `/`.
1167
- - Extracted values are not percent-decoded.
1168
-
1169
- The `MCP::ResourceTemplate.define` and `MCP::Server#define_resource_template` methods are also available,
1170
- mirroring the resource variants:
1171
-
1172
- ```ruby
1173
- server.define_resource_template(
1174
- uri_template: "users://{user_id}/profile",
1175
- name: "user-profile",
1176
- mime_type: "application/json",
1177
- ) do |user_id:|
1178
- [MCP::Resource::TextContents.new(
1179
- uri: "users://#{user_id}/profile",
1180
- mime_type: "application/json",
1181
- text: { id: user_id }.to_json
1182
- )]
1183
- end
1184
- ```
1185
-
1186
- Resource templates can also be registered as plain data objects with `MCP::ResourceTemplate.new`,
1187
- in which case reads must be served by a `resources_read_handler`:
1188
-
1189
- ```ruby
1190
- resource_template = MCP::ResourceTemplate.new(
1191
- uri_template: "https://example.com/my_resource_template",
1192
- name: "my-resource-template",
1193
- title: "My Resource Template",
1194
- description: "Lorem ipsum dolor sit amet",
1195
- mime_type: "text/html",
1196
- )
1197
-
1198
- server = MCP::Server.new(
1199
- name: "my_server",
1200
- resource_templates: [resource_template],
1201
- )
1202
- ```
1203
-
1204
- ### Roots
1205
-
1206
- The Model Context Protocol allows servers to request filesystem roots from clients through the `roots/list` method.
1207
- Roots define the boundaries of where a server can operate, providing a list of directories and files the client has made available.
1208
-
1209
- **Key Concepts:**
1210
-
1211
- - **Server-to-Client Request**: Like sampling, roots listing is initiated by the server
1212
- - **Client Capability**: Clients must declare `roots` capability during initialization
1213
- - **Change Notifications**: Clients that support `roots.listChanged` send `notifications/roots/list_changed` when roots change
1214
-
1215
- > [!NOTE]
1216
- > Per SEP-2260, server-to-client requests (`roots/list`, `sampling/createMessage`, `elicitation/create`) must be associated with
1217
- > an originating client request (`ping` is exempt). Use the `server_context` passed to your handler, which stamps the association
1218
- > automatically and routes the request onto the originating POST stream on the Streamable HTTP transport. Calling the corresponding
1219
- > `ServerSession` methods without `related_request_id:` still works but emits a deprecation warning.
1220
-
1221
- **Using Roots in Tools:**
1222
-
1223
- Tools that accept a `server_context:` parameter can call `list_roots` on it.
1224
- The request is automatically routed to the correct client session:
1225
-
1226
- ```ruby
1227
- class FileSearchTool < MCP::Tool
1228
- description "Search files within the client's project roots"
1229
- input_schema(
1230
- properties: {
1231
- query: { type: "string" }
1232
- },
1233
- required: ["query"]
1234
- )
1235
-
1236
- def self.call(query:, server_context:)
1237
- roots = server_context.list_roots
1238
- root_uris = roots[:roots].map { |root| root[:uri] }
1239
-
1240
- MCP::Tool::Response.new([{
1241
- type: "text",
1242
- text: "Searching in roots: #{root_uris.join(", ")}"
1243
- }])
1244
- end
1245
- end
1246
- ```
1247
-
1248
- Result contains an array of root objects:
1249
-
1250
- ```ruby
1251
- {
1252
- roots: [
1253
- { uri: "file:///home/user/projects/myproject", name: "My Project" },
1254
- { uri: "file:///home/user/repos/backend", name: "Backend Repository" }
1255
- ]
1256
- }
1257
- ```
1258
-
1259
- **Handling Root Changes:**
1260
-
1261
- Register a callback to be notified when the client's roots change:
1262
-
1263
- ```ruby
1264
- server.roots_list_changed_handler do
1265
- puts "Client's roots have changed, tools will see updated roots on next call."
1266
- end
1267
- ```
1268
-
1269
- **Error Handling:**
1270
-
1271
- - Raises `RuntimeError` if client does not support `roots` capability
1272
- - Raises `StandardError` if client returns an error response
1273
-
1274
- ### Resource Subscriptions
1275
-
1276
- Resource subscriptions allow clients to monitor specific resources for changes.
1277
- When a subscribed resource is updated, the server sends a notification to the client.
1278
-
1279
- The SDK does not track subscription state internally.
1280
- Server developers register handlers and manage their own subscription state.
1281
- Three methods are provided:
1282
-
1283
- - `Server#resources_subscribe_handler` - registers a handler for `resources/subscribe` requests
1284
- - `Server#resources_unsubscribe_handler` - registers a handler for `resources/unsubscribe` requests
1285
- - `ServerContext#notify_resources_updated` - sends a `notifications/resources/updated` notification to the subscribing client
1286
-
1287
- ```ruby
1288
- subscribed_uris = Set.new
1289
-
1290
- server = MCP::Server.new(
1291
- name: "my_server",
1292
- resources: [my_resource],
1293
- capabilities: { resources: { subscribe: true } },
1294
- )
1295
-
1296
- server.resources_subscribe_handler do |params|
1297
- subscribed_uris.add(params[:uri].to_s)
1298
- end
1299
-
1300
- server.resources_unsubscribe_handler do |params|
1301
- subscribed_uris.delete(params[:uri].to_s)
1302
- end
1303
-
1304
- server.define_tool(name: "update_resource") do |server_context:, **args|
1305
- if subscribed_uris.include?("test://my-resource")
1306
- server_context.notify_resources_updated(uri: "test://my-resource")
1307
- end
1308
- MCP::Tool::Response.new([MCP::Content::Text.new("Resource updated").to_h])
1309
- end
1310
- ```
1311
-
1312
- ### Sampling
1313
-
1314
- The Model Context Protocol allows servers to request LLM completions from clients through the `sampling/createMessage` method.
1315
- This enables servers to leverage the client's LLM capabilities without needing direct access to AI models.
1316
-
1317
- **Key Concepts:**
1318
-
1319
- - **Server-to-Client Request**: Unlike typical MCP methods (client to server), sampling is initiated by the server
1320
- - **Client Capability**: Clients must declare `sampling` capability during initialization
1321
- - **Tool Support**: When using tools in sampling requests, clients must declare `sampling.tools` capability
1322
- - **Human-in-the-Loop**: Clients can implement user approval before forwarding requests to LLMs
1323
-
1324
- **Using Sampling in Tools:**
1325
-
1326
- Tools that accept a `server_context:` parameter can call `create_sampling_message` on it.
1327
- The request is automatically routed to the correct client session:
1328
-
1329
- ```ruby
1330
- class SummarizeTool < MCP::Tool
1331
- description "Summarize text using LLM"
1332
- input_schema(
1333
- properties: {
1334
- text: { type: "string" }
1335
- },
1336
- required: ["text"]
1337
- )
1338
-
1339
- def self.call(text:, server_context:)
1340
- result = server_context.create_sampling_message(
1341
- messages: [
1342
- { role: "user", content: { type: "text", text: "Please summarize: #{text}" } }
1343
- ],
1344
- max_tokens: 500
1345
- )
1346
-
1347
- MCP::Tool::Response.new([{
1348
- type: "text",
1349
- text: result[:content][:text]
1350
- }])
1351
- end
1352
- end
1353
-
1354
- server = MCP::Server.new(name: "my_server", tools: [SummarizeTool])
1355
- ```
1356
-
1357
- **Parameters:**
1358
-
1359
- Required:
1360
-
1361
- - `messages:` (Array) - Array of message objects with `role` and `content`
1362
- - `max_tokens:` (Integer) - Maximum tokens in the response
1363
-
1364
- Optional:
1365
-
1366
- - `system_prompt:` (String) - System prompt for the LLM
1367
- - `model_preferences:` (Hash) - Model selection preferences (e.g., `{ intelligencePriority: 0.8 }`)
1368
- - `include_context:` (String) - Context inclusion: `"none"`, `"thisServer"`, or `"allServers"` (soft-deprecated)
1369
- - `temperature:` (Float) - Sampling temperature
1370
- - `stop_sequences:` (Array) - Sequences that stop generation
1371
- - `metadata:` (Hash) - Additional metadata
1372
- - `tools:` (Array) - Tools available to the LLM (requires `sampling.tools` capability)
1373
- - `tool_choice:` (Hash) - Tool selection mode (e.g., `{ mode: "auto" }`)
1374
-
1375
- **Error Handling:**
1376
-
1377
- - Raises `RuntimeError` if client does not support `sampling` capability
1378
- - Raises `RuntimeError` if `tools` are used but client lacks `sampling.tools` capability
1379
- - Raises `StandardError` if client returns an error response
1380
-
1381
- ### Notifications
1382
-
1383
- The server supports sending notifications to clients when lists of tools, prompts, or resources change. This enables real-time updates without polling.
1384
-
1385
- #### Notification Methods
1386
-
1387
- The server provides the following notification methods:
1388
-
1389
- - `notify_tools_list_changed` - Send a notification when the tools list changes
1390
- - `notify_prompts_list_changed` - Send a notification when the prompts list changes
1391
- - `notify_resources_list_changed` - Send a notification when the resources list changes
1392
- - `notify_log_message` - Send a structured logging notification message
1393
-
1394
- #### Session Scoping
1395
-
1396
- When using Streamable HTTP transport with multiple clients, each client connection gets its own session. Notifications are scoped as follows:
1397
-
1398
- - **`report_progress`** and **`notify_log_message`** called via `server_context` inside a tool handler are automatically sent only to the requesting client.
1399
- No extra configuration is needed.
1400
- - **`notify_tools_list_changed`**, **`notify_prompts_list_changed`**, and **`notify_resources_list_changed`** are always broadcast to all connected clients,
1401
- as they represent server-wide state changes. These should be called on the `server` instance directly.
1402
-
1403
- #### Notification Format
1404
-
1405
- Notifications follow the JSON-RPC 2.0 specification and use these method names:
1406
-
1407
- - `notifications/tools/list_changed`
1408
- - `notifications/prompts/list_changed`
1409
- - `notifications/resources/list_changed`
1410
- - `notifications/cancelled`
1411
- - `notifications/progress`
1412
- - `notifications/message`
1413
-
1414
- ### Cancellation
1415
-
1416
- The MCP Ruby SDK supports server-side handling of the
1417
- [MCP `notifications/cancelled` utility](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation).
1418
- When a client sends `notifications/cancelled` for an in-flight request, the server stops
1419
- processing cooperatively and suppresses the JSON-RPC response for that request.
1420
-
1421
- Cancellation is cooperative: the SDK does not forcibly terminate tool code. Instead,
1422
- a `MCP::Cancellation` token is threaded through `server_context`, and long-running tools
1423
- poll it to exit early. When a tool returns after cancellation has been observed,
1424
- the server suppresses the JSON-RPC response, matching the spec. The `initialize` request
1425
- is never cancellable per the spec.
1426
-
1427
- Client-initiated cancellation is also supported: see [Client-Side: Cancelling an In-Flight Request](#client-side-cancelling-an-in-flight-request) below.
1428
-
1429
- #### Server-Side: Handlers that Check for Cancellation
1430
-
1431
- Any handler that opts in to `server_context:` - tools (`Tool.call`), prompt templates,
1432
- `resources_read_handler`, `completion_handler`, `resources_subscribe_handler`,
1433
- `resources_unsubscribe_handler`, and `define_custom_method` blocks - receives
1434
- an `MCP::ServerContext` wired to the in-flight request's cancellation token.
1435
- Handlers check `cancelled?` in their work loop, or call `raise_if_cancelled!` to raise
1436
- `MCP::CancelledError` at a safe point:
1437
-
1438
- ```ruby
1439
- class LongRunningTool < MCP::Tool
1440
- description "A tool that supports cancellation"
1441
- input_schema(properties: { count: { type: "integer" } }, required: ["count"])
1442
-
1443
- def self.call(count:, server_context:)
1444
- count.times do |i|
1445
- # Exit early if the client has sent `notifications/cancelled`.
1446
- break if server_context.cancelled?
1447
-
1448
- do_work(i)
1449
- end
1450
-
1451
- MCP::Tool::Response.new([{ type: "text", text: "Done" }])
1452
- end
1453
- end
1454
- ```
1455
-
1456
- Alternatively, raise at the next safe point with `raise_if_cancelled!`:
1457
-
1458
- ```ruby
1459
- def self.call(count:, server_context:)
1460
- count.times do |i|
1461
- server_context.raise_if_cancelled!
1462
-
1463
- do_work(i)
1464
- end
1465
-
1466
- MCP::Tool::Response.new([{ type: "text", text: "Done" }])
1467
- end
1468
- ```
1469
-
1470
- When a handler observes cancellation (either by returning early with `cancelled?` or
1471
- by raising `MCP::CancelledError` via `raise_if_cancelled!`), the server drops the response and
1472
- no JSON-RPC result is sent to the client.
1473
-
1474
- The same pattern works for other handler types:
1475
-
1476
- ```ruby
1477
- # resources/read
1478
- server.resources_read_handler do |params, server_context:|
1479
- server_context.raise_if_cancelled!
1480
- # read the resource
1481
- end
1482
-
1483
- # completion/complete
1484
- server.completion_handler do |params, server_context:|
1485
- server_context.raise_if_cancelled!
1486
- # compute completions
1487
- end
1488
-
1489
- # custom method
1490
- server.define_custom_method(method_name: "custom/slow") do |params, server_context:|
1491
- server_context.raise_if_cancelled!
1492
- # do work
1493
- end
1494
-
1495
- # prompts (via Prompt subclass)
1496
- class SlowPrompt < MCP::Prompt
1497
- prompt_name "slow_prompt"
1498
-
1499
- def self.template(args, server_context:)
1500
- server_context.raise_if_cancelled!
1501
- MCP::Prompt::Result.new(messages: [])
1502
- end
1503
- end
1504
- ```
1505
-
1506
- Handlers that do not declare a `server_context:` keyword continue to work unchanged -
1507
- the opt-in detection only wraps the context when the block signature asks for it.
1508
-
1509
- #### Nested Server-to-Client Requests Are Cancelled Automatically
1510
-
1511
- When a tool handler is waiting on a nested server-to-client request
1512
- (`server_context.create_sampling_message`, `create_form_elicitation`, or
1513
- `create_url_elicitation`), cancelling the parent tool call automatically raises
1514
- `MCP::CancelledError` from the nested call, so the tool does not need to wrap it
1515
- in its own `cancelled?` checks:
1516
-
1517
- ```ruby
1518
- def self.call(server_context:)
1519
- result = server_context.create_sampling_message(messages: messages, max_tokens: 100)
1520
- # If the parent tools/call is cancelled while waiting above, MCP::CancelledError
1521
- # is raised here and the tool can let it propagate or clean up as needed.
1522
- MCP::Tool::Response.new([{ type: "text", text: result[:content][:text] }])
1523
- rescue MCP::CancelledError
1524
- # Optional: run cleanup. Re-raising (or letting it propagate) is fine; the server
1525
- # will still suppress the JSON-RPC response per the MCP spec.
1526
- raise
1527
- end
1528
- ```
1529
-
1530
- Nested cancellation propagation is supported on `StreamableHTTPTransport` only.
1531
- `StdioTransport` is single-threaded and blocks on `$stdin.gets`, so a nested
1532
- `server_context.create_sampling_message` inside a tool runs to completion even if
1533
- the parent `tools/call` is cancelled. The parent tool itself still observes cancellation
1534
- via `server_context.cancelled?` between nested calls.
1535
-
1536
- #### Client-Side: Cancelling an In-Flight Request
1537
-
1538
- `MCP::Client` lets the caller cancel a request it has already issued. The recommended pattern is to pass
1539
- an `MCP::Cancellation` token into the request method, run the request on a worker thread, and call
1540
- `cancellation.cancel(reason:)` from another thread. The cancelling thread sends `notifications/cancelled` to
1541
- the server, and the calling thread is woken up with `MCP::CancelledError`:
1542
-
1543
- ```ruby
1544
- client = MCP::Client.new(transport: transport)
1545
- cancellation = MCP::Cancellation.new
1546
-
1547
- Thread.new do
1548
- client.call_tool(name: "slow_tool", arguments: {}, cancellation: cancellation)
1549
- rescue MCP::CancelledError
1550
- # cleanup
1551
- end
1552
-
1553
- # Later, from another thread:
1554
- cancellation.cancel(reason: "user pressed cancel")
1555
- ```
1556
-
1557
- All request methods (`tools`, `list_tools`, `resources`, `list_resources`, `resource_templates`, `list_resource_templates`,
1558
- `prompts`, `list_prompts`, `call_tool`, `read_resource`, `get_prompt`, `complete`, `ping`) accept the `cancellation:` keyword.
1559
- Request ids are managed internally, so the token is the only thing a caller needs to cancel a request.
1560
-
1561
- > [!NOTE]
1562
- > When a cancel wins the race, the SDK's worker thread that is blocked on the underlying I/O is *not* force-killed;
1563
- > it stays blocked until the transport actually returns (or the user closes the transport). This matches the server-side
1564
- > `StreamableHTTPTransport#send_request` trade-off. For `StreamableHTTPTransport#send_request` trade-off. For `Client::HTTP`
1565
- > the leak resolves as soon as the server sends any response; for `Client::Stdio` you may need to call `client.transport.close`
1566
- > to free the thread if the server stops responding entirely. The cancel-dispatch thread waits for the worker's send-boundary signal
1567
- > (`&on_sent` from `send_request`) before issuing `notifications/cancelled`, so the cancel is held until the worker has at
1568
- > least committed to writing the request; while the worker is wedged the cancel notification is deferred along with it.
1569
-
1570
- ##### Wire-order guarantees
1571
-
1572
- `Client::Stdio` serializes the request write and any subsequent `notifications/cancelled` write through a single `@write_mutex`,
1573
- so the server is guaranteed to read the request line before the cancel line.
1574
-
1575
- `Client::HTTP` cannot offer the same wire-arrival guarantee. Faraday's synchronous `post` does not expose a post-write / pre-response hook,
1576
- so the SDK yields just before the request POST is dispatched. After the yield, the cancel-dispatch thread issues a separate `notifications/cancelled` POST
1577
- 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
1578
- still believes it to be in-progress when issuing the cancel ([MCP cancellation spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation)),
1579
- and on the receiver side, "receivers MAY ignore a cancellation notification whose `requestId` is unknown" covers the case where the cancel POST
1580
- happens to arrive first. The calling thread raises `MCP::CancelledError` regardless of network ordering.
1581
-
1582
- ##### Custom transports
1583
-
1584
- Custom transports that want to support `cancellation:` must implement `send_notification(notification:)` so `notifications/cancelled` can be delivered.
1585
- 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
1586
- (under a write-side mutex for stdio-style transports, immediately before the synchronous round-trip for HTTP-style transports).
1587
- The cancel-dispatch thread waits on this signal before sending `notifications/cancelled`. Transports that do not invoke the block fall back to waiting for
1588
- the worker thread to terminate, which preserves wire-order at the cost of delaying the cancel notification until the request has fully completed.
1589
-
1590
- ### Ping
1591
-
1592
- The MCP Ruby SDK supports the
1593
- [MCP `ping` utility](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/ping),
1594
- which allows either side of the connection to verify that the peer is still responsive.
1595
- A `ping` request has no parameters, and the receiver MUST respond promptly with an empty result.
1596
-
1597
- #### Server-Side
1598
-
1599
- Servers respond to incoming `ping` requests automatically - no setup is required.
1600
- Any `MCP::Server` instance replies with an empty result.
1601
-
1602
- Servers can also send `ping` requests to the client via `ServerSession#ping`.
1603
- Inside a tool handler that receives `server_context:`, call `ping` on it:
1604
-
1605
- ```ruby
1606
- class HealthCheckTool < MCP::Tool
1607
- description "Verifies the client is still responsive"
1608
-
1609
- def self.call(server_context:)
1610
- server_context.ping # => {} on success
1611
-
1612
- MCP::Tool::Response.new([{ type: "text", text: "client is alive" }])
1613
- end
1614
- end
1615
- ```
1616
-
1617
- `#ping` raises `MCP::Server::ValidationError` when the client returns a `result`
1618
- that is not a Hash. Transport-level errors (e.g., the client returning a JSON-RPC error)
1619
- propagate as exceptions raised by the transport layer.
1620
-
1621
- #### Client-Side
1622
-
1623
- `MCP::Client` exposes `ping` to send a ping to the server:
1624
-
1625
- ```ruby
1626
- client = MCP::Client.new(transport: transport)
1627
- client.ping # => {} on success
1628
- ```
1629
-
1630
- `#ping` raises `MCP::Client::ServerError` when the server returns a JSON-RPC error.
1631
- It raises `MCP::Client::ValidationError` when the response `result` is missing or
1632
- is not a Hash (matching the spec requirement that `result` be an object).
1633
- Transport-level errors (for example, `MCP::Client::Stdio`'s `read_timeout:` firing)
1634
- propagate as exceptions raised by the transport layer.
1635
-
1636
- ### Progress
1637
-
1638
- The MCP Ruby SDK supports progress tracking for long-running tool operations,
1639
- following the [MCP Progress specification](https://modelcontextprotocol.io/specification/latest/server/utilities/progress).
1640
-
1641
- #### How Progress Works
1642
-
1643
- 1. **Client Request**: The client sends a `progressToken` in the `_meta` field when calling a tool
1644
- 2. **Server Notification**: The server sends `notifications/progress` messages back to the client during tool execution
1645
- 3. **Tool Integration**: Tools call `server_context.report_progress` to report incremental progress
1646
-
1647
- #### Server-Side: Tool with Progress
1648
-
1649
- Tools that accept a `server_context:` parameter can call `report_progress` on it.
1650
- The server automatically wraps the context in an `MCP::ServerContext` instance that provides this method:
1651
-
1652
- ```ruby
1653
- class LongRunningTool < MCP::Tool
1654
- description "A tool that reports progress during execution"
1655
- input_schema(
1656
- properties: {
1657
- count: { type: "integer" },
1658
- },
1659
- required: ["count"]
1660
- )
1661
-
1662
- def self.call(count:, server_context:)
1663
- count.times do |i|
1664
- # Do work here.
1665
- server_context.report_progress(i + 1, total: count, message: "Processing item #{i + 1}")
1666
- end
1667
-
1668
- MCP::Tool::Response.new([{ type: "text", text: "Done" }])
1669
- end
1670
- end
1671
- ```
1672
-
1673
- The `server_context.report_progress` method accepts:
1674
-
1675
- - `progress` (required) — current progress value (numeric)
1676
- - `total:` (optional) — total expected value, so clients can display a percentage
1677
- - `message:` (optional) — human-readable status message
1678
-
1679
- **Key Features:**
1680
-
1681
- - Tools report progress via `server_context.report_progress`
1682
- - `report_progress` is a no-op when no `progressToken` was provided by the client
1683
- - Supports both numeric and string progress tokens
1684
-
1685
- ### Completions
1686
-
1687
- MCP spec includes [Completions](https://modelcontextprotocol.io/specification/latest/server/utilities/completion),
1688
- which enable servers to provide autocompletion suggestions for prompt arguments and resource URIs.
1689
-
1690
- To enable completions, declare the `completions` capability and register a handler:
1691
-
1692
- ```ruby
1693
- server = MCP::Server.new(
1694
- name: "my_server",
1695
- prompts: [CodeReviewPrompt],
1696
- resource_templates: [FileTemplate],
1697
- capabilities: { completions: {} },
1698
- )
1699
-
1700
- server.completion_handler do |params|
1701
- ref = params[:ref]
1702
- argument = params[:argument]
1703
- value = argument[:value]
1704
-
1705
- case ref[:type]
1706
- when "ref/prompt"
1707
- values = case argument[:name]
1708
- when "language"
1709
- ["python", "pytorch", "pyside"].select { |v| v.start_with?(value) }
1710
- else
1711
- []
1712
- end
1713
- { completion: { values: values, hasMore: false } }
1714
- when "ref/resource"
1715
- { completion: { values: [], hasMore: false } }
1716
- end
1717
- end
1718
- ```
1719
-
1720
- The handler receives a `params` hash with:
1721
-
1722
- - `ref` - The reference (`{ type: "ref/prompt", name: "..." }` or `{ type: "ref/resource", uri: "..." }`)
1723
- - `argument` - The argument being completed (`{ name: "...", value: "..." }`)
1724
- - `context` (optional) - Previously resolved arguments (`{ arguments: { ... } }`)
1725
-
1726
- The handler must return a hash with a `completion` key containing `values` (array of strings), and optionally `total` and `hasMore`.
1727
- The SDK automatically enforces the 100-item limit per the MCP specification.
1728
-
1729
- The server validates that the referenced prompt, resource, or resource template is registered before calling the handler.
1730
- Requests for unknown references return an error.
1731
-
1732
- ### Elicitation
1733
-
1734
- The MCP Ruby SDK supports [elicitation](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation),
1735
- which allows servers to request additional information from users through the client during tool execution.
1736
-
1737
- Elicitation is a **server-to-client request**. The server sends a request and blocks until the user responds via the client.
1738
-
1739
- #### Capabilities
1740
-
1741
- Clients must declare the `elicitation` capability during initialization. The server checks this before sending any elicitation request
1742
- and raises a `RuntimeError` if the client does not support it.
1743
-
1744
- For URL mode support, the client must also declare `elicitation.url` capability.
1745
-
1746
- #### Using Elicitation in Tools
1747
-
1748
- Tools that accept a `server_context:` parameter can call `create_form_elicitation` on it:
1749
-
1750
- ```ruby
1751
- server.define_tool(name: "collect_info", description: "Collect user info") do |server_context:|
1752
- result = server_context.create_form_elicitation(
1753
- message: "Please provide your name",
1754
- requested_schema: {
1755
- type: "object",
1756
- properties: { name: { type: "string" } },
1757
- required: ["name"],
1758
- },
1759
- )
1760
-
1761
- MCP::Tool::Response.new([{ type: "text", text: "Hello, #{result[:content][:name]}" }])
1762
- end
1763
- ```
1764
-
1765
- #### Form Mode
1766
-
1767
- Form mode collects structured data from the user directly through the MCP client:
1768
-
1769
- ```ruby
1770
- server.define_tool(name: "collect_contact", description: "Collect contact info") do |server_context:|
1771
- result = server_context.create_form_elicitation(
1772
- message: "Please provide your contact information",
1773
- requested_schema: {
1774
- type: "object",
1775
- properties: {
1776
- name: { type: "string", description: "Your full name" },
1777
- email: { type: "string", format: "email", description: "Your email address" },
1778
- },
1779
- required: ["name", "email"],
1780
- },
1781
- )
1782
-
1783
- text = case result[:action]
1784
- when "accept"
1785
- "Hello, #{result[:content][:name]} (#{result[:content][:email]})"
1786
- when "decline"
1787
- "User declined"
1788
- when "cancel"
1789
- "User cancelled"
1790
- end
1791
-
1792
- MCP::Tool::Response.new([{ type: "text", text: text }])
1793
- end
1794
- ```
1795
-
1796
- #### URL Mode
1797
-
1798
- URL mode directs the user to an external URL for out-of-band interactions such as OAuth flows:
1799
-
1800
- ```ruby
1801
- server.define_tool(name: "authorize_github", description: "Authorize GitHub") do |server_context:|
1802
- elicitation_id = SecureRandom.uuid
1803
-
1804
- result = server_context.create_url_elicitation(
1805
- message: "Please authorize access to your GitHub account",
1806
- url: "https://example.com/oauth/authorize?elicitation_id=#{elicitation_id}",
1807
- elicitation_id: elicitation_id,
1808
- )
1809
-
1810
- server_context.notify_elicitation_complete(elicitation_id: elicitation_id)
1811
-
1812
- MCP::Tool::Response.new([{ type: "text", text: "Authorization complete" }])
1813
- end
1814
- ```
1815
-
1816
- #### URLElicitationRequiredError
1817
-
1818
- When a tool cannot proceed until an out-of-band elicitation is completed, raise `MCP::Server::URLElicitationRequiredError`.
1819
- This returns a JSON-RPC error with code `-32042` to the client:
1820
-
1821
- ```ruby
1822
- server.define_tool(name: "access_github", description: "Access GitHub") do |server_context:|
1823
- raise MCP::Server::URLElicitationRequiredError.new([
1824
- {
1825
- mode: "url",
1826
- elicitationId: SecureRandom.uuid,
1827
- url: "https://example.com/oauth/authorize",
1828
- message: "GitHub authorization is required.",
1829
- },
1830
- ])
1831
- end
1832
- ```
1833
-
1834
- ### Logging
1835
-
1836
- 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).
1837
-
1838
- The `notifications/message` notification is used for structured logging between client and server.
1839
-
1840
- #### Log Levels
1841
-
1842
- The SDK supports 8 log levels with increasing severity:
1843
-
1844
- - `debug` - Detailed debugging information
1845
- - `info` - General informational messages
1846
- - `notice` - Normal but significant events
1847
- - `warning` - Warning conditions
1848
- - `error` - Error conditions
1849
- - `critical` - Critical conditions
1850
- - `alert` - Action must be taken immediately
1851
- - `emergency` - System is unusable
1852
-
1853
- #### How Logging Works
1854
-
1855
- 1. **Client Configuration**: The client sends a `logging/setLevel` request to configure the minimum log level
1856
- 2. **Server Filtering**: The server only sends log messages at the configured level or higher severity
1857
- 3. **Notification Delivery**: Log messages are sent as `notifications/message` to the client
1858
-
1859
- For example, if the client sets the level to `"error"` (severity 4), the server will send messages with levels: `error`, `critical`, `alert`, and `emergency`.
1860
-
1861
- For more details, see the [MCP Logging specification](https://modelcontextprotocol.io/specification/latest/server/utilities/logging).
1862
-
1863
- **Usage Example:**
1864
-
1865
- ```ruby
1866
- server = MCP::Server.new(name: "my_server")
1867
- transport = MCP::Server::Transports::StdioTransport.new(server)
1868
-
1869
- # The client first configures the logging level (on the client side):
1870
- transport.send_request(
1871
- request: {
1872
- jsonrpc: "2.0",
1873
- method: "logging/setLevel",
1874
- params: { level: "info" },
1875
- id: session_id # Unique request ID within the session
1876
- }
1877
- )
1878
-
1879
- # Send log messages at different severity levels
1880
- server.notify_log_message(
1881
- data: { message: "Application started successfully" },
1882
- level: "info"
1883
- )
1884
-
1885
- server.notify_log_message(
1886
- data: { message: "Configuration file not found, using defaults" },
1887
- level: "warning"
1888
- )
1889
-
1890
- server.notify_log_message(
1891
- data: {
1892
- error: "Database connection failed",
1893
- details: { host: "localhost", port: 5432 }
1894
- },
1895
- level: "error",
1896
- logger: "DatabaseLogger" # Optional logger name
1897
- )
1898
- ```
1899
-
1900
- **Key Features:**
1901
-
1902
- - 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
1903
- - Server has capability `logging` to send log messages
1904
- - Messages are only sent if a transport is configured
1905
- - Messages are filtered based on the client's configured log level
1906
- - If the log level hasn't been set by the client, no messages will be sent
1907
-
1908
- #### Transport Support
1909
-
1910
- - **stdio**: Notifications are sent as JSON-RPC 2.0 messages to stdout
1911
- - **Streamable HTTP**: Notifications are sent as JSON-RPC 2.0 messages over HTTP with streaming (chunked transfer or SSE)
1912
-
1913
- #### Usage Example
1914
-
1915
- ```ruby
1916
- server = MCP::Server.new(name: "my_server")
1917
-
1918
- # Default Streamable HTTP - session oriented
1919
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server)
1920
-
1921
- # When tools change, notify clients
1922
- server.define_tool(name: "new_tool") { |**args| { result: "ok" } }
1923
- server.notify_tools_list_changed
1924
- ```
1925
-
1926
- You can use Stateless Streamable HTTP, where notifications are not supported and all calls are request/response interactions.
1927
- This mode allows for easy multi-node deployment.
1928
- Set `stateless: true` in `MCP::Server::Transports::StreamableHTTPTransport.new` (`stateless` defaults to `false`):
1929
-
1930
- ```ruby
1931
- # Stateless Streamable HTTP - session-less
1932
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stateless: true)
1933
- ```
1934
-
1935
- In stateless mode, each POST is fully self-contained per SEP-2567: no `Mcp-Session-Id` is issued or required,
1936
- handlers run against an ephemeral per-request session (so client identity never leaks across requests or onto the shared server),
1937
- and repeated `initialize` requests are permitted. Request-scoped notifications such as progress and log messages are skipped
1938
- (there is no stream to deliver them), while server-to-client requests (`sampling/createMessage`, `roots/list`, `elicitation/create`) raise an error.
1939
-
1940
- You can enable JSON response mode, where the server returns `application/json` instead of `text/event-stream`.
1941
- Set `enable_json_response: true` in `MCP::Server::Transports::StreamableHTTPTransport.new`:
1942
-
1943
- ```ruby
1944
- # JSON response mode
1945
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, enable_json_response: true)
1946
- ```
1947
-
1948
- In JSON response mode, the POST response is a single JSON object, so server-to-client messages
1949
- that need to arrive during request processing are not supported:
1950
- request-scoped notifications (`progress`, `log`) are silently dropped, and all server-to-client requests
1951
- (`sampling/createMessage`, `roots/list`, `elicitation/create`) raise an error.
1952
- Session-scoped standalone notifications (`resources/updated`, `elicitation/complete`) and
1953
- broadcast notifications (`tools/list_changed`, etc.) still flow to clients connected to the GET SSE stream.
1954
- This mode is suitable for simple tool servers that do not need server-initiated requests.
1955
-
1956
- By default, stateful sessions are bounded so an `initialize` flood cannot retain sessions until memory is exhausted:
1957
- they expire after `session_idle_timeout` seconds of inactivity (default 1800, i.e. 30 minutes) and the concurrent
1958
- session count is capped at `max_sessions` (default 10000). A session's idle timer is reset by activity that touches it
1959
- (a GET, or a regular-request POST), and expired sessions are collected by a background reaper roughly once a minute,
1960
- so cleanup lags inactivity by up to that interval. At the cap, the transport first reclaims any already-expired slots
1961
- and then, if still full, rejects a new `initialize` with HTTP 503 (it does not evict an existing session).
1962
-
1963
- ```ruby
1964
- # Tune the limits
1965
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, session_idle_timeout: 900, max_sessions: 5000)
1966
-
1967
- # Opt out of expiry and/or the cap (not recommended on internet-facing deployments)
1968
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, session_idle_timeout: nil, max_sessions: nil)
1969
- ```
1970
-
1971
- Stateless mode (`stateless: true`) retains no sessions, so neither limit applies to it.
1972
-
1973
- #### Session Ownership
1974
-
1975
- `StreamableHTTPTransport` issues a random `SecureRandom.uuid` session ID and validates incoming requests by session
1976
- existence and idle timeout only. It does not bind a session to a user, because the transport never receives
1977
- an authenticated identity on its own. A caller that obtains a valid session ID could therefore act on that session,
1978
- so binding a session to a user is the deploying application's responsibility (the MCP spec frames this as a SHOULD).
1979
-
1980
- The primary control is the `session_request_validator`. It is called as `->(request, session_id) { true | false }`
1981
- on every non-`initialize` POST, GET, and DELETE against an existing session (including notification and response POSTs,
1982
- so a stolen session ID cannot, for example, POST `notifications/cancelled` against a victim's request). A falsy return
1983
- rejects the request with HTTP 403. Use it to compare the request's authenticated principal against the one recorded
1984
- when the session was created:
1985
-
1986
- ```ruby
1987
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(
1988
- server,
1989
- session_request_validator: ->(request, session_id) { owns_session?(request, session_id) },
1990
- )
1991
- ```
1992
-
1993
- Without a validator the transport does not enforce ownership. As a limited defense in depth (not authentication),
1994
- it also records the `Origin` header at `initialize` and rejects a later request whose `Origin` differs, but only
1995
- when both are present - a non-browser client that omits `Origin` (e.g. `curl` or a script) is not stopped by this check.
1996
- Enforcing ownership against a determined attacker requires supplying the validator with an authenticated principal.
1997
-
1998
- #### Request Size Limits
1999
-
2000
- `StreamableHTTPTransport` bounds how many bytes a single POST body may allocate, so a peer cannot exhaust memory
2001
- with one oversized message. A body larger than `max_request_bytes` (default 4 MiB) is rejected with HTTP 413,
2002
- and JSON nesting depth is capped. The 4 MiB default comfortably fits a typical JSON-RPC message (a 4 MiB JSON
2003
- string decodes to roughly 3 MiB of base64 payload) and matches the TypeScript SDK's 4 MB default; raise it only
2004
- if you exchange unusually large payloads:
2005
-
2006
- ```ruby
2007
- transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, max_request_bytes: 8 * 1024 * 1024)
2008
- ```
2009
-
2010
- ### Pagination
2011
-
2012
- The MCP Ruby SDK supports [pagination](https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/pagination)
2013
- for list operations that may return large result sets. Pagination uses string cursor tokens carrying a zero-based offset,
2014
- treated as opaque by clients: the server decides page size, and the client follows `nextCursor` until the server omits it.
2015
-
2016
- Pagination applies to `tools/list`, `prompts/list`, `resources/list`, and `resources/templates/list`.
2017
-
2018
- #### Server-Side: Enabling Pagination
2019
-
2020
- Pass `page_size:` to `MCP::Server.new` to split list responses into pages. When `page_size` is omitted (the default),
2021
- list responses contain all items in a single response, preserving the pre-pagination behavior.
2022
-
2023
- ```ruby
2024
- server = MCP::Server.new(
2025
- name: "my_server",
2026
- tools: tools,
2027
- page_size: 50,
2028
- )
2029
- ```
2030
-
2031
- When `page_size` is set, list responses include a `nextCursor` field whenever more pages are available:
2032
-
2033
- ```json
2034
- {
2035
- "jsonrpc": "2.0",
2036
- "id": 1,
2037
- "result": {
2038
- "tools": [
2039
- { "name": "example_tool" }
2040
- ],
2041
- "nextCursor": "50"
2042
- }
2043
- }
2044
- ```
2045
-
2046
- 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.
2047
-
2048
- #### Client-Side: Iterating Pages
2049
-
2050
- `MCP::Client` exposes `list_tools`, `list_prompts`, `list_resources`, and `list_resource_templates`.
2051
- **Each call issues exactly one `*/list` JSON-RPC request and returns exactly one page** — not the full collection.
2052
- The returned result object (`MCP::Client::ListToolsResult` etc.) exposes the page items and the next cursor as method accessors:
2053
-
2054
- ```ruby
2055
- client = MCP::Client.new(transport: transport)
2056
-
2057
- cursor = nil
2058
- loop do
2059
- page = client.list_tools(cursor: cursor)
2060
- page.tools.each { |tool| process(tool) }
2061
- cursor = page.next_cursor
2062
- break unless cursor
2063
- end
2064
- ```
2065
-
2066
- The same pattern applies to `list_prompts` (`page.prompts`), `list_resources` (`page.resources`), and
2067
- `list_resource_templates` (`page.resource_templates`). `next_cursor` is `nil` on the final page.
2068
-
2069
- Because a single call returns a single page, how many items come back depends on the server's `page_size` configuration:
2070
-
2071
- | Server `page_size` | `client.list_tools(cursor: nil)` |
2072
- |--------------------|---------------------------------------------------------------------|
2073
- | Not set (default) | Returns every item in one response. `next_cursor` is `nil`. |
2074
- | Set to `N` | Returns the first `N` items. `next_cursor` is set for continuation. |
2075
-
2076
- If your application needs the complete collection regardless of how the server is configured, either loop on
2077
- `next_cursor` as shown above, or use the whole-collection methods described below.
2078
-
2079
- #### Fetching the Complete Collection
2080
-
2081
- `client.tools`, `client.resources`, `client.resource_templates`, and `client.prompts` auto-iterate
2082
- through all pages and return a plain array of items, guaranteeing the full collection regardless
2083
- of the server's `page_size` setting. When a server paginates, they issue multiple JSON-RPC round
2084
- trips per call and break out of the pagination loop if the server returns the same `nextCursor`
2085
- twice in a row as a safety measure.
2086
-
2087
- ```ruby
2088
- tools = client.tools # => Array<MCP::Client::Tool> of every tool on the server.
2089
- ```
2090
-
2091
- Use these when you want the complete list; use `list_tools(cursor:)` etc. when you need
2092
- fine-grained iteration (e.g. to stream-process pages without loading everything into memory).
2093
-
2094
- #### List Result Caching (`ttlMs` / `cacheScope`)
2095
-
2096
- 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;
2097
- `0` means do not cache) and whether shared intermediaries may cache it (`cacheScope`: `"public"` or `"private"`).
2098
-
2099
- 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`,
2100
- `resources/templates/list`, and `resources/read` results (a missing field is filled with the defaults `ttlMs: 0` / `cacheScope: "public"`).
2101
- When neither is set, responses are serialized exactly as before.
2102
-
2103
- ```ruby
2104
- server = MCP::Server.new(
2105
- name: "my_server",
2106
- tools: tools,
2107
- ttl_ms: 60_000, # results stay fresh for one minute
2108
- cache_scope: "private", # only the requesting client may cache them
2109
- )
2110
- ```
2111
-
2112
- A `resources_read_handler` can override the hints per result by returning a full result hash instead of bare contents:
2113
-
2114
- ```ruby
2115
- server.resources_read_handler do |params|
2116
- { contents: [{ uri: params[:uri], mimeType: "text/plain", text: "..." }], ttlMs: 5_000 }
2117
- end
2118
- ```
2119
-
2120
- On the client, the values are surfaced on the paginated result structs as `ttl_ms` and `cache_scope`:
2121
-
2122
- ```ruby
2123
- page = client.list_tools
2124
- page.ttl_ms # => 60000 (nil when the server sent no hint)
2125
- page.cache_scope # => "private"
2126
- ```
2127
-
2128
- ### Advanced
2129
-
2130
- #### Custom Methods
2131
-
2132
- The server allows you to define custom JSON-RPC methods beyond the standard MCP protocol methods using the `define_custom_method` method:
2133
-
2134
- ```ruby
2135
- server = MCP::Server.new(name: "my_server")
2136
-
2137
- # Define a custom method that returns a result
2138
- server.define_custom_method(method_name: "add") do |params|
2139
- params[:a] + params[:b]
2140
- end
2141
-
2142
- # Define a custom notification method (returns nil)
2143
- server.define_custom_method(method_name: "notify") do |params|
2144
- # Process notification
2145
- nil
2146
- end
2147
- ```
2148
-
2149
- **Key Features:**
2150
-
2151
- - Accepts any method name as a string
2152
- - Block receives the request parameters as a hash
2153
- - Can handle both regular methods (with responses) and notifications
2154
- - Prevents overriding existing MCP protocol methods
2155
- - Supports instrumentation callbacks for monitoring
2156
-
2157
- **Usage Example:**
2158
-
2159
- ```ruby
2160
- # Client request
2161
- {
2162
- "jsonrpc": "2.0",
2163
- "id": 1,
2164
- "method": "add",
2165
- "params": { "a": 5, "b": 3 }
2166
- }
2167
-
2168
- # Server response
2169
- {
2170
- "jsonrpc": "2.0",
2171
- "id": 1,
2172
- "result": 8
2173
- }
2174
- ```
2175
-
2176
- **Error Handling:**
2177
-
2178
- - Raises `MCP::Server::MethodAlreadyDefinedError` if trying to override an existing method
2179
- - Supports the same exception reporting and instrumentation as standard methods
2180
-
2181
- ## Building an MCP Client
2182
-
2183
- The `MCP::Client` class provides an interface for interacting with MCP servers.
2184
-
2185
- This class supports:
2186
-
2187
- - Liveness check via the `ping` method (`MCP::Client#ping`)
2188
- - Tool listing via the `tools/list` method (`MCP::Client#tools`)
2189
- - Tool invocation via the `tools/call` method (`MCP::Client#call_tool`)
2190
- - Resource listing via the `resources/list` method (`MCP::Client#resources`)
2191
- - Resource template listing via the `resources/templates/list` method (`MCP::Client#resource_templates`)
2192
- - Resource reading via the `resources/read` method (`MCP::Client#read_resource`)
2193
- - Prompt listing via the `prompts/list` method (`MCP::Client#prompts`)
2194
- - Prompt retrieval via the `prompts/get` method (`MCP::Client#get_prompt`)
2195
- - Completion requests via the `completion/complete` method (`MCP::Client#complete`)
2196
- - Automatic JSON-RPC 2.0 message formatting
2197
- - UUID request ID generation
2198
-
2199
- Clients are initialized with a transport layer instance that handles the low-level communication mechanics.
2200
- Authorization is handled by the transport layer.
2201
-
2202
- ## Transport Layer Interface
2203
-
2204
- 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:
2205
-
2206
- ```ruby
2207
- class CustomTransport
2208
- # Sends a JSON-RPC request to the server and returns the raw response.
2209
- #
2210
- # @param request [Hash] A complete JSON-RPC request object.
2211
- # https://www.jsonrpc.org/specification#request_object
2212
- # @return [Hash] A hash modeling a JSON-RPC response object.
2213
- # https://www.jsonrpc.org/specification#response_object
2214
- def send_request(request:)
2215
- # Your transport-specific logic here
2216
- # - HTTP: POST to endpoint with JSON body
2217
- # - WebSocket: Send message over WebSocket
2218
- # - stdio: Write to stdout, read from stdin
2219
- # - etc.
2220
- end
2221
- end
2222
- ```
2223
-
2224
- ### Stdio Transport Layer
2225
-
2226
- Use the `MCP::Client::Stdio` transport to interact with MCP servers running as subprocesses over standard input/output.
2227
-
2228
- `MCP::Client::Stdio.new` accepts the following keyword arguments:
2229
-
2230
- | Parameter | Required | Description |
2231
- |---|---|---|
2232
- | `command:` | Yes | The command to spawn the server process (e.g., `"ruby"`, `"bundle"`, `"npx"`). |
2233
- | `args:` | No | An array of arguments passed to the command. Defaults to `[]`. |
2234
- | `env:` | No | A hash of environment variables to set for the server process. Defaults to `nil`. |
2235
- | `read_timeout:` | No | Timeout in seconds for waiting for a server response. Defaults to `nil` (no timeout). |
2236
- | `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). |
2237
-
2238
- Example usage:
2239
-
2240
- ```ruby
2241
- stdio_transport = MCP::Client::Stdio.new(
2242
- command: "bundle",
2243
- args: ["exec", "ruby", "path/to/server.rb"],
2244
- env: { "API_KEY" => "my_secret_key" },
2245
- read_timeout: 30
2246
- )
2247
- client = MCP::Client.new(transport: stdio_transport)
2248
-
2249
- # Perform the MCP initialization handshake before sending any requests.
2250
- client.connect
2251
-
2252
- # List available tools.
2253
- tools = client.tools
2254
- tools.each do |tool|
2255
- puts "Tool: #{tool.name} - #{tool.description}"
2256
- end
2257
-
2258
- # Call a specific tool.
2259
- response = client.call_tool(
2260
- tool: tools.first,
2261
- arguments: { message: "Hello, world!" }
2262
- )
2263
-
2264
- # Close the transport when done.
2265
- stdio_transport.close
2266
- ```
2267
-
2268
- The stdio transport automatically handles:
2269
-
2270
- - Spawning the server process with `Open3.popen3`
2271
- - MCP protocol initialization handshake (`initialize` request + `notifications/initialized`)
2272
- - JSON-RPC 2.0 message framing over newline-delimited JSON
2273
-
2274
- ### HTTP Transport Layer
2275
-
2276
- Use the `MCP::Client::HTTP` transport to interact with MCP servers using simple HTTP requests.
2277
-
2278
- 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:
2279
-
2280
- ```ruby
2281
- gem 'mcp'
2282
- gem 'faraday', '>= 2.0'
2283
- gem 'event_stream_parser', '>= 1.0' # optional, required only for SSE responses
2284
- ```
2285
-
2286
- Example usage:
2287
-
2288
- ```ruby
2289
- http_transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp")
2290
- client = MCP::Client.new(transport: http_transport)
2291
-
2292
- # Perform the MCP initialization handshake before sending any requests.
2293
- client.connect
2294
-
2295
- # List available tools
2296
- tools = client.tools
2297
- tools.each do |tool|
2298
- puts <<~TOOL_INFORMATION
2299
- Tool: #{tool.name}
2300
- Description: #{tool.description}
2301
- Input Schema: #{tool.input_schema}
2302
- TOOL_INFORMATION
2303
- end
2304
-
2305
- # Call a specific tool
2306
- response = client.call_tool(
2307
- tool: tools.first,
2308
- arguments: { message: "Hello, world!" }
2309
- )
2310
-
2311
- # Call a tool with progress tracking.
2312
- response = client.call_tool(
2313
- tool: tools.first,
2314
- arguments: { count: 10 },
2315
- progress_token: "my-progress-token"
2316
- )
2317
- ```
2318
-
2319
- The server will send `notifications/progress` back to the client during execution.
2320
-
2321
- `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 -
2322
- 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
2323
- a server that never terminates an SSE event. It defaults to `4 * 1024 * 1024` (4 MiB); raise it if your server returns larger responses.
2324
-
2325
- #### Server-to-Client Requests (Elicitation)
2326
-
2327
- Servers can send requests back to the client while one of the client's own requests is in flight - for example,
2328
- [`elicitation/create`](https://modelcontextprotocol.io/specification/2025-11-25/client/elicitation) to ask the user for additional input during a tool call.
2329
- Register a handler and advertise the capability on `connect` to respond to them:
2330
-
2331
- ```ruby
2332
- client.connect(capabilities: { elicitation: {} })
2333
-
2334
- client.on_elicitation do |params|
2335
- {
2336
- action: "accept",
2337
- # Fill fields omitted by the user with the schema's `default` values (SEP-1034)
2338
- content: MCP::Client::Elicitation.apply_defaults(params["requestedSchema"]),
2339
- }
2340
- end
2341
- ```
2342
-
2343
- Registering a handler opens a standalone HTTP GET SSE stream on a background thread
2344
- ([listening for messages from the server](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#listening-for-messages-from-the-server)),
2345
- since servers deliver requests that are not tied to a client request on that stream. Server requests with no registered handler are answered with
2346
- a JSON-RPC `-32601` (method not found) error. To handle methods other than `elicitation/create`, register directly on the transport with
2347
- `http_transport.on_server_request("method/name") { |params| ... }`.
2348
-
2349
- #### Server-to-Client Requests (Sampling)
2350
-
2351
- Servers can also request an LLM completion from the client with [`sampling/createMessage`](https://modelcontextprotocol.io/specification/2025-11-25/client/sampling),
2352
- letting a server leverage the client's model access without its own API keys.
2353
-
2354
- > MCP Sampling is deprecated as of protocol version `2026-07-28` (SEP-2577), while remaining fully supported under `2025-11-25`.
2355
- > Register this handler to interoperate with servers that still send sampling requests during the deprecation window;
2356
- > new servers should call LLM provider APIs directly.
2357
-
2358
- Register a handler and advertise the capability on `connect`:
2359
-
2360
- ```ruby
2361
- client.connect(capabilities: { sampling: {} })
2362
-
2363
- client.on_sampling do |params|
2364
- completion = my_llm.complete(params["messages"], max_tokens: params["maxTokens"])
2365
- {
2366
- role: "assistant",
2367
- content: { type: "text", text: completion.text },
2368
- model: completion.model,
2369
- stopReason: "endTurn",
2370
- }
2371
- end
2372
- ```
2373
-
2374
- For trust and safety, the spec recommends a human in the loop able to review, edit, or reject the request and the generated response.
2375
- To reject a request, raise `MCP::Client::ServerRequestError` with the spec's user-rejection code `-1`:
2376
-
2377
- ```ruby
2378
- client.on_sampling do |params|
2379
- raise MCP::Client::ServerRequestError.new("User rejected sampling request", code: -1) unless approved?(params)
2380
-
2381
- generate_completion(params)
2382
- end
2383
- ```
2384
-
2385
- Use `capabilities: { sampling: { tools: {} } }` to receive tool-enabled sampling requests. Like elicitation, this uses the same standalone GET SSE listening stream.
2386
-
2387
- #### HTTP Authorization
2388
-
2389
- 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:
2390
-
2391
- ```ruby
2392
- http_transport = MCP::Client::HTTP.new(
2393
- url: "https://api.example.com/mcp",
2394
- headers: {
2395
- "Authorization" => "Bearer my_token"
2396
- }
2397
- )
2398
-
2399
- client = MCP::Client.new(transport: http_transport)
2400
- client.tools # will make the call using Bearer auth
2401
- ```
2402
-
2403
- 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.
2404
-
2405
- #### OAuth 2.1 Authorization
2406
-
2407
- When an MCP server enforces the [MCP Authorization spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization),
2408
- pass an `MCP::Client::OAuth::Provider` to the transport instead of a static `Authorization` header. The transport will:
2409
-
2410
- - Send `Authorization: Bearer <access_token>` on every request when a token is available.
2411
- - On a `401 Unauthorized`, parse the `WWW-Authenticate` header, discover the authorization server (Protected Resource Metadata + RFC 8414 Authorization Server Metadata),
2412
- 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.
2413
- - 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
2414
- 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),
2415
- and when even that is absent the spec's default endpoints `/authorize`, `/token`, and `/register` at the origin are used with PKCE S256 assumed.
2416
- - 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).
2417
- - 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),
2418
- 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.
2419
- 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.
2420
- - Request the `offline_access` scope when `client_metadata[:grant_types]` includes `refresh_token` and the authorization server advertises `offline_access` in its metadata
2421
- `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
2422
- `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.
2423
-
2424
- ```ruby
2425
- require "mcp"
2426
-
2427
- provider = MCP::Client::OAuth::Provider.new(
2428
- client_metadata: {
2429
- client_name: "My MCP App",
2430
- redirect_uris: ["http://localhost:3030/callback"],
2431
- grant_types: ["authorization_code", "refresh_token"],
2432
- response_types: ["code"],
2433
- token_endpoint_auth_method: "none",
2434
- },
2435
- redirect_uri: "http://localhost:3030/callback",
2436
- redirect_handler: ->(authorization_url) {
2437
- # Send the user to the authorization URL - typically `Launchy.open(authorization_url)`
2438
- # or a manual `puts authorization_url` in CLI tools.
2439
- },
2440
- callback_handler: -> {
2441
- # Capture the redirect (for example, by running a small HTTP listener on
2442
- # `redirect_uri`) and return [code, state] from the query string.
2443
- },
2444
- )
2445
-
2446
- transport = MCP::Client::HTTP.new(
2447
- url: "https://api.example.com/mcp",
2448
- oauth: provider,
2449
- )
2450
- client = MCP::Client.new(transport: transport)
2451
- client.connect # `initialize` is sent here; if the server replies 401 the OAuth flow runs and the handshake is retried with the acquired token
2452
- client.tools
2453
- ```
2454
-
2455
- Required keyword arguments to `Provider.new`:
2456
-
2457
- - `client_metadata`: Hash sent to the authorization server's Dynamic Client Registration endpoint. Must include `redirect_uris`, `grant_types`, `response_types`,
2458
- `token_endpoint_auth_method`. `redirect_uri` (below) must appear in this list, otherwise the constructor raises `Provider::UnregisteredRedirectURIError`.
2459
- 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);
2460
- an explicit value always wins.
2461
- - `redirect_uri`: String. Must use HTTPS or be a loopback URL (`localhost`, `127.0.0.0/8`, `::1`); other values raise `Provider::InsecureRedirectURIError`.
2462
- - `redirect_handler`: Callable invoked with the fully-built authorization `URI`. Typically opens the user's browser.
2463
- - `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
2464
- (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
2465
- the authorization server's issuer, and a missing one is rejected when the server advertises `authorization_response_iss_parameter_supported`.
2466
-
2467
- Optional keyword arguments:
2468
-
2469
- - `scope`: Space-separated scopes to request when the server's `WWW-Authenticate` does not specify one.
2470
- - `storage`: Object responding to `tokens`, `save_tokens(t)`, `client_information`, `save_client_information(info)`. Defaults to `MCP::Client::OAuth::InMemoryStorage`,
2471
- which keeps credentials in process memory only. Persisted `client_information` is stamped with an `"issuer"` member binding it to the authorization server that
2472
- issued it (SEP-2352): when the server's authorization server changes, the SDK discards the stale registration and its tokens and re-registers automatically
2473
- (portable CIMD `client_id`s are kept). Treat the hash as opaque and persist it as-is.
2474
- - `client_id_metadata_document_url`: URL where you publish a Client ID Metadata Document
2475
- (`draft-ietf-oauth-client-id-metadata-document` and the MCP authorization specification).
2476
- When the authorization server advertises `client_id_metadata_document_supported: true`,
2477
- the SDK uses this URL as the OAuth `client_id` and skips Dynamic Client Registration.
2478
- Spec-required: the URL MUST be `https://` with a non-root path and MUST NOT include a fragment,
2479
- userinfo, or `.`/`..` segments. The SDK additionally rejects query strings (the draft only marks
2480
- them SHOULD NOT include, but the SDK refuses to send any) for `client_id` stability.
2481
- Any of these failures raise `Provider::InvalidClientIDMetadataDocumentURLError`. The CIMD document
2482
- served at the URL is a separate JSON artifact from the `client_metadata` keyword above:
2483
- the DCR `client_metadata` MUST NOT include `client_id`, while the CIMD document MUST include
2484
- `client_id` set to the document URL, `client_name`, and `redirect_uris` covering `redirect_uri`.
2485
-
2486
- To persist credentials across restarts, supply your own storage:
2487
-
2488
- ```ruby
2489
- class FileTokenStorage
2490
- def initialize(path)
2491
- @path = path
2492
- end
2493
-
2494
- def tokens
2495
- read["tokens"]
2496
- end
2497
-
2498
- def save_tokens(value)
2499
- write("tokens" => value)
2500
- end
2501
-
2502
- def client_information
2503
- read["client"]
2504
- end
2505
-
2506
- def save_client_information(value)
2507
- write("client" => value)
2508
- end
2509
-
2510
- private
2511
-
2512
- def read
2513
- File.exist?(@path) ? JSON.parse(File.read(@path)) : {}
2514
- end
2515
-
2516
- def write(updates)
2517
- File.write(@path, JSON.dump(read.merge(updates)))
2518
- end
2519
- end
2520
-
2521
- provider = MCP::Client::OAuth::Provider.new(
2522
- # ... required keywords ...
2523
- storage: FileTokenStorage.new(File.expand_path("~/.config/my-app/oauth.json")),
2524
- )
2525
- ```
2526
-
2527
- ##### Client Credentials Grant
2528
-
2529
- For a confidential machine-to-machine client (no user, no browser redirect), use `MCP::Client::OAuth::ClientCredentialsProvider` instead of `Provider`.
2530
- The transport discovers the authorization server the same way, then exchanges the OAuth 2.1 `client_credentials` grant (RFC 6749 Section 4.4) at
2531
- the token endpoint. There is no authorization request, PKCE, or `offline_access`, because the grant does not issue a refresh token.
2532
-
2533
- ```ruby
2534
- provider = MCP::Client::OAuth::ClientCredentialsProvider.new(
2535
- client_id: "my-service",
2536
- client_secret: ENV.fetch("MCP_CLIENT_SECRET"),
2537
- # token_endpoint_auth_method: "client_secret_basic" (default) or "client_secret_post"
2538
- # scope: "mcp:read mcp:write" (optional; used when the server does not advertise scopes)
2539
- )
2540
-
2541
- transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp", oauth: provider)
2542
- ```
2543
-
2544
- Keyword arguments:
2545
-
2546
- - `client_id`, `client_secret`: Required. The grant is for confidential clients, so a credential is mandatory.
2547
- - `token_endpoint_auth_method`: `"client_secret_basic"` (default) or `"client_secret_post"`. `"none"` is rejected with `ClientCredentialsProvider::InvalidCredentialsError`.
2548
- - `scope`, `storage`: Optional, same meaning as on `Provider`.
2549
-
2550
- ##### Cross-App Access (JWT Bearer) Grant
2551
-
2552
- For enterprise MCP deployments where an identity provider (IdP) governs authorization (SEP-990), use `MCP::Client::OAuth::CrossAppAccessProvider` instead of `Provider`.
2553
- 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
2554
- 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`.
2555
- Mirrors `CrossAppAccessProvider` and `requestJwtAuthorizationGrant` in the TypeScript SDK.
2556
-
2557
- `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
2558
- an enterprise secret store or a test double without changing the transport wiring.
2559
-
2560
- ```ruby
2561
- provider = MCP::Client::OAuth::CrossAppAccessProvider.new(
2562
- client_id: "my-mcp-client",
2563
- client_secret: ENV.fetch("MCP_CLIENT_SECRET"),
2564
- assertion_provider: ->(audience:, resource:) {
2565
- MCP::Client::OAuth::IDJAGTokenExchange.request(
2566
- token_endpoint: "https://idp.example.com/token",
2567
- id_token: ENV.fetch("IDP_ID_TOKEN"),
2568
- client_id: "my-idp-client",
2569
- audience: audience,
2570
- resource: resource,
2571
- )
2572
- },
2573
- # scope: "mcp:read mcp:write" (optional; used when neither WWW-Authenticate nor PRM specify one)
2574
- )
2575
-
2576
- transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp", oauth: provider)
2577
- ```
2578
-
2579
- Keyword arguments:
2580
-
2581
- - `client_id`, `client_secret`: Required. The `jwt-bearer` grant authenticates with `client_secret_basic` at the MCP authorization server.
2582
- - `assertion_provider`: Required. Callable invoked as `call(audience:, resource:)` and returning the ID-JAG assertion.
2583
- `audience` is the MCP authorization server's validated issuer identifier; `resource` is the canonical MCP server URL (RFC 8707).
2584
- Passing both through to `IDJAGTokenExchange.request` covers the common case.
2585
- - `scope`, `storage`: Optional, same meaning as on `Provider`.
2586
-
2587
- ##### Communication Security
2588
-
2589
- When `oauth:` is set, the MCP transport URL and every OAuth-facing URL (PRM, Authorization Server metadata, `authorization_endpoint`, `token_endpoint`, `registration_endpoint`,
2590
- `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.
2591
-
2592
- 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
2593
- 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,
2594
- whether the swap was triggered by
2595
- `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,
2596
- and whether the new URL is `http://` *or* `https://` to a different host or tenant.
2597
-
2598
- #### Customizing the Faraday Connection
2599
-
2600
- You can pass a block to `MCP::Client::HTTP.new` to customize the underlying Faraday connection.
2601
- The block is called after the default middleware is configured, so you can add middleware or swap the HTTP adapter:
2602
-
2603
- ```ruby
2604
- http_transport = MCP::Client::HTTP.new(url: "https://api.example.com/mcp") do |faraday|
2605
- faraday.use MyApp::Middleware::HttpRecorder
2606
- faraday.adapter :typhoeus
2607
- end
2608
- ```
2609
-
2610
- ### Tool Objects
2611
-
2612
- The client provides a wrapper class for tools returned by the server:
2613
-
2614
- - `MCP::Client::Tool` - Represents a single tool with its metadata
2615
-
2616
- This class provides easy access to tool properties like name, description, input schema, and output schema.
2617
-
2618
- ### Multi-Round-Trip Results (Experimental, SEP-2322)
2619
-
2620
- 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`,
2621
- 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
2622
- and an opaque `requestState`; the client fulfills the requests and re-issues the original request with `inputResponses` and the echoed `requestState`.
2623
-
2624
- 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`,
2625
- 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`
2626
- are provided for forward compatibility. Servers on stable protocol versions never send `resultType`, so existing behavior is unchanged.
2627
-
2628
- ## Conformance Testing
2629
-
2630
- 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).
2631
-
2632
- See [conformance/README.md](conformance/README.md) for usage instructions.
2633
-
2634
- ## Documentation
2635
-
2636
- - [SDK API documentation](https://rubydoc.info/gems/mcp)
2637
- - [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.