mcp 1.11.0 → 1.13.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a7387e5c2a8bc058687718d9e1d2a9e876c914adf72ca9ffa3105091afe2bcbb
4
- data.tar.gz: 4a3f2b69ffec38ef5141df63b63505219bbd06180a49316306d36d8b6254358f
3
+ metadata.gz: d50d1abe149ce555b22e169ece7783afcf5839b994e761b099aea430800d9317
4
+ data.tar.gz: ba7a5dcafbb14e42459d2e0fa327913174ec1ff3146a1ee738d6ea2f1ffd1922
5
5
  SHA512:
6
- metadata.gz: c1be8465ddd4a52f68ec4a69f548846aaca2df9c47c5b930af0ec65c5c489de9f04415f2c6e9b99a94ebdf22c4dee534e1f867988d18407a6a531b5881dff89c
7
- data.tar.gz: be116455c8537480257a1ac835bb4974561f750b4a110e26cc4d11d661cdb5ab42b6ebb9eee9e448aed998832a1abc248c200273558f24bf9a58ac52b371fc29
6
+ metadata.gz: 2f33d991991bdc4e9ae0890767aa061951ae7f2a4097210c2fee780812f4d8f4df8e4f370b42da9afba44723d669ab6c217f28808b1b6d4d776f7608d1172830
7
+ data.tar.gz: 7e036ad949d5dd6dfc18169212e82c804128bd59eaf6c47f5ac415c05cc1e300c292fcfb21e9f6fe220e327702419a8537245341b3b7da83abbc14e3998d464f
@@ -210,11 +210,103 @@ module JsonRpcHandler
210
210
 
211
211
  error_response(id: id, id_validation_pattern: id_validation_pattern, error: {
212
212
  code: code,
213
- message: message,
214
- data: data,
213
+ message: printable_text(message),
214
+ data: printable_data(data),
215
215
  })
216
216
  end
217
217
 
218
+ # The text of a request handler error often quotes what the client sent, such as the name of a tool that does not exist,
219
+ # and the parser passes bytes that are not valid UTF-8 through. Generating the response from such a text raises,
220
+ # which would replace the error and its code with Internal error. Those bytes are replaced with U+FFFD; a valid UTF-8 text,
221
+ # and `data` that is not a String, come through unchanged. A text in another encoding is transcoded.
222
+ # A binary one has no characters to transcode, and Ruby has no converter for some encodings, such as UTF-7;
223
+ # those are read as UTF-8, so that this never raises in place of the error it is writing.
224
+ def printable_text(value)
225
+ return value unless value.is_a?(String)
226
+ return value if value.encoding == Encoding::UTF_8 && value.valid_encoding?
227
+
228
+ unless value.encoding == Encoding::UTF_8 || value.encoding == Encoding::BINARY
229
+ begin
230
+ return value.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)
231
+ rescue EncodingError
232
+ # Falls through to the bytes read as UTF-8.
233
+ end
234
+ end
235
+
236
+ value.dup.force_encoding(Encoding::UTF_8).scrub
237
+ end
238
+
239
+ # `data` can quote the request as well, inside a structure: `ResourceNotFoundError` carries `{ uri: <uri> }`.
240
+ # The texts in it, String keys included, get the treatment of `printable_text`; anything else comes through unchanged.
241
+ # A key that is not a String is written as its text, so it is left as it is.
242
+ #
243
+ # A `data` in which a Hash or Array holds itself, or that nests deeper than `MAX_PRINTABLE_DATA_DEPTH`, cannot be written
244
+ # and comes through unchanged as a whole: the generator refuses it at once, as it would have without this,
245
+ # and following it here could take far longer than that. In one that can be written, a Hash or Array is converted once,
246
+ # however many times it is held; `converted` maps each to its copy.
247
+ def printable_data(value, converted = nil)
248
+ case value
249
+ when String
250
+ printable_text(value)
251
+ when Hash, Array
252
+ if converted.nil?
253
+ return value unless nests_within?(value, MAX_PRINTABLE_DATA_DEPTH)
254
+
255
+ converted = {}.compare_by_identity
256
+ end
257
+
258
+ converted[value] ||= if value.is_a?(Hash)
259
+ value.to_h { |key, member| [key.is_a?(String) ? printable_text(key) : key, printable_data(member, converted)] }
260
+ else
261
+ value.map { |member| printable_data(member, converted) }
262
+ end
263
+ else
264
+ value
265
+ end
266
+ end
267
+
268
+ # Whether the Hashes and Arrays that `container` holds through its values and members, itself included, nest
269
+ # at most `limit` deep and never hold themselves. One pass, without recursion: a Hash or Array is entered once
270
+ # however many times it is held, and `depths` keeps how deep the nesting goes below each, or `:open` while it is
271
+ # being looked into. Meeting one that is `:open` closes a cycle.
272
+ def nests_within?(container, limit)
273
+ depths = {}.compare_by_identity
274
+ depths[container] = :open
275
+ # Each entry: a Hash or Array, those it holds that are still to be looked at, and how deep it nests as far as is known.
276
+ path = [[container, containers_in(container), 1]]
277
+
278
+ until path.empty?
279
+ entry = path.last
280
+ inner = entry[1].pop
281
+
282
+ if inner.nil?
283
+ return false if entry[2] > limit
284
+
285
+ depths[entry[0]] = entry[2]
286
+ path.pop
287
+ path.last[2] = [path.last[2], entry[2] + 1].max unless path.empty?
288
+ elsif depths[inner] == :open
289
+ return false
290
+ elsif depths.key?(inner)
291
+ entry[2] = [entry[2], depths[inner] + 1].max
292
+ else
293
+ depths[inner] = :open
294
+ path << [inner, containers_in(inner), 1]
295
+ end
296
+ end
297
+
298
+ true
299
+ end
300
+
301
+ def containers_in(container)
302
+ (container.is_a?(Hash) ? container.values : container).select { |member| member.is_a?(Hash) || member.is_a?(Array) }
303
+ end
304
+
305
+ # `JSON.generate` writes 100 levels by default, and `data` already sits two levels down in a response,
306
+ # so nothing that can be written nests deeper than this.
307
+ MAX_PRINTABLE_DATA_DEPTH = 100
308
+ private_constant :MAX_PRINTABLE_DATA_DEPTH
309
+
218
310
  def valid_version?(version)
219
311
  version == Version::V2_0
220
312
  end
@@ -3,6 +3,7 @@
3
3
  require "securerandom"
4
4
  require_relative "../../json_rpc_handler"
5
5
  require_relative "../configuration"
6
+ require_relative "../duration"
6
7
  require_relative "../methods"
7
8
  require_relative "../protocol_deprecations"
8
9
  require_relative "../version"
@@ -123,10 +124,11 @@ module MCP
123
124
  attr_reader :buffer, :response, :response_headers, :last_event_id, :retry_ms
124
125
  attr_accessor :abortable
125
126
 
126
- def initialize(abortable:, max_message_bytes: MAX_MESSAGE_BYTES, on_request: nil)
127
+ def initialize(abortable:, max_message_bytes: MAX_MESSAGE_BYTES, on_request: nil, request_id: nil)
127
128
  @abortable = abortable
128
129
  @max_message_bytes = max_message_bytes
129
130
  @on_request = on_request
131
+ @request_id = request_id
130
132
  @buffer = +""
131
133
  @parser = nil
132
134
  @response = nil
@@ -213,17 +215,27 @@ module MCP
213
215
  next unless parsed.is_a?(Hash)
214
216
 
215
217
  if parsed.key?("result") || parsed.key?("error")
218
+ # A response carrying the id of another request does not answer this one. One carrying no id
219
+ # still does: it is how a server refuses a request whose id it could not read.
220
+ next if @request_id && !parsed["id"].nil? && parsed["id"] != @request_id
221
+
216
222
  @response ||= parsed
217
223
  elsif parsed["method"] && parsed.key?("id") && JsonRpcHandler.valid_version?(parsed["jsonrpc"])
218
224
  # A server-to-client request (e.g. `elicitation/create`) delivered on the stream while
219
225
  # the original request is still pending. One that is not JSON-RPC 2.0 is dropped unanswered,
220
- # as the TypeScript client drops it at schema validation, and so is one whose integer id is
221
- # too large to write back at a reasonable cost.
222
- @on_request&.call(parsed) unless JsonRpcHandler.oversized_integer_id?(parsed["id"])
226
+ # as the TypeScript client drops it at schema validation, and so is one whose id cannot be written back.
227
+ @on_request&.call(parsed) unless unwritable_id?(parsed["id"])
223
228
  end
224
229
  end
225
230
  end
226
231
 
232
+ # An id the answer could not carry, as `Client::Stdio` skips a ping with one: a number such as `1e400`,
233
+ # which the parser reads as an infinite Float that JSON cannot represent, or an integer too large to write back
234
+ # at a reasonable cost.
235
+ def unwritable_id?(id)
236
+ JsonRpcHandler.oversized_integer_id?(id) || (id.is_a?(Float) && !id.finite?)
237
+ end
238
+
227
239
  # Bytes the parser has buffered for a not-yet-dispatched event: the partial line
228
240
  # and the accumulated `data:` field values (plus the small event type and last event id buffers).
229
241
  # External byte counting cannot tell consumed-and-discarded bytes (comments, field names, delimiters)
@@ -267,8 +279,8 @@ module MCP
267
279
  raise ArgumentError, "max_message_bytes must be a positive Integer"
268
280
  end
269
281
 
270
- unless max_reconnection_wait.is_a?(Numeric) && max_reconnection_wait > 0
271
- raise ArgumentError, "max_reconnection_wait must be a positive number"
282
+ unless Duration.positive_finite?(max_reconnection_wait)
283
+ raise ArgumentError, "max_reconnection_wait must be a positive finite number"
272
284
  end
273
285
 
274
286
  if oauth && !MCP::Client::OAuth::Discovery.secure_url?(url)
@@ -430,6 +442,7 @@ module MCP
430
442
  abortable: true,
431
443
  max_message_bytes: @max_message_bytes,
432
444
  on_request: ->(message) { dispatch_server_request(message) },
445
+ request_id: request_id,
433
446
  )
434
447
 
435
448
  yield if block_given?
@@ -590,6 +603,21 @@ module MCP
590
603
  end
591
604
  end
592
605
 
606
+ # `inspect` is what error reporters and consoles print an object with, and the default one walks every instance variable:
607
+ # the static `headers:` (often an API key), the Faraday connection that holds them as well, and the session id.
608
+ # It shows the header names only, the URL without its userinfo and query, whether a session is open, and
609
+ # the class of the `oauth:` provider: what a provider or its storage prints is theirs to decide, and may hold a credential.
610
+ def inspect
611
+ safe_url = begin
612
+ MCP::Client::OAuth::Discovery.canonicalize_origin_and_path(@url)
613
+ rescue StandardError
614
+ "[unparseable]"
615
+ end
616
+
617
+ "#<#{self.class.name} url=#{safe_url.inspect} headers=#{(@headers || {}).keys.inspect} " \
618
+ "session_id=#{@session_id.nil? ? "nil" : "[present]"} oauth=#{@oauth.nil? ? "nil" : @oauth.class.name}>"
619
+ end
620
+
593
621
  private
594
622
 
595
623
  attr_reader :headers
@@ -611,8 +639,9 @@ module MCP
611
639
  if response.is_a?(Hash) && response.key?("error")
612
640
  clear_session
613
641
  error = response["error"]
642
+ message = error.is_a?(Hash) ? error["message"] : "malformed JSON-RPC error object"
614
643
  raise RequestHandlerError.new(
615
- "Server initialization failed: #{error["message"]}",
644
+ "Server initialization failed: #{message}",
616
645
  { method: MCP::Methods::INITIALIZE },
617
646
  error_type: :internal_error,
618
647
  )
@@ -732,8 +761,9 @@ module MCP
732
761
 
733
762
  if response.is_a?(Hash) && response.key?("error")
734
763
  error = response["error"]
764
+ message = error.is_a?(Hash) ? error["message"] : "malformed JSON-RPC error object"
735
765
  raise RequestHandlerError.new(
736
- "Server discovery failed: #{error["message"]}",
766
+ "Server discovery failed: #{message}",
737
767
  { method: MCP::Methods::SERVER_DISCOVER },
738
768
  error_type: :internal_error,
739
769
  )
@@ -792,7 +822,8 @@ module MCP
792
822
 
793
823
  # Per SEP-2243, mirror the JSON-RPC method and target name/uri into HTTP headers so intermediaries
794
824
  # can route and inspect requests without parsing the body. `Mcp-Name` comes from `params.name`
795
- # (tools, prompts) or, when absent, `params.uri` (resources).
825
+ # (tools, prompts) or, when absent, `params.uri` (resources). A `resources/read` is named by its `uri`
826
+ # whatever else its `params` carry, since that is the member the server checks the header against.
796
827
  #
797
828
  # https://modelcontextprotocol.io/specification/draft/basic/transports/streamable-http#request-metadata
798
829
  def request_metadata_headers(method, params)
@@ -800,7 +831,7 @@ module MCP
800
831
 
801
832
  metadata_headers = { METHOD_HEADER => method }
802
833
  if params.is_a?(Hash)
803
- name = params[:name] || params["name"]
834
+ name = params[:name] || params["name"] unless method == MCP::Methods::RESOURCES_READ
804
835
  name = params[:uri] || params["uri"] unless name.is_a?(String)
805
836
  metadata_headers[NAME_HEADER] = encode_header_value(name) if name.is_a?(String)
806
837
 
@@ -824,14 +855,17 @@ module MCP
824
855
  return unless modern?
825
856
  return unless method.to_s == MCP::Methods::TOOLS_LIST && body.is_a?(Hash)
826
857
 
827
- tools = body.dig("result", "tools")
858
+ result = body["result"]
859
+ return unless result.is_a?(Hash)
860
+
861
+ tools = result["tools"]
828
862
  return unless tools.is_a?(Array)
829
863
 
830
864
  # An uncursored request answered without `nextCursor` is the complete tool universe,
831
865
  # so knowledge about unlisted tools is stale; the registry is rebuilt from this listing,
832
866
  # the same pruning the Python SDK applies to complete listings.
833
867
  cursor = params.is_a?(Hash) && (params[:cursor] || params["cursor"])
834
- complete = !cursor && body.dig("result", "nextCursor").nil?
868
+ complete = !cursor && result["nextCursor"].nil?
835
869
  registry = complete ? {} : @mcp_param_declarations
836
870
 
837
871
  tools.each do |tool|
@@ -154,6 +154,13 @@ module MCP
154
154
  )
155
155
  end
156
156
 
157
+ # `inspect` is what error reporters and consoles print an object with, and the default one would print
158
+ # the `private_key` given as a PEM String in full, so it shows only whether a key is held, and the class of
159
+ # the storage: what a custom storage prints is its own to decide.
160
+ def inspect
161
+ "#<#{self.class.name} client_id=#{@client_id.inspect} private_key=#{@private_key.nil? ? "nil" : "[present]"} storage=#{@storage.class.name}>"
162
+ end
163
+
157
164
  private
158
165
 
159
166
  def validate_private_key_jwt_arguments!(client_secret:, private_key:, signing_algorithm:)
@@ -6,6 +6,7 @@ require "securerandom"
6
6
  require "timeout"
7
7
  require_relative "../../json_rpc_handler"
8
8
  require_relative "../configuration"
9
+ require_relative "../duration"
9
10
  require_relative "../methods"
10
11
  require_relative "../protocol_deprecations"
11
12
  require_relative "../version"
@@ -55,6 +56,10 @@ module MCP
55
56
  raise ArgumentError, "max_line_bytes must be a positive Integer"
56
57
  end
57
58
 
59
+ unless read_timeout.nil? || Duration.positive_finite?(read_timeout)
60
+ raise ArgumentError, "read_timeout must be a positive finite number or nil"
61
+ end
62
+
58
63
  @command = command
59
64
  @args = args
60
65
  @env = env
@@ -77,6 +82,14 @@ module MCP
77
82
  @write_mutex = Mutex.new
78
83
  end
79
84
 
85
+ # The default `inspect` would print the `env:` given to the server process, which is where its API keys usually go,
86
+ # and the arguments, which can hold one as well. It shows the command, the number of arguments and the names
87
+ # of the variables only.
88
+ def inspect
89
+ "#<#{self.class.name} command=#{@command.inspect} args=#{Array(@args).size} env=#{(@env || {}).keys.inspect} " \
90
+ "started=#{@started}>"
91
+ end
92
+
80
93
  # Performs the MCP `initialize` handshake: sends an `initialize` request
81
94
  # followed by the required `notifications/initialized` notification. The
82
95
  # server's `InitializeResult` (protocol version, capabilities, server
@@ -255,8 +268,9 @@ module MCP
255
268
 
256
269
  if response.key?("error")
257
270
  error = response["error"]
271
+ message = error.is_a?(Hash) ? error["message"] : "malformed JSON-RPC error object"
258
272
  raise RequestHandlerError.new(
259
- "Server initialization failed: #{error["message"]}",
273
+ "Server initialization failed: #{message}",
260
274
  { method: MCP::Methods::INITIALIZE },
261
275
  error_type: :internal_error,
262
276
  )
@@ -390,8 +404,9 @@ module MCP
390
404
 
391
405
  if response.key?("error")
392
406
  error = response["error"]
407
+ message = error.is_a?(Hash) ? error["message"] : "malformed JSON-RPC error object"
393
408
  raise RequestHandlerError.new(
394
- "Server discovery failed: #{error["message"]}",
409
+ "Server discovery failed: #{message}",
395
410
  { method: MCP::Methods::SERVER_DISCOVER },
396
411
  error_type: :internal_error,
397
412
  )
data/lib/mcp/client.rb CHANGED
@@ -127,7 +127,8 @@ module MCP
127
127
  #
128
128
  # @param transport [Object] The transport object to use for communication with the server.
129
129
  # The transport should be a duck type that responds to `send_request`. See the README for more details.
130
- # @param input_required_max_rounds [Integer] Cap on SEP-2322 driver rounds.
130
+ # @param input_required_max_rounds [Integer] Non-negative cap on SEP-2322 driver rounds; with `0`
131
+ # no handler runs and {InputRequiredError} is raised for manual driving.
131
132
  # @param max_pages [Integer] Maximum number of pages the all-pages methods ({#tools}, {#resources},
132
133
  # {#resource_templates}, {#prompts}) will walk before raising {MCP::Client::PaginationLimitError}.
133
134
  #
@@ -146,6 +147,10 @@ module MCP
146
147
  raise ArgumentError, "max_pages must be a positive Integer"
147
148
  end
148
149
 
150
+ unless input_required_max_rounds.is_a?(Integer) && !input_required_max_rounds.negative?
151
+ raise ArgumentError, "input_required_max_rounds must be a non-negative Integer"
152
+ end
153
+
149
154
  @transport = transport
150
155
  @max_pages = max_pages
151
156
  # Populated by `on_elicitation`, `on_sampling`, and `on_roots`. The same handler answers both ways
@@ -312,7 +317,7 @@ module MCP
312
317
  def list_tools(cursor: nil, meta: nil, cancellation: nil)
313
318
  params = cursor ? { cursor: cursor } : nil
314
319
  response = request(method: "tools/list", params: params, meta: meta, cancellation: cancellation)
315
- result = response["result"] || {}
320
+ result = result_hash(response)
316
321
 
317
322
  tools = (result["tools"] || []).filter_map do |tool|
318
323
  next if exclude_invalid_x_mcp_header?(tool)
@@ -372,7 +377,7 @@ module MCP
372
377
  def list_resources(cursor: nil, meta: nil, cancellation: nil)
373
378
  params = cursor ? { cursor: cursor } : nil
374
379
  response = request(method: "resources/list", params: params, meta: meta, cancellation: cancellation)
375
- result = response["result"] || {}
380
+ result = result_hash(response)
376
381
 
377
382
  ListResourcesResult.new(
378
383
  resources: result["resources"] || [],
@@ -408,7 +413,7 @@ module MCP
408
413
  def list_resource_templates(cursor: nil, meta: nil, cancellation: nil)
409
414
  params = cursor ? { cursor: cursor } : nil
410
415
  response = request(method: "resources/templates/list", params: params, meta: meta, cancellation: cancellation)
411
- result = response["result"] || {}
416
+ result = result_hash(response)
412
417
 
413
418
  ListResourceTemplatesResult.new(
414
419
  resource_templates: result["resourceTemplates"] || [],
@@ -444,7 +449,7 @@ module MCP
444
449
  def list_prompts(cursor: nil, meta: nil, cancellation: nil)
445
450
  params = cursor ? { cursor: cursor } : nil
446
451
  response = request(method: "prompts/list", params: params, meta: meta, cancellation: cancellation)
447
- result = response["result"] || {}
452
+ result = result_hash(response)
448
453
 
449
454
  ListPromptsResult.new(
450
455
  prompts: result["prompts"] || [],
@@ -539,7 +544,7 @@ module MCP
539
544
 
540
545
  response = drive_input_required(method: "resources/read", params: params, cancellation: cancellation)
541
546
 
542
- response.dig("result", "contents") || []
547
+ result_hash(response)["contents"] || []
543
548
  end
544
549
 
545
550
  # Gets a prompt from the server by name and returns its details.
@@ -557,7 +562,7 @@ module MCP
557
562
 
558
563
  response = drive_input_required(method: "prompts/get", params: params, cancellation: cancellation)
559
564
 
560
- response.fetch("result", {})
565
+ result_hash(response)
561
566
  end
562
567
 
563
568
  # Requests completion suggestions from the server for a prompt argument or resource template URI.
@@ -576,7 +581,7 @@ module MCP
576
581
 
577
582
  response = request(method: "completion/complete", params: params, meta: meta, cancellation: cancellation)
578
583
 
579
- response.dig("result", "completion") || { "values" => [], "hasMore" => false }
584
+ result_hash(response)["completion"] || { "values" => [], "hasMore" => false }
580
585
  end
581
586
 
582
587
  # Registers a handler for `elicitation/create` requests the server sends while one of
@@ -678,6 +683,16 @@ module MCP
678
683
 
679
684
  private
680
685
 
686
+ def result_hash(response)
687
+ if response.is_a?(Hash)
688
+ result = response["result"]
689
+ return {} if result.nil?
690
+ return result if result.is_a?(Hash)
691
+ end
692
+
693
+ raise ValidationError, "Response validation failed: missing or invalid `result`"
694
+ end
695
+
681
696
  # Records a handler for one of the three kinds of input a server can ask this client for, and wires it to
682
697
  # the transport when the transport can carry server-to-client requests. One registration serves both routes:
683
698
  # the real request a 2025-11-25 server sends mid-call, and the request embedded in a SEP-2322
@@ -804,6 +819,10 @@ module MCP
804
819
  # Guard with `is_a?(Hash)` because custom transports may return non-Hash values.
805
820
  if response.is_a?(Hash) && response.key?("error")
806
821
  error = response["error"]
822
+ unless error.is_a?(Hash)
823
+ raise ServerError.new("Server returned a malformed JSON-RPC error object", code: nil)
824
+ end
825
+
807
826
  raise ServerError.new(error["message"], code: error["code"], data: error["data"])
808
827
  end
809
828
 
@@ -835,6 +854,7 @@ module MCP
835
854
  backoff = STATE_ONLY_BACKOFF_INITIAL_SECONDS
836
855
 
837
856
  loop do
857
+ cancellation&.raise_if_cancelled!
838
858
  result = response["result"]
839
859
  rounds += 1
840
860
  if rounds > @input_required_max_rounds
@@ -849,11 +869,11 @@ module MCP
849
869
  input_requests = result["inputRequests"] || {}
850
870
  responses = nil
851
871
  if input_requests.empty?
852
- sleep(backoff)
872
+ sleep_with_cancellation(backoff, cancellation)
853
873
  backoff = [backoff * 2, STATE_ONLY_BACKOFF_CAP_SECONDS].min
854
874
  else
855
875
  backoff = STATE_ONLY_BACKOFF_INITIAL_SECONDS
856
- responses = fulfill_input_requests(input_requests, result)
876
+ responses = fulfill_input_requests(input_requests, result, cancellation: cancellation)
857
877
  end
858
878
 
859
879
  retry_params = original_params.dup
@@ -873,8 +893,9 @@ module MCP
873
893
  # Dispatches every embedded request to its configured handler and collects
874
894
  # the answers under the same keys. A kind without a handler falls back to
875
895
  # the manual path by raising `InputRequiredError` with the full result.
876
- def fulfill_input_requests(input_requests, result)
896
+ def fulfill_input_requests(input_requests, result, cancellation:)
877
897
  input_requests.each_with_object({}) do |(key, entry), responses|
898
+ cancellation&.raise_if_cancelled!
878
899
  entry_method = entry.is_a?(Hash) ? entry["method"] || entry[:method] : nil
879
900
  handler = @input_required_handlers[entry_method]
880
901
  unless handler
@@ -891,6 +912,29 @@ module MCP
891
912
  end
892
913
  end
893
914
 
915
+ # Waits out `seconds`, returning early on cancellation. Re-issuing the request then raises `CancelledError`
916
+ # before anything is sent.
917
+ def sleep_with_cancellation(seconds, cancellation)
918
+ return sleep(seconds) unless cancellation
919
+
920
+ mutex = Mutex.new
921
+ wakeup = ConditionVariable.new
922
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
923
+ hook = cancellation.on_cancel { mutex.synchronize { wakeup.signal } }
924
+
925
+ # Check cancellation under the wait mutex so a signal between registration and waiting is handled too.
926
+ mutex.synchronize do
927
+ until cancellation.cancelled?
928
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
929
+ break if remaining <= 0
930
+
931
+ wakeup.wait(mutex, remaining)
932
+ end
933
+ end
934
+ ensure
935
+ cancellation.off_cancel(hook) if hook
936
+ end
937
+
894
938
  def input_required?(response)
895
939
  result = response.is_a?(Hash) ? response["result"] : nil
896
940
  result.is_a?(Hash) && result["resultType"] == ResultType::INPUT_REQUIRED
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MCP
4
+ # @api private
5
+ module ClientCapabilities
6
+ class << self
7
+ def value(capabilities, name)
8
+ return unless capabilities.is_a?(Hash)
9
+
10
+ value = capabilities[name.to_sym]
11
+ value.nil? ? capabilities[name.to_s] : value
12
+ end
13
+
14
+ def elicitation?(capabilities, mode)
15
+ modes = value(capabilities, :elicitation)
16
+ return false unless modes.is_a?(Hash)
17
+
18
+ # A declaration naming neither mode, such as `elicitation: {}`, implies form mode only,
19
+ # matching the multi round-trip checks of the TypeScript and Python SDKs.
20
+ (mode == :form && value(modes, :form).nil? && value(modes, :url).nil?) || !!value(modes, mode)
21
+ end
22
+ end
23
+ end
24
+ private_constant :ClientCapabilities
25
+ end
data/lib/mcp/content.rb CHANGED
@@ -46,6 +46,18 @@ module MCP
46
46
  end
47
47
  end
48
48
 
49
+ class ResourceLink
50
+ attr_reader :resource
51
+
52
+ def initialize(resource)
53
+ @resource = resource
54
+ end
55
+
56
+ def to_h
57
+ resource.to_h.merge(type: "resource_link")
58
+ end
59
+ end
60
+
49
61
  class EmbeddedResource
50
62
  attr_reader :resource, :annotations, :meta
51
63
 
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MCP
4
+ # @api private
5
+ module Duration
6
+ class << self
7
+ def positive_finite?(value)
8
+ value.is_a?(Numeric) && value.real? && value.finite? && value.positive?
9
+ end
10
+ end
11
+ end
12
+ private_constant :Duration
13
+ end