Skip to content
Back to search

ruby-mcp-client

This is a Ruby implementation of MCP (Model Context Protocol) client

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/simonx1/ruby-mcp-client with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/simonx1/ruby-mcp-client'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/simonx1--ruby-mcp-client/badge.svg)](/listings/simonx1--ruby-mcp-client)

HTML

<a href="/listings/simonx1--ruby-mcp-client"><img src="/api/listings/simonx1--ruby-mcp-client/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

# Gemfile
gem 'ruby-mcp-client'
bundle install
# or
gem install ruby-mcp-client

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,516 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # ruby-mcp-client
  2. A Ruby client for the Model Context Protocol (MCP), enabling integration with external tools and services via a standardized protocol.
  3. ## Installation
  4. ```ruby
  5. # Gemfile
  6. gem 'ruby-mcp-client'
  7. ```
  8. ```bash
  9. bundle install
  10. # or
  11. gem install ruby-mcp-client
  12. ```
  13. ## Overview
  14. MCP enables AI assistants to discover and invoke external tools via different transport mechanisms:
  15. - **stdio** - Local processes implementing the MCP protocol
  16. - **SSE** *(deprecated)* - Server-Sent Events with streaming support; the HTTP+SSE transport is deprecated and new integrations should use **Streamable HTTP** instead (see [Deprecated features](#deprecated-features))
  17. - **HTTP** - Simple request/response (non-streaming)
  18. - **Streamable HTTP** - HTTP POST with SSE-formatted responses
  19. Built-in API conversions: `to_openai_tools()`, `to_anthropic_tools()`, `to_google_tools()`
  20. ## MCP Protocol Support
  21. Implements the **MCP 2026-07-28** specification and stays compatible with
  22. every earlier revision (`2025-11-25`, `2025-06-18`, `2025-03-26`,
  23. `2024-11-05`). The client is dual-era: it probes each server with
  24. `server/discover` and talks the stateless 2026-07-28 protocol (per-request
  25. `_meta`, no `initialize`, no sessions) to servers that answer it, and runs
  26. the classic `initialize` handshake with everyone else — disconnecting if a
  27. server answers with a revision it cannot speak. See
  28. [MCP 2026-07-28 Features](#mcp-2026-07-28-features) for the new
  29. capabilities and [Deprecated features](#deprecated-features) for what the
  30. revision retires.
  31. - **Tools**: list, call, streaming, annotations (hint-style), structured outputs validated against `outputSchema` (JSON Schema 2020-12 / 2019-09 / draft-07), title, `x-mcp-header` parameters
  32. - **Prompts**: list, get with parameters
  33. - **Resources**: list, read, templates, subscriptions, pagination, ResourceLink content
  34. - **Elicitation**: Server-initiated user interactions (stdio, Streamable HTTP, and the *deprecated* HTTP+SSE transport) and multi round-trip `input_required` results
  35. - **Roots** *(deprecated in 2026-07-28)*: Filesystem scope boundaries with change notifications
  36. - **Sampling** *(deprecated in 2026-07-28)*: Server-requested LLM completions with modelPreferences
  37. - **Completion**: Autocomplete for prompts/resources with context
  38. - **Logging** *(deprecated in 2026-07-28)*: Server log messages with level filtering
  39. - **Tasks**: Task-augmented `tools/call` — declare the `io.modelcontextprotocol/tasks` extension, poll `tasks/get`, answer `inputRequests` with `tasks/update`, and take the outcome from `tasks/get`; the 2025-11-25 surface stays as legacy
  40. - **Subscriptions**: `subscriptions/listen` notification streams (2026-07-28)
  41. - **Caching**: `ttlMs` / `cacheScope` freshness hints on lists, reads and discovery (2026-07-28)
  42. - **Audio**: Audio content type support
  43. - **Progress & Cancellation**: `progressToken` plumbing with per-call callbacks; automatic `notifications/cancelled` for abandoned requests (on a modern Streamable HTTP session closing the response stream is itself the cancellation, so no notification is sent)
  44. - **Metadata**: `icons`, `title` and `_meta` parsed on tools, prompts and resources
  45. - **OAuth 2.1**: PKCE (S256 required), RFC 8414/9728 discovery, RFC 9207 issuer validation, Client ID Metadata Documents, dynamic registration *(deprecated)*, scope step-up challenges
  46. Transports treat the server as untrusted input — see
  47. [Treating the Server as Untrusted](#treating-the-server-as-untrusted) for the
  48. limits applied to peer-controlled data.
  49. ## Quick Connect API (Recommended)
  50. The simplest way to connect to an MCP server:
  51. ```ruby
  52. require 'mcp_client'
  53. # Auto-detect transport from URL
  54. client = MCPClient.connect('http://localhost:8931/mcp') # Streamable HTTP
  55. client = MCPClient.connect('npx -y @modelcontextprotocol/server-filesystem /home') # stdio
  56. client = MCPClient.connect('http://localhost:8000/sse') # SSE (HTTP+SSE: deprecated, use Streamable HTTP)
  57. # With options
  58. client = MCPClient.connect('http://api.example.com/mcp',
  59. headers: { 'Authorization' => 'Bearer TOKEN' },
  60. read_timeout: 60,
  61. retries: 3,
  62. logger: Logger.new($stdout)
  63. )
  64. # Multiple servers
  65. client = MCPClient.connect(['http://server1/mcp', 'http://server2/mcp'])
  66. # Force specific transport
  67. client = MCPClient.connect('http://custom.com/api', transport: :streamable_http)
  68. # Protocol era and extensions (see "MCP 2026-07-28 Features" below)
  69. client = MCPClient.connect('http://api.example.com/mcp',
  70. protocol: :modern, # :auto (default), :modern or :legacy
  71. discover_timeout: 5, # bound on the server/discover probe
  72. extensions: ['io.modelcontextprotocol/tasks'] # extensions the client declares
  73. )
  74. # Use the client
  75. tools = client.list_tools
  76. result = client.call_tool('example_tool', { param: 'value' })
  77. client.cleanup
  78. ```
  79. **Configured headers:** `headers:` values are sent on every request, with one
  80. reserved namespace. On a modern (MCP 2026-07-28) HTTP session the client owns
  81. `Mcp-Param-*`: those headers are derived from a `tools/call`'s own arguments
  82. (the tool's `x-mcp-header` annotations), so any header of that name given in
  83. `headers:` is dropped from modern requests rather than standing in for an
  84. argument the call did not carry. Legacy sessions, where the namespace has no
  85. protocol meaning, send it unchanged.
  86. **Transport Detection:**
  87. | URL Pattern | Transport |
  88. |-------------|-----------|
  89. | Ends with `/sse` | SSE — HTTP+SSE is *deprecated*, prefer Streamable HTTP ([Deprecated features](#deprecated-features)) |
  90. | Ends with `/mcp` | Streamable HTTP |
  91. | `stdio://command` or Array | stdio |
  92. | `npx`, `node`, `python`, etc. | stdio |
  93. | Other HTTP URLs | Auto-detect (Streamable HTTP → SSE → HTTP) — the SSE step is the *deprecated* HTTP+SSE transport, tried only after Streamable HTTP fails ([Deprecated features](#deprecated-features)) |
  94. ## Working with Tools, Prompts & Resources
  95. ```ruby
  96. # Tools
  97. tools = client.list_tools
  98. result = client.call_tool('tool_name', { param: 'value' })
  99. result = client.call_tool('tool_name', { param: 'value' }, server: 'server_name')
  100. # Batch tool calls
  101. results = client.call_tools([
  102. { name: 'tool1', parameters: { key: 'value' } },
  103. { name: 'tool2', parameters: { key: 'value' }, server: 'specific_server' }
  104. ])
  105. # Streaming (SSE/Streamable HTTP)
  106. client.call_tool_streaming('tool', { param: 'value' }).each do |chunk|
  107. puts chunk
  108. end
  109. # Prompts
  110. prompts = client.list_prompts
  111. result = client.get_prompt('greeting', { name: 'Alice' })
  112. # Pagination: list_tools and list_prompts automatically follow the server's
  113. # nextCursor and return the COMPLETE set across all pages (with a per-call
  114. # safety bound and an identical-cursor loop guard). No manual cursor handling
  115. # is required.
  116. # Resources
  117. result = client.list_resources
  118. contents = client.read_resource('file:///example.txt')
  119. contents.each do |content|
  120. puts content.text if content.text?
  121. data = Base64.decode64(content.blob) if content.binary?
  122. end
  123. # Resource update subscriptions (per server)
  124. server = client.servers.first
  125. server.subscribe_resource('file:///example.txt')
  126. server.unsubscribe_resource('file:///example.txt')
  127. ```
  128. `subscribe_resource` answers `true` only once the server has confirmed the
  129. subscription, and raises otherwise — the server's own error, or
  130. `MCPClient::Errors::ResourceReadError` (including when the confirmation does
  131. not arrive within the transport's `read_timeout`). On a 2025-11-25 server the
  132. confirmation is the `resources/subscribe` response; on a 2026-07-28 one it is
  133. the `subscriptions/listen` acknowledgment naming that URI, which the call
  134. waits for. Updates then arrive as `notifications/resources/updated` through
  135. `on_notification`. Every later acknowledgment of that stream is rechecked too:
  136. a stream re-opened after a dropped HTTP connection or a stdio restart is a new
  137. listen request the server may acknowledge more narrowly, so one that comes back
  138. without the URI closes the subscription instead of leaving the resource
  139. reported as watched while nothing watches it — including one that arrives in
  140. the window between the acknowledgment `subscribe_resource` waited for and the
  141. URI being mapped to the stream, which is checked once more with the mapping in
  142. place before the call answers. A stream already mapped to the URI is reused
  143. only while the server is honouring that URI on it *now*: one that has dropped
  144. is waited for — through the HTTP re-open backoff or the stdio handshake, and
  145. on past the replacement request until the server answers it — rather than
  146. reported as a watch on the strength of what the stream that is gone had been
  147. granted, because no server-side subscription exists between listen attempts
  148. and the request that replaces one is a new listen the server holds no state
  149. for and may reject or acknowledge without the URI. Only a stream the server is
  150. actively honouring counts as a live watch, and one that does not become
  151. one — its replacement is refused, or nothing answers within the
  152. acknowledgment timeout — is closed as well as unmapped, so it cannot come back
  153. and deliver the same updates beside the stream that replaces it, and
  154. `unsubscribe_resource` is never left looking for a subscription the mapping no
  155. longer names. The subscriber waiting on its own
  156. listen request is a different matter and still gets its answer: a connection
  157. that drops the moment the acknowledgment arrives does not unanswer it, so the
  158. call does not wait out its acknowledgment timeout for a grant it already
  159. has — while a replacement request that has actually gone out is unanswered
  160. until the server answers *it*.
  161. On a 2026-07-28 server a host can also open a stream of its own with
  162. `server.listen(notifications: { tools_list_changed: true }) { |method, params| … }`
  163. and end it with `subscription.close`. A listen the server never acknowledges is
  164. given up on rather than left pending for ever: `ack_timeout:` bounds the wait
  165. for the acknowledgment (the transport's read timeout by default, `false` to
  166. wait for ever), and one that expires cancels the request and closes the handle
  167. with a `RequestTimeoutError`. It bounds every listen request made for that
  168. subscription, not only the first: an HTTP stream re-opened after a drop, and a
  169. subscription re-sent to the process that replaced the one it was on, are new
  170. requests the server has to acknowledge afresh. The stream itself is not
  171. bounded — once acknowledged it runs for as long as the server keeps it. The block runs on the
  172. subscription's own dispatcher thread, never on the transport's reader, so a
  173. listener may issue requests of its own; the notifications waiting for it are bounded both in
  174. number (`MCPClient::Subscription::MAX_PENDING_NOTIFICATIONS`) and in the bytes
  175. they retain (`MCPClient::Subscription::MAX_PENDING_NOTIFICATION_BYTES`) — a
  176. count alone is not a memory bound when the peer chooses how big each payload
  177. is. Everything a queued notification retains is charged, its method name as
  178. well as its params: a peer tagging `{}` params with a multi-megabyte method
  179. name would otherwise pay two bytes apiece and put a thousand of them behind a
  180. slow listener without touching the byte ceiling. A listener that cannot keep
  181. up with the server loses **repeats**, not signals: whichever ceiling the
  182. arriving notification would breach, the queue gives up the oldest notification
  183. about the same thing as it (same method and
  184. same `uri`/`taskId`), or failing that the oldest of whichever thing has the
  185. most queued, so a stream watching several resources or tasks never loses the
  186. only queued update for a quiet one to make room for a busy one. Every MCP
  187. notification is a "look again" signal about state the host re-reads for itself,
  188. so a later notice of the same thing carries what the dropped one said, while
  189. the only notice of another thing carries what nothing else would. Two rules hold
  190. this together: every queued notification is charged exactly what it retains,
  191. and every eviction gives up an entry whose removal relieves the pressure that
  192. caused it — the byte budget considers only the entries charged against it, the
  193. count ceiling considers them all — so overflow always makes progress and no
  194. signal is spent on pressure that discarding it cannot relieve. A notification
  195. larger than the whole byte budget is not charged against it: it is held in a
  196. slot of its own, and there is only ever one such slot, so it is neither lost
  197. for being large nor able to displace anything else, and what the queue retains
  198. stays within the budget plus one peer-sized payload.
  199. `pending_notifications` / `pending_notification_bytes` /
  200. `dropped_notifications` report how far behind a listener fell. An incoming
  201. notification is routed in a fixed order: subscription bookkeeping (an
  202. acknowledgment, a server-side teardown) first, then the transport and client
  203. cache invalidation, then the delivery to the subscription's listeners, and the
  204. host's `on_notification` listeners **last**. Caches are therefore dropped
  205. *before* a notification reaches the listeners, so a listener reacting to a
  206. `list_changed` notification by calling `list_tools` (or the prompt or resource
  207. equivalents) always re-fetches rather than reading the entry the notification
  208. just invalidated. That holds for the client's caches as well as the
  209. transport's: the client drops its `tool_cache` / `prompt_cache` /
  210. `resource_cache` on the transport's `on_cache_invalidation` hook, which runs at
  211. the invalidation step, rather than on the host callback that runs after the
  212. delivery. A custom transport that emits no such hook — one written against the
  213. older interface, which only calls the notification callback — still has those
  214. caches dropped, on the callback and ahead of everything else there. Everything else the client does with a notification (logging,
  215. progress callbacks, task status) stays behind the delivery, because it is host
  216. code or leads to it. Transports that carry no subscription stream announce the
  217. same hook before their notification callback — the legacy SSE parser, and the
  218. synthetic `tools/list_changed` a `Mcp-Param-*` header-mismatch refresh emits —
  219. so nothing that invalidates a cache is announced on only one of the two.
  220. The host callback comes last because it is the only step
  221. that can block: it is host code and it runs on whatever thread is routing — on
  222. stdio the server process's sole reader — so a callback that issues a
  223. synchronous request of its own would otherwise hold up the delivery while
  224. waiting for a response only that reader can deliver. Queueing the delivery is
  225. all the routing thread does (the listeners themselves run on the
  226. subscription's dispatcher thread), so nothing host-supplied runs ahead of the
  227. callback either way. Being last, the callback can prevent nothing: one that
  228. raises is logged and stops neither the invalidation nor the delivery, and one
  229. that edits the payload it is handed can neither drop nor redirect it — the
  230. subscription a notification belongs to is resolved, and the delivery queued,
  231. before the callback sees it. The requested
  232. filter is copied and frozen when the subscription is created, so a caller that
  233. keeps and mutates the array it passed cannot change the request that goes out
  234. (Streamable HTTP builds it on the stream's own thread) or what a reconnect asks
  235. for. `unsupported` names the requested fields the acknowledgment did not really
  236. grant, read from its values rather than its keys: a `resourceSubscriptions`
  237. echoed with none of the requested URIs, or a flag acknowledged as `false`,
  238. counts as unsupported. `acknowledged` is a frozen copy of what the server
  239. granted, arrays and strings included: the notification it arrives in is handed
  240. to `on_notification` and to the subscription's listeners, and host code editing
  241. it in place must not be able to rewrite the subscription's own record of the
  242. watch. `active?` answers false while a dropped stream
  243. waits to re-open, and a closing response the client cannot recognize (an unknown
  244. `resultType`, a missing or scalar result) fails the subscription instead of
  245. closing it gracefully — as does one that is recognized but says the request has
  246. not finished (`input_required`, which is valid on `tools/call`,
  247. `resources/read` and `prompts/get` alone). On Streamable HTTP closing the SSE response stream *is*
  248. the cancellation, including against a connection that is still opening its
  249. socket: once `close` (or the transport's `cleanup`) returns, either the listen
  250. request was never sent — that session refuses to send one for a closed
  251. subscription, however long its connect takes — or its response stream has been
  252. closed. A listen POST the server answers with a 5xx is treated as a dropped
  253. stream and re-opened on the usual backoff, the way a connection failure or a
  254. read timeout on the very same request is: a brief 500 or 503 no longer ends a
  255. long-lived subscription for good. Only a 4xx, or an authorization challenge,
  256. is the server refusing this subscription, and those still end it.
  257. On stdio a server process that exits on its own is restarted at once
  258. while subscriptions are open, since a host that is only waiting for
  259. notifications never makes the request that would otherwise restart it, and the
  260. subscriptions are re-sent on the new process. An exit *during* the
  261. initialization that established the process counts too: a replacement that
  262. answers the discovery probe and then dies is noticed by its own reader, which
  263. waits out the initialization still in flight and then restarts — otherwise
  264. nothing noticed, the dead connection was marked initialized, the re-sent
  265. listens failed into the "wait for the next process" path, and no reader was
  266. left to establish one. If the process cannot be restarted, or if
  267. the process they were last re-sent to died less than
  268. `MCPClient::ServerStdio::SUBSCRIPTION_RESTART_MIN_INTERVAL` after receiving
  269. them, they end with that error rather than waiting for ever. Only an exit
  270. counts against that bound, never a teardown the client asked for: a host that
  271. calls `cleanup` and reconnects — which every `cleanup`/request cycle does —
  272. tears the process down whenever it likes, and reading that as a crash closed
  273. the very subscriptions the reconnect exists to carry across. The record of
  274. that process answers only that one question, and asking it spends it: a
  275. subscription opened directly on the replacement, after a refusal had already
  276. closed the ones the corpse carried, is judged on its own process's uptime
  277. rather than refused for a crash it had no part in. That interval runs
  278. from the moment that process received them, not from the moment a restart was
  279. attempted, so a server whose start-up alone takes longer is not credited with
  280. its own handshake and respawned for ever; both moments are recorded on the
  281. record of the process itself, and the question is asked in the one place the
  282. subscriptions are handed over, so the bound holds however a host request and
  283. the reader's own restart interleave — whichever of them re-establishes the
  284. process. A restarted process that negotiates a pre-2026-07-28 version cannot
  285. carry them either, and ends them with a `CapabilityError` rather than leaving
  286. them `:reconnecting`. A listen write that fails after the process is gone
  287. leaves the subscription for the next process to be re-sent to instead of
  288. closing it — including when it fails on the hand-over itself, where taking the
  289. new listen id has already moved the subscription off `:reconnecting` and the
  290. stream being torn down would have been the very one the restart was
  291. re-establishing. One that fails after a newer stream replaced it raises only
  292. if that newer stream has itself failed. The subscriptions waiting for a
  293. process live on a single queue behind one lock, and a handle is on it at most
  294. once: a `cleanup` moving the open subscriptions onto it overlaps a failed
  295. hand-over putting one back, and two threads appending to a bare Array can lose
  296. an entry — stranding a stream the spec requires to be re-sent — or duplicate
  297. it and send two listen requests for one subscription. `close` cancels what is
  298. actually outstanding: `notifications/cancelled` names every listen request the
  299. client wrote for that subscription on the live process, not only the id it
  300. happens to be on, while ids written to a process that has since gone are
  301. forgotten rather than cancelled on the one that replaced it. That accounting
  302. holds because a listen request is written to the pipe it was recorded against
  303. rather than to whichever process is current when the write finally happens: a
  304. write still pending when the process exits goes to the process it was opening
  305. on (failing into the paths above once its pipe is closed), never to the
  306. replacement, which would otherwise be serving a second stream whose id the
  307. teardown had already forgotten. On Streamable HTTP the mirror image is
  308. refused rather than deferred — a `listen` whose connection is closed while it
  309. is being opened raises `ConnectionError` instead of POSTing onto a transport
  310. the host has closed, which no later `cleanup` would find.
  311. ## MCP 2026-07-28 Features
  312. The 2026-07-28 revision makes the protocol stateless: there is no
  313. `initialize` handshake, no session and no server-to-client request channel.
  314. Every request carries its own metadata, and anything the server needs from
  315. the client is asked for through the result itself. The client detects which
  316. era a server speaks and adapts; existing code keeps working unchanged.
  317. ### Discovery and per-request metadata
  318. ```ruby
  319. client = MCPClient.connect('http://localhost:8931/mcp')
  320. server = client.servers.first
  321. server.modern? # => true for a 2026-07-28 server
  322. server.protocol_version # => "2026-07-28"
  323. server.protocol_era # => :modern or :legacy
  324. ```
  325. A modern server is recognised by its answer to `server/discover`; every
  326. request then carries `io.modelcontextprotocol/protocolVersion`,
  327. `io.modelcontextprotocol/clientInfo` and
  328. `io.modelcontextprotocol/clientCapabilities` in `_meta`, and on HTTP the
  329. `MCP-Protocol-Version`, `Mcp-Method` and `Mcp-Name` headers. Host-supplied
  330. metadata (a Hash or a callable evaluated per request) is merged into every
  331. request with `MCPClient::Client.new(request_meta: ...)`. Force an era with
  332. `protocol: :modern` / `protocol: :legacy` (default `:auto`) and tune the
  333. probe with `discover_timeout:` on `stdio_config`, `http_config` and
  334. `streamable_http_config` (or the matching server constructors), and on
  335. `MCPClient.connect` for those same three transports. The deprecated HTTP+SSE
  336. transport has no era of its own: `MCPClient::ServerSSE` takes neither option,
  337. so `MCPClient.connect` drops both for an `/sse` URL rather than passing them
  338. on ([Deprecated features](#deprecated-features)) — except `protocol: :modern`,
  339. which an explicit `transport: :sse` refuses with `ArgumentError` rather than
  340. silently connecting legacy.
  341. `ping` maps to `server/discover` and `log_level=` to the per-request log
  342. level on modern servers.
  343. > `log_level=` is deprecated in MCP 2026-07-28 (SEP-2577). On a modern
  344. > server it writes `_meta["io.modelcontextprotocol/logLevel"]`, part of the
  345. > Logging utility the revision marks Deprecated as a whole: new
  346. > implementations SHOULD NOT adopt it. See
  347. > [Deprecated features](#deprecated-features).
  348. Typed errors
  349. carry the JSON-RPC code: `MCPClient::Errors::HeaderMismatchError`
  350. (-32020), `MissingRequiredClientCapabilityError` (-32021) and
  351. `UnsupportedProtocolVersionError` (-32022).
  352. ### Multi round-trip requests
  353. On a modern server `tools/call`, `resources/read` and `prompts/get` may
  354. answer `resultType: "input_required"`. The client fulfils each request in
  355. `inputRequests` with the handlers it already has — the elicitation handler,
  356. the sampling handler and the configured roots — and re-sends the original
  357. request with `inputResponses` and the server's opaque `requestState`. More
  358. than 10 rounds, a request the client cannot honour or a malformed
  359. `inputRequests` raise `MCPClient::Errors::InputRequiredError` (exposing
  360. `input_requests` and `request_state`).
  361. ### URL-mode elicitation
  362. An elicitation handler of arity 2 (or more) is called with the message and a
  363. metadata hash when the server asks for an out-of-band (`url`) interaction.
  364. On a **2025-11-25** server that hash is
  365. `{ 'mode' => 'url', 'url' => ..., 'elicitationId' => ... }`; on a
  366. **2026-07-28** server it is `{ 'mode' => 'url', 'url' => ... }` — the
  367. revision removed `elicitationId` together with
  368. `notifications/elicitation/complete`, because the outcome is learned by
  369. retrying the original request rather than from a server-initiated signal, and
  370. a server that must correlate an elicitation across retries carries its own
  371. identifier in the opaque `requestState`. A modern server that sends
  372. `elicitationId` anyway does not reach the host with it: the field is dropped
  373. and a warning is logged.
  374. ### Custom headers from tool parameters
  375. Tool parameters annotated with `x-mcp-header` are mirrored into
  376. `Mcp-Param-{name}` request headers on `tools/call` (Streamable HTTP and
  377. plain HTTP). A `-32020` HeaderMismatch rejection triggers one `tools/list`
  378. refresh and a retry; tools with invalid annotations are excluded from the
  379. list with a warning. `MCPClient::HeaderParams` exposes the validation.
  380. ### Subscriptions (`subscriptions/listen`)
  381. ```ruby
  382. subscription = client.listen(notifications: { tools_list_changed: true,
  383. resource_subscriptions: ['file:///etc/hosts'] }) do |method, params|
  384. puts "#{method}: #{params.inspect}"
  385. end
  386. subscription.acknowledged # what the server agreed to watch
  387. subscription.unsupported # what it did not
  388. subscription.close
  389. ```
  390. Each subscription is one long-lived `subscriptions/listen` request; on
  391. Streamable HTTP it runs on its own stream and is re-opened with backoff when
  392. the stream drops, on stdio it is re-sent when the process restarts.
  393. `subscribe_resource` / `unsubscribe_resource` map onto listen streams on
  394. modern servers.
  395. ### Cacheable results
  396. `server/discover`, the `*/list` requests and `resources/read` carry
  397. `ttlMs` and `cacheScope`. Lists are served while fresh and re-fetched on
  398. access once stale (a stale list is served with a warning when the re-fetch
  399. fails transiently); `resources/read` results with a `ttlMs` are cached per
  400. URI. Entries with `cacheScope: "private"` are bound to the credentials the
  401. request went out with and never shared across authorization contexts.
  402. `server.cache_info(:tools)` / `cache_info(:read, uri)` expose `ttl_ms`,
  403. `cache_scope`, `received_at` and `fresh`.
  404. ### Tasks extension (`io.modelcontextprotocol/tasks`)
  405. ```ruby
  406. client = MCPClient::Client.new(mcp_server_configs: [...],
  407. extensions: ['io.modelcontextprotocol/tasks'])
  408. result = client.call_tool('long_running', {}) # polls tasks/get transparently
  409. task = client.call_tool_as_task('long_running', {})
  410. task = client.wait_for_task(task, timeout: 120) # answers input_required via tasks/update
  411. task.result if task.completed?
  412. client.cancel_task(task)
  413. ```
  414. Task-augmented calls are opt-in through `extensions:`; a server that
  415. answers `tools/call` with a task is polled at its `pollIntervalMs` until the
  416. task is terminal or its `ttlMs` elapses, and `input_required` tasks are
  417. answered with the elicitation / sampling / roots handlers. `tasks/list` and
  418. `tasks/result` do not exist on 2026-07-28 servers; the legacy task API keeps
  419. working on 2025-11-25 servers.
  420. ### Authorization
  421. `OAuthProvider` records the authorization server's `issuer` with each
  422. authorization request and validates the callback's `iss` per RFC 9207
  423. (`complete_authorization_flow(code, state, iss:)`); client credentials and
  424. tokens are bound to the issuer that produced them, so a server that
  425. switches authorization servers never sees another server's token. Dynamic
  426. Client Registration carries `application_type` and is deprecated in favour
  427. of Client ID Metadata Documents (`client_id_metadata_url:`). See
  428. [OAUTH.md](OAUTH.md).
  429. ### Deprecated features
  430. The 2026-07-28 [deprecated features registry](https://modelcontextprotocol.io/specification/2026-07-28/deprecated)
  431. lists these as Deprecated under the feature lifecycle policy: they keep
  432. working during their deprecation window, but new integrations should not
  433. adopt them. The earliest removal is the registry's own, and it names a
  434. *revision*, not a date: what the features 2026-07-28 deprecates wait for is
  435. the first revision released on or after 2027-07-28, which may itself land
  436. well after that date — do not plan around 2027-07-28 as a removal date. The
  437. `includeContext` values follow Sampling, and only the HTTP+SSE transport has
  438. a clock of its own. The earliest removal is when a feature becomes
  439. *eligible* for removal; the actual removal is a Core Maintainer decision
  440. taken during release preparation. The client logs one notice per feature per
  441. process on first use, naming the earliest removal and the suggested
  442. migration:
  443. | Feature | Deprecated since | Earliest removal | Migration |
  444. |---------|------------------|------------------|-----------|
  445. | Roots (`roots:`, `Client#roots=`, or answering a `roots/list` request with a non-empty list) | 2026-07-28 (SEP-2577) | the first revision released on or after 2027-07-28 | Pass directories or files through tool parameters, resource URIs or server configuration |
  446. | Sampling (`sampling_handler:` on `Client.new` or `MCPClient.connect`, or serving a request through a transport's `on_sampling_request`) | 2026-07-28 (SEP-2577) | the first revision released on or after 2027-07-28 | Integrate directly with the LLM provider API |
  447. | Logging (`log_level=` on the client or a server, an `io.modelcontextprotocol/logLevel` in `request_meta` or a per-call `_meta`, `notifications/message`) | 2026-07-28 (SEP-2577) | the first revision released on or after 2027-07-28 | Log to stderr (stdio) or use OpenTelemetry |
  448. | HTTP+SSE transport (`MCPClient::ServerSSE`, warned once it is connected) | 2025-03-26 (reclassified by SEP-2596) | three months after SEP-2596 reaches Final | Migrate the server to Streamable HTTP |
  449. | `includeContext` `"thisServer"` / `"allServers"` in sampling requests | 2025-11-25 (reclassified by SEP-2596) | follows Sampling (SEP-2577) | Servers omit the field or send `"none"` |
  450. | OAuth Dynamic Client Registration | 2026-07-28 (PR #2858) | the first revision released on or after 2027-07-28 | Client ID Metadata Documents or pre-registered credentials |
  451. A client that never adopted Roots is never warned about them. It registers a
  452. `roots/list` handler on every server unconditionally, so that a later
  453. `client.roots = [...]` is served without reconnecting, and until a root is set
  454. it answers `roots/list` with an empty list — an empty answer exposes nothing
  455. deprecated, so it raises no notice. The notice fires when the host configures
  456. `roots:`, calls `Client#roots=`, or serves an answer that actually carries a
  457. root (including from a transport driven directly, without a `Client`).
  458. `MCPClient::Deprecations::REGISTRY` lists them, each with its
  459. `earliest_removal`; set
  460. `MCPClient::Deprecations.enabled = false` (before constructing clients) to
  461. silence the notices. Notices go to the logger the client or server was
  462. given; without one they go to the default `$stdout` logger like every other
  463. warning. A notice costs the deprecated operation exactly what one
  464. `logger.warn` costs it, and no more: a logger that raises, drops the notice
  465. or writes nowhere (`Logger.new(nil)`, or one whose device has been closed) is
  466. swallowed, so the feature keeps working and the notice stays owed to a later
  467. use — but a logger that blocks, blocks its caller here just as it does
  468. everywhere else in the library. One failure is beyond reach: a standard
  469. `Logger` over an open device that fails to write hides that from its caller
  470. (it reports it on `$stderr` only and returns as if it had written), so that
  471. notice is spent; a closed device is recognised, a broken one is not. A logger the host wrapped is asked through
  472. the wrapper (`warn?`, and the device of the `Delegator` it holds), so a
  473. tagged, broadcast or hand-rolled wrapper above WARN leaves the notice owed
  474. rather than spending it on a line nobody reads; a wrapper that filters on
  475. something a level cannot express — a tag, a source allow-list — cannot be
  476. asked, and does spend it.
  477. Nothing ever waits for a notice. A caller that meets one already in flight —
  478. another thread's first use, or a formatter, log subscriber, audit hook or
  479. `level` accessor that reaches a deprecated feature from inside the notice
  480. being written — stands down at once instead of queueing behind it. Queueing would be worth a
  481. deadlock, since the thread writing a notice holds the logger and the thread
  482. that would queue may be holding a lock that logger needs (an ordinary
  483. `logger.info` holds exactly such a lock while its device runs). And it would
  484. buy nothing: whoever holds the notice is writing it, and if their logger
  485. fails or filters the warning the notice is owed again, so the feature's next
  486. use raises it.
  487. ## MCP 2025-11-25 Features
  488. ### Tool Annotations
  489. ```ruby
  490. tool = client.find_tool('delete_user')
  491. # Hint-style annotations (MCP 2025-11-25)
  492. # Defaults follow the MCP ToolAnnotations schema: when a hint is absent the
  493. # client assumes the less-safe value, so an un-annotated tool is treated as
  494. # writable, potentially destructive, and open-world.
  495. tool.read_only_hint? # Defaults to false; tool may modify its environment
  496. tool.destructive_hint? # Defaults to true; tool may perform destructive updates
  497. tool.idempotent_hint? # Defaults to false; repeated calls may have additional effects
  498. tool.open_world_hint? # Defaults to true; tool may interact with external entities
  499. # Legacy annotations
  500. tool.read_only? # Safe to execute?
  501. tool.destructive? # Warning: destructive operation
  502. tool.requires_confirmation? # Needs user confirmation
  503. ```
  504. ### Structured Outputs
  505. ```ruby
  506. tool = client.find_tool('get_weather')
  507. tool.structured_output? # Has output schema?
  508. tool.output_schema # JSON Schema for output
  509. result = client.call_tool('get_weather', { location: 'SF' })
  510. data = result['structuredContent'] # Type-safe structured data
  511. # Per MCP 2025-11-25, clients SHOULD validate structured results against the
  512. # tool's output schema, and a tool that declares an outputSchema must return
  513. # structuredContent in successful results. call_tool checks both automatically
  514. # (so does call_tool_streaming, for a chunk that is a complete result, and so
  515. # does a task's result), against the JSON Schema vocabulary this client
  516. # evaluates: type, enum/const, properties/required, patternProperties,
  517. # additionalProperties, propertyNames, minProperties/maxProperties,
  518. # dependentRequired/dependentSchemas (draft-07 dependencies),
  519. # items/prefixItems/additionalItems, minItems/maxItems, uniqueItems (JSON
  520. # equality, so an object is never equal to an array), contains with
  521. # minContains/maxContains, string bounds and pattern (an ECMA-262 regular
  522. # expression, translated before it is matched), numeric bounds and multipleOf,
  523. # allOf/anyOf/oneOf/not, if/then/else, $ref/$defs/definitions inside the
  524. # document, and unevaluatedItems/unevaluatedProperties from the annotations
  525. # the whole composition produces (what properties/patternProperties/
  526. # additionalProperties, prefixItems/items/contains and the two keywords
  527. # themselves evaluated, collected through every $ref/allOf/anyOf/oneOf/
  528. # if-then-else/dependentSchemas that passed — never from a cousin). A
  529. # $dynamicRef or $recursiveRef that names no dynamic anchor is the plain
  530. # reference it resolves to and is applied as one; one that does binds to the
  531. # outermost resource of the DYNAMIC SCOPE declaring that anchor — the
  532. # resources the evaluation actually entered, tracked as it enters them, so a
  533. # duplicate anchor in a resource the instance never enters decides nothing.
  534. # What is NOT evaluated is the two keywords that only annotate
  535. # (format, contentSchema). When a schema uses one of those, call_tool logs a
  536. # "validation is partial" warning naming them (in both modes), since data may
  537. # pass this check that a full validator would reject; an unevaluated keyword
  538. # is never read as a match for not/oneOf/if either. A pattern is bounded to
  539. # 10,000 characters and must be an ECMA-262 expression (Ruby-only syntax such
  540. # as inline flags or possessive quantifiers makes the schema unusable). Two
  541. # ECMA-262 constructs Ruby's engine cannot reproduce — a back-reference to a
  542. # group a quantifier repeats (ECMA-262 clears it at each iteration, Ruby
  543. # keeps it) and a variable-length lookbehind — make the schema unusable too,
  544. # rather than being answered under the other engine's rules. By default a
  545. # violation (mismatch, or missing structuredContent on a successful result)
  546. # logs a warning; opt in to strict mode to raise instead:
  547. client = MCPClient::Client.new(
  548. mcp_server_configs: [...],
  549. validate_structured_content: :strict # raises MCPClient::Errors::ValidationError on violation
  550. )
  551. # A task-delivered result (get_task_result) is validated the same way when the
  552. # task is named with a Task handle: the handle call_tool_as_task returns carries
  553. # the definition its creating call went out under, and every handle of that task
  554. # keeps it — the one a get_task refresh returns, and the one a wait_for_task
  555. # hands back. A bare task ID identifies no tool, so a result fetched by ID is
  556. # not validated.
  557. ```
  558. A result is checked against the tool definition the request that produced it
  559. went out under. That matters on a modern HTTP session, where a `HeaderMismatch`
  560. rejection makes the client refresh `tools/list` and retry with recomputed
  561. `Mcp-Param-*` headers: the retry is answered under the refreshed definition, so
  562. that is the one it is validated against. A `tools/list_changed` that merely
  563. arrives while the call is in flight never changes the definition the result is
  564. checked against — the server never saw the replacement.
  565. What counts as structured content follows the revision the session was
  566. negotiated to. MCP 2026-07-28 widened `structuredContent` to any JSON value,
  567. so a present `null`, array, string, number or boolean is structured content
  568. and is validated against the output schema. MCP 2025-11-25 types it as an
  569. object: on a session negotiated to that revision anything else is no
  570. structured content at all, and a tool that declares an `outputSchema` and
  571. sends one is reported as having returned none. A transport that cannot say
  572. which revision it negotiated is not assumed legacy.
  573. #### JSON Schema dialects and references
  574. The built-in validator reads JSON Schema 2020-12 (the MCP default), 2019-09
  575. and draft-07. Per MCP 2026-07-28 an unsupported dialect must be reported as
  576. an error, so a tool whose `inputSchema` declares one this client does not
  577. implement is refused before the request is sent:
  578. ```ruby
  579. # inputSchema: {"$schema": "urn:unknown-dialect", ...}
  580. client.call_tool('t', {})
  581. # => raises MCPClient::Errors::ValidationError:
  582. # "...input schema declares the JSON Schema dialect \"urn:unknown-dialect\":
  583. # that dialect is not supported (supported: ...)"
  584. ```
  585. The same applies to an `outputSchema`: an unsupported dialect there raises a
  586. `ValidationError` in both modes, since the client cannot read the schema at
  587. all — unlike a structured-content mismatch, which the
  588. `validate_structured_content` mode decides. The definition checked is the one
  589. the answered request actually went out under, so a `HeaderMismatch` retry
  590. under a refreshed schema is covered too — and since the rejection means the
  591. server did not execute the attempt, a refreshed `inputSchema` whose dialect
  592. this client cannot read stops the retry before it is sent rather than after
  593. the tool has run. A schema that is merely unusable for another reason (a
  594. `$ref` that would need a network fetch, a document past the resource bounds,
  595. a malformed keyword value — the metadata keywords included, which must be
  596. written as the type JSON Schema gives them) is warned about, and for an input
  597. schema the call still goes out, since the server owns argument validation.
  598. Two schema resources may not answer to one URI: a document whose `$id`s (or
  599. whose `$anchor` names within one resource) collide is unusable, since which
  600. declaration a reference lands on would otherwise depend on the order the
  601. document was read in.
  602. References are resolved inside the document only — nothing is ever fetched —
  603. but a document that bundles the resources it uses is resolved in full: a
  604. `$ref` naming an embedded `$id` (`"urn:example:s"`, a relative URI against the
  605. base an enclosing `$id` established, or the empty reference `""`) resolves to
  606. that resource, and only a reference to a resource the document does not carry
  607. is reported as external. Under 2020-12 and 2019-09 `definitions` behaves as
  608. the `$defs` it was renamed from, as the meta-schema of both dialects retains
  609. it.
  610. ### Roots
  611. > Deprecated in MCP 2026-07-28 (SEP-2577); see [Deprecated features](#deprecated-features).
  612. ```ruby
  613. # Set filesystem scope boundaries
  614. client.roots = [
  615. { uri: 'file:///home/user/project', name: 'Project' },
  616. { uri: 'file:///var/log', name: 'Logs' }
  617. ]
  618. # Access current roots
  619. client.roots
  620. ```
  621. ### Sampling (Server-requested LLM completions)
  622. > Deprecated in MCP 2026-07-28 (SEP-2577); see [Deprecated features](#deprecated-features).
  623. ```ruby
  624. # Configure handler when creating client
  625. client = MCPClient.connect('http://server/mcp',
  626. sampling_handler: ->(messages, model_prefs, system_prompt, max_tokens) {
  627. # Process server's LLM request
  628. {
  629. 'model' => 'gpt-4',
  630. 'stopReason' => 'endTurn',
  631. 'role' => 'assistant',
  632. 'content' => { 'type' => 'text', 'text' => 'Response here' }
  633. }
  634. }
  635. )
  636. ```
  637. Sampling histories are checked before the handler runs (MCP 2026-07-28
  638. client/sampling: both parties SHOULD validate message content): every message
  639. needs a `"user"`/`"assistant"` role and content, a user message holding tool
  640. results holds nothing else, and each assistant tool use is answered by the user
  641. message that follows it. A malformed history is refused with `-32602` (or fails
  642. the multi round-trip locally on a 2026-07-28 server) and the handler is not
  643. invoked.
  644. A multi round-trip request may wait on an interaction that happens out of band
  645. (a URL-mode elicitation): the server keeps answering with only a
  646. `requestState`, and the client retries with a growing pause. The host steers
  647. that wait, and can resume a request it stopped:
  648. ```ruby
  649. client.on_input_required_wait do |wait|
  650. # wait.rpc_method, wait.round_trip, wait.delay, wait.request_state,
  651. # wait.result, wait.elapsed
  652. :cancel if user_pressed_cancel? # :retry retries now; anything else waits the pace
  653. end
  654. begin
  655. client.call_tool('checkout', { 'cart' => cart })
  656. rescue MCPClient::Errors::InputRequiredError => e
  657. # e.resumable? — the continuation (e.request_method, e.request_params,
  658. # e.request_state) is carried by every error the round trip raises
  659. client.resume_input_required(e) if e.resumable? && user_pressed_retry?
  660. end
  661. ```
  662. A wait never runs past the timeout the request runs under either — the one
  663. given to the call, or the transport's configured `read_timeout` when the call
  664. named none — and the time your own control spends deciding counts against it.
  665. The error it raises then is resumable in the same way.
  666. Sampling tool calling (SEP-1577) is opt-in: pass `sampling_supports_tools: true`
  667. to declare the `sampling.tools` capability. The handler then receives the full
  668. request params (including `tools`/`toolChoice`) as an optional fifth argument;
  669. without the opt-in, tool-enabled sampling requests are rejected with `-32602`
  670. as the spec requires. On a 2026-07-28 server, where sampling arrives as an
  671. input request inside a multi round-trip answer and `inputResponses` has no
  672. per-request error channel, the same rejection fails the whole round trip with
  673. `MCPClient::Errors::InputRequiredError` and the handler is never invoked:
  674. ```ruby
  675. client = MCPClient::Client.new(
  676. mcp_server_configs: [...],
  677. sampling_supports_tools: true,
  678. sampling_handler: ->(messages, prefs, system_prompt, max_tokens, params = nil) {
  679. tools = params && params['tools'] # ToolUseContent may be returned in content
  680. # ...
  681. }
  682. )
  683. ```
  684. ### Progress Tracking
  685. Attach a per-call progress callback — the client generates a unique
  686. `progressToken`, places it in the request `_meta`, and routes matching
  687. `notifications/progress` to your block while the request is active (stale
  688. tokens after completion are dropped):
  689. ```ruby
  690. client.call_tool('long_running', args, progress: ->(progress, total, message) {
  691. puts "#{message}: #{progress}/#{total}"
  692. })
  693. ```
  694. A request-level `_meta` (e.g. a hand-picked `progressToken`) can also be passed
  695. inside the arguments under the `'_meta'` key on every transport — it is hoisted
  696. to the JSON-RPC params level on the wire, never sent as a tool argument.
  697. ### Timeouts and Cancellation
  698. Timeouts are configurable per request in addition to the per-server
  699. `read_timeout`. A timed-out request raises
  700. `MCPClient::Errors::RequestTimeoutError` (a `TransportError` subclass), is
  701. **never** silently re-sent by the retry layer, and a best-effort
  702. `notifications/cancelled` is sent for the abandoned request (never for
  703. `initialize`, and task-augmented calls use `tasks/cancel` instead):
  704. ```ruby
  705. client.send_rpc('tools/call', params: { name: 'slow', arguments: {} }, timeout: 300)
  706. server.rpc_request('tools/list', {}, timeout: 5)
  707. ```
  708. ### Client Identity and Server Instructions
  709. Hosts can present their own `Implementation` info (sent as `clientInfo` during
  710. initialize; `name` and `version` required — `title`, `description`,
  711. `websiteUrl`, `icons` optional), and read the server's `instructions` hint
  712. after connecting:
  713. ```ruby
  714. client = MCPClient::Client.new(
  715. mcp_server_configs: [...],
  716. client_info: { 'name' => 'my-ide', 'version' => '2.0.0', 'description' => 'An MCP-powered IDE' }
  717. )
  718. client.servers.first.connect
  719. puts client.servers.first.instructions # e.g. "Use the search tool before answering."
  720. ```
  721. ### Capability Gating
  722. Optional server features (`logging/setLevel`, `resources/subscribe`,
  723. `completion/complete`, `tasks/list`, `tasks/cancel`) are only sent to servers
  724. that negotiated the corresponding capability; otherwise
  725. `MCPClient::Errors::CapabilityError` is raised (the lifecycle forbids using
  726. capabilities that were not negotiated). `Client#log_level=` skips
  727. non-logging servers instead of failing. Declared *client* capabilities are
  728. derived from what the host actually registered (handlers, roots), never
  729. hardcoded — and they gate the client's own traffic too:
  730. `notifications/roots/list_changed` goes only to a session that declared
  731. `roots` (never to a 2026-07-28 server, which removed the notification, and
  732. never to plain HTTP on a legacy session, which has no server-request channel
  733. to serve roots on).
  734. ### Completion (Autocomplete)
  735. ```ruby
  736. result = client.complete(
  737. ref: { type: 'ref/prompt', name: 'greeting' },
  738. argument: { name: 'name', value: 'A' }
  739. )
  740. # => { 'values' => ['Alice', 'Alex'], 'total' => 100, 'hasMore' => true }
  741. ```
  742. ### Logging
  743. > Deprecated in MCP 2026-07-28 (SEP-2577); see [Deprecated features](#deprecated-features).
  744. ```ruby
  745. # Set log level
  746. client.log_level = 'debug' # debug/info/notice/warning/error/critical
  747. # Handle log notifications
  748. client.on_notification do |server, method, params|
  749. if method == 'notifications/message'
  750. puts "[#{params['level']}] #{params['logger']}: #{params['data']}"
  751. end
  752. end
  753. ```
  754. ### Tasks (Long-running, task-augmented tools)
  755. A task-capable server (one advertising `tasks.requests.tools.call`) can run a tool
  756. whose `execution.taskSupport` is `optional` or `required` as a background task:
  757. the call returns immediately with a task handle, and the result is fetched later.
  758. Try it locally: `python3 examples/echo_server_streamable.py &` then
  759. `./examples/tasks_example.rb` runs the full lifecycle against a task-capable
  760. demo server.
  761. On MCP 2026-07-28 the client must declare the extension for the server to be
  762. allowed to answer with a task at all:
  763. ```ruby
  764. client = MCPClient::Client.new(mcp_server_configs: [...],
  765. extensions: ['io.modelcontextprotocol/tasks'])
  766. tool = client.find_tool('long_job')
  767. tool.supports_task? # execution.taskSupport is optional/required?
  768. # Create the task (returns immediately). The server sets the lifetime it
  769. # grants (ttlMs) and the pace it wants to be polled at (pollIntervalMs).
  770. task = client.call_tool_as_task('long_job', { input: 'data' })
  771. # Drive the whole lifecycle: polls tasks/get at the server's pace, answers
  772. # any inputRequests through your elicitation/sampling handlers with
  773. # tasks/update, and returns the finished task.
  774. finished = client.wait_for_task(task)
  775. result = finished.result # the CallToolResult the task produced
  776. # Or step it yourself
  777. until task.terminal? || task.input_required?
  778. sleep((task.poll_interval || 1000) / 1000.0)
  779. task = client.get_task(task) # tasks/get, routed to the task's own server
  780. end
  781. result = client.get_task_result(task) # read from tasks/get on 2026-07-28
  782. client.cancel_task(task) # tasks/cancel
  783. ```
  784. On a 2026-07-28 server `tasks/result` and `tasks/list` are gone: the outcome
  785. is read from `tasks/get`, `client.list_tasks` raises, and a `ttl:` passed to
  786. `call_tool_as_task` is ignored (the server grants `ttlMs`). Against a
  787. 2025-11-25 server the earlier surface still applies — `ttl:` is sent,
  788. `get_task_result` uses `tasks/result`, and `client.list_tasks` pages
  789. `tasks/list`.
  790. Task IDs are only unique within the server that issued them, so pass the `Task`
  791. returned by `call_tool_as_task` — it carries its own server. A bare task ID also
  792. works when the client has a single server; with several servers configured it
  793. raises `ArgumentError` rather than guessing, so name the server explicitly:
  794. ```ruby
  795. client.get_task('task-123', server: 'my-server')
  796. # React to server-pushed status updates
  797. client.on_notification do |server, method, params|
  798. puts "Task #{params['taskId']} -> #{params['status']}" if method == 'notifications/tasks/status'
  799. end
  800. ```
  801. Notifications announce; they do not drive. A `notifications/tasks` (2026-07-28,
  802. on a `listen` stream) that carries `inputRequests` reaches the listeners exactly
  803. as it arrived — the client answers input requests only inside `wait_for_task`
  804. (and `call_tool`), or when the host sends the answers itself with
  805. `update_task`. A host that follows a task through notifications hands it to
  806. `wait_for_task` when it wants the requests answered.
  807. Handles outlive a process only as far as the host keeps them: `task.to_h`
  808. serializes a handle, and `MCPClient::Task.from_json(hash, server: server)` (or
  809. the bare `taskId` with `server:`) names the same task in another client, which
  810. can `get_task`, `wait_for_task` or `cancel_task` it. Every handle a creation, a
  811. `get_task` refresh, a `wait_for_task` or a cancellation hands back within one
  812. client also names the *lifetime* of its task: once the server has handed the
  813. same id to a new task, that handle raises `TaskReplacedError` instead of
  814. reaching the replacement.
  815. ### Elicitation (Server-initiated user interactions)
  816. ```ruby
  817. client = MCPClient::Client.new(
  818. mcp_server_configs: [MCPClient.stdio_config(command: 'python server.py')],
  819. elicitation_handler: ->(message, schema) {
  820. puts "Server asks: #{message}"
  821. # Return: { 'action' => 'accept', 'content' => { 'field' => 'value' } }
  822. # Or: { 'action' => 'decline' } or { 'action' => 'cancel' }
  823. }
  824. )
  825. ```
  826. In form mode the handler may return the content on its own (`{ 'field' =>
  827. 'value' }`), which is sent as an `accept`. An explicit `action` must be one of
  828. `accept`, `decline` or `cancel` — any other value is answered `cancel`, since
  829. it is not consent the user gave.
  830. In URL mode the handler's second argument is `{ 'mode' => 'url', 'url' => ... }`
  831. on a **2026-07-28** server and
  832. `{ 'mode' => 'url', 'url' => ..., 'elicitationId' => ... }` on a **2025-11-25**
  833. one: the newer revision removed `elicitationId`, so a host must not expect that
  834. key from a modern server (see
  835. [URL-mode elicitation](#url-mode-elicitation)). Its answer is
  836. consent, not data: only an explicit `action` of `accept`, `decline` or `cancel`
  837. (or a literal `true` for accept) counts — anything else is answered `cancel`.
  838. `content` is dropped, since it is form-mode only, while a handler-supplied
  839. `_meta` is passed through.
  840. ## Advanced Configuration
  841. For more control, use `create_client` with explicit configs:
  842. ```ruby
  843. client = MCPClient.create_client(
  844. mcp_server_configs: [
  845. MCPClient.stdio_config(command: 'npx server', name: 'local'),
  846. # HTTP+SSE is deprecated (SEP-2596): keep this only for an existing SSE
  847. # server, and prefer Streamable HTTP (streamable_http_config below) for
  848. # anything new. See "Deprecated features".
  849. MCPClient.sse_config(
  850. base_url: 'https://api.example.com/sse',
  851. headers: { 'Authorization' => 'Bearer TOKEN' },
  852. read_timeout: 30, ping: 10, retries: 3
  853. ),
  854. MCPClient.http_config(
  855. base_url: 'https://api.example.com',
  856. endpoint: '/rpc',
  857. headers: { 'Authorization' => 'Bearer TOKEN' }
  858. ),
  859. MCPClient.streamable_http_config(
  860. base_url: 'https://api.example.com/mcp',
  861. read_timeout: 60, retries: 3
  862. )
  863. ],
  864. logger: Logger.new($stdout)
  865. )
  866. # Or load from JSON file
  867. client = MCPClient.create_client(server_definition_file: 'servers.json')
  868. ```
  869. ### Retries
  870. The `retries:` option controls automatic retry with exponential backoff. Only
  871. failures where the request most likely did **not** complete at the server are
  872. retried: transport/network errors and HTTP **5xx** responses. Application-level
  873. failures — a JSON-RPC error response or an HTTP **4xx** — are **never** retried,
  874. because the server already processed or rejected the request. Retryable server
  875. failures raise `MCPClient::Errors::TransientServerError`, a subclass of
  876. `MCPClient::Errors::ServerError`, so existing `rescue ServerError` handlers are
  877. unaffected.
  878. **`tools/call` is never retried automatically.** Even a "transient" failure can
  879. arrive *after* the server executed the request, and JSON-RPC has no idempotency
  880. key that would make a replay safe — so a retry could run a side effect twice.
  881. Retry a tool call explicitly if your application knows it is safe to repeat, and
  882. treat the raised error as *outcome unknown* rather than *not executed*:
  883. ```ruby
  884. begin
  885. client.call_tool('send_invoice', { customer: 'acme' })
  886. rescue MCPClient::Errors::TransportError => e
  887. # The server may or may not have sent the invoice. Check before retrying.
  888. end
  889. ```
  890. The same reasoning excludes `RequestTimeoutError` and `ResponseTooLargeError`
  891. from retries, and applies to session recovery: if a `tools/call` comes back with
  892. an expired-session 404, the client starts a fresh session but does **not** re-send
  893. the call — it raises so you can decide. Idempotent requests are re-sent against
  894. the new session as before.
  895. **One exception: a broken response stream on a modern (MCP 2026-07-28)
  896. Streamable HTTP connection.** That revision removed SSE resumability and requires
  897. that a broken response stream loses the in-flight request, which clients **MUST**
  898. re-issue as a new request with a new request ID — with no exception for
  899. `tools/call`. It can require that safely because closing the response stream *is*
  900. the cancellation signal: the server **MUST** treat the break as a cancellation of
  901. that request, stop work as soon as practical, and send nothing further for it. So
  902. when a modern response stream ends without the result, the client sends the call
  903. again once with a fresh request id; if that stream breaks too, it raises
  904. `MCPClient::Errors::ResponseStreamClosedError` rather than trying again. Every
  905. other ambiguous failure is unchanged and still never re-sent, because in none of
  906. those cases was the server told to stop.
  907. A response that *did* arrive is not ambiguous, so it is never replaced: the
  908. client reads response bodies as they stream in, and a socket that dies after
  909. the final SSE event returns the result it already carried instead of calling
  910. the tool a second time.
  911. ### Response Size Limits (Streamable HTTP)
  912. A gzip-encoded response is decompressed incrementally and abandoned once it
  913. expands past `max_decompressed_body_bytes` (default **64 MiB**), so a small
  914. highly-compressed body cannot exhaust memory. Exceeding it raises
  915. `MCPClient::Errors::ResponseTooLargeError`.
  916. Raise the limit if you legitimately exchange very large payloads — base64
  917. resource blobs or audio — so that whether a response is accepted does not depend
  918. on the server's choice to compress it:
  919. ```ruby
  920. MCPClient.streamable_http_config(
  921. base_url: 'https://api.example.com/mcp',
  922. max_decompressed_body_bytes: 256 * 1024 * 1024
  923. )
  924. ```
  925. ### Faraday Customization
  926. ```ruby
  927. MCPClient.http_config(base_url: 'https://internal.company.com') do |faraday|
  928. faraday.ssl.cert_store = custom_cert_store
  929. faraday.ssl.verify = true
  930. end
  931. ```
  932. Response middleware you add here is respected on both paths: if a
  933. `conn.response :json` middleware (with or without `conn.response :raise_error`)
  934. has already decoded the body, a successful result is read from the decoded
  935. object rather than parsed a second time, and the JSON-RPC error an HTTP 4xx
  936. carries is still recognized, so a protocol rejection keeps its `code`, `data`
  937. and typed error class instead of degrading to a bare `ServerError`.
  938. ### Server Definition JSON
  939. ```json
  940. {
  941. "mcpServers": {
  942. "filesystem": {
  943. "type": "stdio",
  944. "command": "npx",
  945. "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home"]
  946. },
  947. "api": {
  948. "type": "streamable_http",
  949. "url": "https://api.example.com/mcp",
  950. "headers": { "Authorization": "Bearer TOKEN" }
  951. }
  952. }
  953. }
  954. ```
  955. ## AI Integration Examples
  956. ### OpenAI
  957. ```ruby
  958. require 'mcp_client'
  959. require 'openai'
  960. mcp = MCPClient.connect('npx -y @modelcontextprotocol/server-filesystem .')
  961. tools = mcp.to_openai_tools
  962. client = OpenAI::Client.new(api_key: ENV['OPENAI_API_KEY'])
  963. response = client.chat.completions.create(
  964. model: 'gpt-4',
  965. messages: [{ role: 'user', content: 'List files' }],
  966. tools: tools
  967. )
  968. ```
  969. ### Anthropic
  970. ```ruby
  971. require 'mcp_client'
  972. require 'anthropic'
  973. mcp = MCPClient.connect('npx -y @modelcontextprotocol/server-filesystem .')
  974. tools = mcp.to_anthropic_tools
  975. client = Anthropic::Client.new(access_token: ENV['ANTHROPIC_API_KEY'])
  976. # Use tools with Claude API
  977. ```
  978. ### RubyLLM
  979. ```ruby
  980. require 'mcp_client'
  981. require 'ruby_llm'
  982. RubyLLM.configure { |c| c.openai_api_key = ENV['OPENAI_API_KEY'] }
  983. mcp = MCPClient.connect('http://localhost:8931/mcp') # Playwright MCP
  984. # Wrap each MCP tool as a RubyLLM tool
  985. tools = mcp.list_tools.map do |t|
  986. tool_name = t.name
  987. Class.new(RubyLLM::Tool) do
  988. description t.description
  989. params t.schema
  990. define_method(:name) { tool_name }
  991. define_method(:execute) { |**args| mcp.call_tool(tool_name, args) }
  992. end.new
  993. end
  994. chat = RubyLLM.chat(model: 'gpt-4o-mini')
  995. tools.each { |tool| chat.with_tool(tool) }
  996. response = chat.ask('Navigate to google.com and tell me the page title')
  997. ```
  998. See `examples/` for complete implementations:
  999. - `ruby_openai_mcp.rb`, `openai_ruby_mcp.rb` - OpenAI integration
  1000. - `ruby_anthropic_mcp.rb` - Anthropic integration
  1001. - `gemini_ai_mcp.rb` - Google Vertex AI integration
  1002. - `ruby_llm_mcp.rb` - RubyLLM integration (OpenAI provider)
  1003. ## Running the Examples
  1004. The `examples/run_all_examples.sh` harness runs every example that can run on the current machine — self-contained stdio servers, the Python/Flask/FastMCP echo and elicitation servers, `npx`-based MCP servers, and (optionally) the paid LLM integrations. It starts and tears down each server automatically and prints a `PASS`/`FAIL`/`SKIP` summary. `tasks_example.rb` runs against the local `echo_server_streamable.py`; `oauth_browser_auth.rb` is interactive and only runs when you opt in with `RUN_OAUTH=1`.
  1005. ### Prerequisites
  1006. Run `bundle install` first. The script preflight-checks the following and prints a warning (it does **not** abort) for anything missing; affected examples are then skipped or fail:
  1007. - `ruby`, `bundle`, `curl`, `lsof` - on `PATH`
  1008. - `python3` (or `$PYTHON`) plus a separate `python` binary - on `PATH`
  1009. - Python packages `flask`, `fastmcp`, `mcp` - importable by `$PYTHON`
  1010. - `npx` (Node) - needed by the `npx`-based example (`json_input`) and by every LLM example, which spawn `npx` filesystem/Playwright servers
  1011. ### Usage
  1012. ```bash
  1013. examples/run_all_examples.sh # run everything runnable on this machine
  1014. RUN_AI=0 examples/run_all_examples.sh # skip the paid-LLM examples
  1015. RUN_NPX=0 examples/run_all_examples.sh # skip the npx-based example (json_input)
  1016. LOG_DIR=/path examples/run_all_examples.sh # write logs to a chosen dir
  1017. PYTHON=python3.12 TIMEOUT=180 examples/run_all_examples.sh # override interpreter and per-example timeout
  1018. ```
  1019. ### Environment Knobs
  1020. | Variable | Default | Effect |
  1021. |----------|---------|--------|
  1022. | `RUN_AI` | `1` | Set to `0` to skip the LLM integrations, which make **real, paid** API calls. |
  1023. | `RUN_NPX` | `1` | Set to `0` (or leave `npx` off `PATH`) to skip the `npx`-based example (`json_input`). The LLM examples spawn `npx` servers too, but are gated by `RUN_AI` and their API keys instead. |
  1024. | `PYTHON` | `python3` | Interpreter used to launch the Python/Flask/FastMCP servers and run the import preflight checks. |
  1025. | `TIMEOUT` | `120` | Per-example wall-clock timeout in seconds; a timeout is reported as a `FAIL`. |
  1026. | `LOG_DIR` | fresh `mktemp` dir | Directory for per-example and per-server logs; the path is printed after preflight and in the summary. |
  1027. ### Secrets and API Keys
  1028. Real secrets live in `examples/secrets.env`, which is **gitignored** and sourced automatically (every `KEY=value` line is exported) when present. Copy the tracked template to get started:
  1029. ```bash
  1030. cp examples/secrets.env.example examples/secrets.env
  1031. # then set ZAPIER_MCP_TOKEN=... to enable the Zapier streamable-HTTP example
  1032. ```
  1033. Set `ZAPIER_MCP_TOKEN` (from the Zapier MCP setup page, "Option 1: Authorization header") to run `streamable_http_example.rb` and `oauth_example.rb` against Zapier; override `ZAPIER_MCP_URL` if your connect URL differs. To run the interactive `oauth_browser_auth.rb`, set `MCP_SERVER_URL` (e.g. an ngrok tunnel to your OAuth-protected MCP server) in `secrets.env` and pass `RUN_OAUTH=1`. The LLM examples each need their own credentials in the environment and are skipped without them:
  1034. - `ruby_anthropic_mcp.rb` - `ANTHROPIC_API_KEY` (+ `npx`)
  1035. - `openai_ruby_mcp.rb` - `OPENAI_API_KEY` (+ `npx`)
  1036. - `ruby_openai_mcp.rb`, `ruby_llm_mcp.rb` - `OPENAI_API_KEY` (+ `npx`, plus a Playwright MCP server on `:8931`)
  1037. - `gemini_ai_mcp.rb` - a Vertex service-account JSON at `VERTEX_CREDENTIALS_FILE` (default `examples/google-credentials.json`, + `npx`)
  1038. ### How Pass/Fail Is Judged
  1039. Most examples print their own success/failure marks but exit `0` regardless, so the harness combines the exit code with a scan of the output rather than trusting the exit status alone. An example `FAIL`s when it exits nonzero, times out (exit `124`), prints a hard-error signature (a Ruby/Python traceback, `Connection refused`, `uninitialized constant`, and similar), prints a `❌` mark, or is missing its expected success marker; otherwise it `PASS`es. (The `❌` check is suppressed with `IGNORE_XMARK=1` for the interactive elicitation demos, where `❌` can be legitimate "declined" output.) The script exits `0` only if zero examples failed — `SKIP`s do not affect the exit status.
  1040. For deeper, per-topic walkthroughs see [`examples/README.md`](examples/README.md), [`examples/README_ECHO_SERVER.md`](examples/README_ECHO_SERVER.md), [`examples/STREAMABLE_HTTP_TESTING.md`](examples/STREAMABLE_HTTP_TESTING.md), and [`examples/elicitation/README.md`](examples/elicitation/README.md).
  1041. ## OAuth 2.1 Authentication
  1042. ```ruby
  1043. require 'mcp_client'
  1044. require 'mcp_client/auth/browser_oauth'
  1045. oauth = MCPClient::Auth::OAuthProvider.new(
  1046. server_url: 'https://api.example.com/mcp',
  1047. redirect_uri: 'http://localhost:8080/callback',
  1048. scope: 'mcp:read mcp:write'
  1049. )
  1050. browser_oauth = MCPClient::Auth::BrowserOAuth.new(oauth)
  1051. token = browser_oauth.authenticate # Opens browser, handles callback
  1052. client = MCPClient::Client.new(
  1053. mcp_server_configs: [{
  1054. type: 'streamable_http',
  1055. base_url: 'https://api.example.com/mcp',
  1056. oauth_provider: oauth
  1057. }]
  1058. )
  1059. ```
  1060. Features: PKCE, server discovery (`.well-known`), RFC 9207 issuer validation, Client ID Metadata Documents, dynamic registration (deprecated fallback), token refresh.
  1061. See [OAUTH.md](OAUTH.md) for full documentation.
  1062. ### OAuth Extras (2025-11-25)
  1063. - **Client ID Metadata Documents (SEP-991)** — pass
  1064. `client_id_metadata_url: 'https://myapp.example/oauth-client.json'` (an HTTPS
  1065. URL with a path, which doubles as the `client_id`); when the authorization
  1066. server advertises `client_id_metadata_document_supported`, dynamic client
  1067. registration is skipped entirely.
  1068. - **Scope challenges (SEP-835)** — an HTTP 403 `insufficient_scope` challenge
  1069. raises `MCPClient::Errors::InsufficientScopeError` (a `ConnectionError`
  1070. subclass) exposing `#scope` and `#error_description`; the challenged scopes
  1071. are treated as authoritative for the next authorization flow.
  1072. - **PKCE** — authorization refuses to proceed when the authorization server
  1073. does not advertise `code_challenge_methods_supported` including `S256`.
  1074. ### Authorization server binding (2026-07-28)
  1075. - **Registration state is per authorization server (SEP-2352)** — credentials
  1076. *and tokens* are stored under the MCP server URL (the record in use) *and*
  1077. under `provider.client_registration_key(issuer)`, so two authorization
  1078. servers behind one MCP server each keep their own registration state
  1079. instead of replacing one another. Seed pre-registered credentials for a
  1080. specific authorization server with
  1081. `storage.set_client_info(provider.client_registration_key(issuer), creds)`.
  1082. - **Pre-registered credentials must name their authorization server** — a
  1083. `client_id` (and any secret with it) is issued by one authorization server,
  1084. so credentials that name none are not bound to whichever server discovery
  1085. happens to find: that would send the secret registered with one server to
  1086. another. Store them with `issuer:` on the `ClientInfo`, or under
  1087. `client_registration_key(issuer)`; without it, authorization raises a
  1088. `ConnectionError` saying so and nothing is sent anywhere. A Client ID
  1089. Metadata Document id is portable and needs no issuer.
  1090. - **Pre-registered credentials outrank what the client registered itself** —
  1091. when an authorization server has credentials of its own under
  1092. `client_registration_key(issuer)`, they are used ahead of a Client ID
  1093. Metadata Document id (which answers for every server) and ahead of a
  1094. dynamic registration in the slot, as the MCP registration priority order
  1095. requires — and a dynamic registration never overwrites them.
  1096. - **A token is kept for each authorization server** — when the authorization
  1097. server changes, the token of the previous one is set aside under its own
  1098. key rather than thrown away, and picked up again if that server becomes the
  1099. one in use. A token this client retired (a 401 challenge naming another
  1100. authorization server) is deleted wherever it is kept, and no token is ever
  1101. presented to an authorization server other than the one that issued it.
  1102. - **A registration a flow needs must reach storage** — a backend that cannot
  1103. persist the credentials in use raises instead of returning an authorization
  1104. URL whose callback would then report "Missing PKCE or client info". The
  1105. per-authorization-server copy stays best-effort.
  1106. - **A refresh presents the credentials in the slot a host writes to** — a
  1107. secret rotated under the MCP server URL is used, not the older copy kept
  1108. under the authorization server's own key. Authorization and refresh pick the
  1109. same record.
  1110. - **A refresh and a code exchange are both re-checked when the response
  1111. arrives** — a token from an authorization server that stopped being this
  1112. resource's while the request was in flight is discarded rather than stored
  1113. over the current server's token or presented, and a code exchange that
  1114. arrives late no longer deletes the pending authorization request another
  1115. flow started meanwhile.
  1116. - **One per-request record** — the `state`, the PKCE verifier, the expected
  1117. issuer, the client id and the redirect URI of an authorization request are
  1118. written together, and the callback's `state` is checked against the record
  1119. the other checks read. Two flows sharing one storage backend can no longer
  1120. interleave their writes until one flow's state names the other flow's
  1121. request.
  1122. - **Scopes accumulate across step-ups** — re-authorizing after an
  1123. `insufficient_scope` challenge asks for the union of the scopes already
  1124. requested and the ones the challenge names, so getting `files:write` does
  1125. not give up `files:read`. "Already requested" survives a restart: it covers
  1126. the configured scope and the scope the authorization server granted the
  1127. token in hand, not only what this provider object last asked for. It is
  1128. scoped to one authorization server, so another server's scopes are never
  1129. asked of the new one.
  1130. - **An authorization request parameter appears once** — the authorization
  1131. endpoint's own query string is retained (RFC 6749 §3.1), but an endpoint of
  1132. `https://as.example/authorize?scope=openid` does not add a second `scope`
  1133. to the request; the same for `state`, `client_id` and the PKCE parameters.
  1134. Everything else the endpoint carries (`tenant`, `brand`, a locale) is kept.
  1135. - **Only a token type the client understands is presented** — `token_type` is
  1136. REQUIRED (RFC 6749 §5.1) and must be `Bearer` (§7.1). A `DPoP` or `mac`
  1137. token is refused where it is issued and where it is read back, and so is a
  1138. response that names no type at all: §5.1 defines no default, and §7.1
  1139. forbids using a token whose type the client does not understand.
  1140. - **Every redirect URI is `localhost` or HTTPS** — MCP 2026-07-28
  1141. "Communication Security". `http://app.example.com/callback` is refused when
  1142. it is configured and when a registration response registers it; plain HTTP
  1143. on the loopback interface and RFC 8252 private-use schemes
  1144. (`com.example.app:/cb`) are unaffected.
  1145. - **A callback parameter may appear once** — RFC 6749 §3.1: `BrowserOAuth`
  1146. refuses a callback that repeats `iss`, `state`, `code` or any other
  1147. parameter instead of silently taking the last value.
  1148. ## Cacheable Results (MCP 2026-07-28)
  1149. A 2026-07-28 server may bound a result with `ttlMs` (how long the client MAY
  1150. consider it fresh, counted from receipt) and `cacheScope` (`"public"` or
  1151. `"private"`). The transports honour both for `tools/list`, `prompts/list`,
  1152. `resources/list`, `resources/templates/list`, `server/discover` and
  1153. `resources/read`; `cache_info(:tools)` — or `cache_info(:read, uri)` — reports
  1154. what was recorded. An absent `ttlMs` means 0 on a 2026-07-28 server, a missing
  1155. or unrecognized `cacheScope` is treated as `"private"`, and a `resources/read`
  1156. result is kept only when the server gave it a positive `ttlMs`.
  1157. A cached result is served only to a request that would carry the same things
  1158. the request that produced it did:
  1159. - **the same authorization.** A `"private"` entry is bound to the
  1160. `Authorization` its own request actually went out with — what the adapter
  1161. sent, not what the response phase later left in the request environment — so
  1162. a rotated token, a revoked one, or an anonymous request never reads it.
  1163. - **the same effective parameters.** The `_meta` a request carries (your
  1164. `request_meta` and its `baggage`, the client identity and capabilities) is
  1165. part of what a result is bound to, whatever its scope: `"public"` permits
  1166. sharing across callers, not across parameters a server may vary its answer
  1167. by. A request carries a copy of that metadata, taken when it is built, so
  1168. rewriting a string or a container you handed `request_meta` in place does
  1169. not change what a request already sent means — set `request_meta` to the new
  1170. value instead, and the next request carries it.
  1171. Anything the transport cannot read off its own configuration makes those
  1172. unknowable, and reuse is then turned off rather than guessed at. Middleware of
  1173. your own installed through `faraday_config` is such a case — anything with a
  1174. request hook, and any handler carrying a callback of yours: it may set an
  1175. `Authorization` or rewrite the request body, and no inspection can tell whether
  1176. it does. Framework middleware the transport can read (Faraday's own retry,
  1177. JSON, url-encoded, multipart, logger, follow-redirects, and `:authorization`
  1178. configured with literal values) keeps caching on; an `:authorization` handed a
  1179. proc keeps public entries but not private ones, since the credential it vends
  1180. may differ from request to request.
  1181. Two rules follow the protocol rather than the cache:
  1182. - a `resources/templates/list` a server put **no** hint on is fetched again on
  1183. every call, as it was before results were cached at all; only a positive
  1184. `ttlMs` lets a template list be answered without a request;
  1185. - a cursor the server rejects (`-32602`) ends the page sequence it belonged to.
  1186. The pages cached for that list are dropped, an automatically paginated list
  1187. restarts once from the first page, and an explicit `list_resources(cursor:)`
  1188. or `list_resource_templates(cursor:)` raises — after the first page cached
  1189. under the dead cursor has been discarded, so the next call really re-fetches.
  1190. A re-fetch of a list that fails for a transient reason may serve the stale copy
  1191. on the HTTP transports ("Clients MAY serve stale responses if errors occur
  1192. during re-fetching"); the SSE and stdio transports raise instead, and an
  1193. authorization failure never serves a stale copy, so it reaches your auth flow.
  1194. A `server/discover` result is judged by the one rule every cached result
  1195. uses: once its `ttlMs` has elapsed (an absent, zero, negative or malformed
  1196. hint is stale at once) it is re-fetched on the next access that needs it,
  1197. before a capability is judged, on every transport.
  1198. ## Server Notifications
  1199. ```ruby
  1200. client.on_notification do |server, method, params|
  1201. case method
  1202. when 'notifications/tools/list_changed'
  1203. client.clear_cache # Auto-handled
  1204. when 'notifications/message'
  1205. puts "Log: #{params['data']}"
  1206. when 'notifications/roots/list_changed'
  1207. puts "Roots changed"
  1208. end
  1209. end
  1210. ```
  1211. ## Session Management
  1212. On a legacy session (a server speaking MCP 2025-11-25 or earlier), both HTTP
  1213. and Streamable HTTP transports automatically handle session-based servers:
  1214. - **Session capture**: Extracts `Mcp-Session-Id` from initialize response
  1215. - **Session persistence**: Includes session header in subsequent requests
  1216. - **Session termination**: Sends DELETE request during cleanup
  1217. - **Resumability** (Streamable HTTP, SEP-1699): tracks SSE event IDs and, when a
  1218. response stream is interrupted, resumes via GET with `Last-Event-ID` so the
  1219. server can replay missed messages — honoring the server's `retry:` directive
  1220. No configuration required - works automatically.
  1221. A modern session (MCP 2026-07-28) has none of this: no session id, no DELETE,
  1222. no GET stream and no resumption. A response stream that breaks loses the
  1223. in-flight request, and the client re-issues it once as a new request — see
  1224. [Treating the Server as Untrusted](#treating-the-server-as-untrusted) for what
  1225. that means for `tools/call`.
  1226. ## Server Compatibility
  1227. Works with any MCP-compatible server:
  1228. - [@modelcontextprotocol/server-filesystem](https://www.npmjs.com/package/@modelcontextprotocol/server-filesystem)
  1229. - [@playwright/mcp](https://www.npmjs.com/package/@playwright/mcp)
  1230. - [FastMCP](https://github.com/jlowin/fastmcp)
  1231. - Custom servers implementing MCP protocol
  1232. ### FastMCP Example
  1233. ```bash
  1234. # Start server
  1235. python examples/echo_server_streamable.py
  1236. ```
  1237. ```ruby
  1238. # Connect and use
  1239. client = MCPClient.connect('http://localhost:8931/mcp')
  1240. tools = client.list_tools
  1241. result = client.call_tool('echo', { message: 'Hello!' })
  1242. ```
  1243. ## Treating the Server as Untrusted
  1244. A connected MCP server controls everything it sends you, and the transports are
  1245. written on that assumption. You do not need to configure any of this — it is the
  1246. default behaviour — but it is worth knowing what the client will refuse:
  1247. | Peer-controlled input | What the client does |
  1248. |---|---|
  1249. | Compressed response bodies (**Streamable HTTP only** — the only transport that requests gzip) | Decompressed incrementally, abandoned past `max_decompressed_body_bytes` (64 MiB default) |
  1250. | SSE streams | Per-connection buffer cap; events scanned incrementally, so an unterminated event costs bounded memory *and* CPU |
  1251. | `retry:` directives | Honored, but floored so `retry: 0` cannot drive a reconnect loop |
  1252. | SSE event IDs | Bounded length, printable ASCII only (they are echoed in `Last-Event-ID`) |
  1253. | Legacy SSE `endpoint` events | Must stay on the connection's origin; off-origin redirects are refused, so configured credential headers never reach another host |
  1254. | OAuth discovery URLs from a peer | Must be HTTPS, and rejected when the host is a *literal* loopback/private/link-local address. The only exception is a local stack: a configured server URL on the loopback interface (`localhost`, `*.localhost`, 127.0.0.0/8, `::1`) may be sent to a plain-HTTP *loopback* URL — never to a link-local or otherwise private one. A refused challenge fails closed. Hostnames are not resolved, so a public name pointing at a private address is not caught — see the note below |
  1255. | Unsolicited JSON-RPC responses | Discarded — only IDs with an outstanding request are accepted |
  1256. | Server-initiated requests | Replies are bounded by a concurrency budget rather than spawning unbounded threads |
  1257. | Schema `pattern` values | Matched under a whole-operation time budget; a timeout fails validation rather than silently passing |
  1258. | Log messages (`notifications/message`) | Control characters escaped and length-capped, so a server cannot forge log lines |
  1259. | Broken response streams (MCP 2026-07-28) | The lost request is re-issued **once** as a new request, `tools/call` included: the revision says clients MUST re-issue and makes the closed stream the server's cancellation signal. A server that had already finished the tool before the stream broke runs it a second time. A `-32020` HeaderMismatch rejection is likewise retried once, after a `tools/list` refresh. Legacy sessions keep the 2.1.0 rule: non-idempotent requests are never re-sent |
  1260. | `cacheScope: "private"` results | Bound to the `Authorization` header the request went out with (SHA-256 of its bytes) and never served under another. A credential carried elsewhere — a cookie, an `X-Api-Key` header, client TLS — is not part of that context |
  1261. **Known limit:** the OAuth check is textual. A peer can still advertise a public
  1262. hostname whose DNS record points inside your network; catching that needs
  1263. resolution-time filtering in the HTTP layer, which this gem does not do. If you
  1264. run in an environment where that matters, restrict egress at the network layer.
  1265. Two related defaults worth calling out because they affect *your* data rather
  1266. than the peer's:
  1267. - **Payloads are never written to logs.** At DEBUG the client logs a method/id
  1268. summary and a byte count, not request params, response bodies or raw SSE
  1269. chunks. Server configurations are logged with credential-bearing keys redacted.
  1270. - **Host exceptions are not reflected to the server.** A raising elicitation,
  1271. sampling or roots handler yields a constant JSON-RPC error message; the detail
  1272. stays in your local log. When a server asks for several inputs at once (MCP
  1273. 2026-07-28 multi round-trip requests) and one of them fails, the answers your
  1274. handler already produced are kept rather than thrown away: a task's poll loop
  1275. sends them with its next `tasks/update` and never puts an answered request to
  1276. your handler a second time.
  1277. ## Requirements
  1278. - Ruby >= 3.3.0
  1279. - Runtime dependencies: `faraday` (~> 2.0) with `faraday-follow_redirects` and
  1280. `faraday-retry`, plus `base64` — all pulled in automatically by the gem
  1281. Development uses Ruby 4.0.7 (see `.ruby-version`). CI runs the suite on 4.0.7
  1282. plus the supported floor, 3.3.
  1283. ## License
  1284. Available as open source under the [MIT License](LICENSE).
  1285. ## Contributing
  1286. Bug reports and pull requests welcome at https://github.com/simonx1/ruby-mcp-client.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.