From bcc5ea4cd09bb0d8792f2f199b10be234280f59d Mon Sep 17 00:00:00 2001 From: Andy Wang Date: Tue, 1 Dec 2026 14:21:04 +0800 Subject: [PATCH] fix: validate transport timeouts and input round limits ## Motivation and Context Durations that are not finite were accepted by the transport constructors, and most of them raised `RangeError` later, in the wait that used them. The constructors now require a positive finite number, or `nil` where the option documents it. `input_required_max_rounds` must be a non-negative Integer; `0` still leaves the input to the caller. ## Breaking Changes These values had an effect and now raise `ArgumentError`: - `session_idle_timeout`: `Float::INFINITY`, `Float::NAN` and `false` disabled expiry. Pass `nil`. - `max_stream_lifetime` and `stream_write_timeout`: `Float::INFINITY` meant no limit. Pass `nil`. - `read_timeout` of `MCP::Client::Stdio`: `false` meant no timeout. Pass `nil`. - `listen_keepalive_interval`: `Float::INFINITY` worked on streams with a deadline. Pass a large finite number; `nil` would also stop closing a quiet stream at its deadline. - `input_required_max_rounds`: a Float or Rational was rounded down; pass an Integer. `Float::INFINITY` and `Float::NAN` meant no cap; pass a large Integer, as `nil` is not accepted. A negative number acted as `0`; pass `0`. Fixes #735. --- docs/_client/mrtr.md | 2 +- docs/_client/transports.md | 4 +-- lib/mcp/client.rb | 7 +++- lib/mcp/client/http.rb | 5 +-- lib/mcp/client/stdio.rb | 5 +++ lib/mcp/duration.rb | 13 ++++++++ .../transports/streamable_http_transport.rb | 29 +++++++++-------- test/mcp/client/http_test.rb | 4 +-- test/mcp/client/stdio_test.rb | 10 ++++++ test/mcp/client_test.rb | 17 ++++++++++ .../streamable_http_transport_test.rb | 32 ++++++++++++++++--- 11 files changed, 103 insertions(+), 25 deletions(-) create mode 100644 lib/mcp/duration.rb diff --git a/docs/_client/mrtr.md b/docs/_client/mrtr.md index 4a68e5fd..892e1518 100644 --- a/docs/_client/mrtr.md +++ b/docs/_client/mrtr.md @@ -16,7 +16,7 @@ and an opaque `requestState`; the client fulfills the requests and re-issues the The Ruby client drives such results automatically: once a handler is registered through `on_elicitation`, `on_sampling`, or `on_roots`, the `call_tool`, `get_prompt`, and `read_resource` methods fulfill the embedded requests and re-issue the original request with `inputResponses` plus the echoed `requestState`, capped at `input_required_max_rounds` -(10 by default, matching the TypeScript and Python SDKs). +(a non-negative integer, 10 by default, matching the TypeScript and Python SDKs). ```ruby client = MCP::Client.new(transport: transport) diff --git a/docs/_client/transports.md b/docs/_client/transports.md index deec4ea6..ea04a420 100644 --- a/docs/_client/transports.md +++ b/docs/_client/transports.md @@ -27,7 +27,7 @@ Use the `MCP::Client::Stdio` transport to interact with MCP servers running as s | `args:` | No | An array of arguments passed to the command. Defaults to `[]`. | | `env:` | No | Extra environment variables for the server process, merged over the inherited base environment. Values override inherited variables; a `nil` value removes a variable. Defaults to `nil`. | | `inherit_env:` | No | Inherit the full parent environment instead of the default allow-list. Defaults to `false`. | -| `read_timeout:` | No | Timeout in seconds for waiting for a server response. Defaults to `nil` (no timeout). | +| `read_timeout:` | No | Positive, finite timeout in seconds for waiting for a server response. Defaults to `nil` (no timeout). | | `max_line_bytes:` | No | Maximum byte length of a single newline-delimited response frame. A frame that reaches this limit without a newline is rejected as a transport error, preventing unbounded memory growth from a server that never emits a newline. Defaults to `4 * 1024 * 1024` (4 MiB). | By default, the server inherits only these variables that are present in the parent environment: @@ -148,7 +148,7 @@ to a server-to-client request, and the answer to the session DELETE. These bodie `event_stream_parser`. An over-limit DELETE reply raises a transport error before its status is handled, including 404 or 405; replies with those statuses within the limit are still tolerated. It defaults to `4 * 1024 * 1024` (4 MiB); raise it if your server returns larger responses. -`MCP::Client::HTTP.new` also accepts `max_reconnection_wait:`, a budget in seconds for resuming a closed SSE stream. It gates every wait between reconnection attempts, +`MCP::Client::HTTP.new` also accepts `max_reconnection_wait:`, a positive, finite budget in seconds for resuming a closed SSE stream. It gates every wait between reconnection attempts, and what is left of it becomes the read timeout of each resumed stream. The server chooses that wait through the SSE `retry:` field, and resuming happens on the calling thread, so without a budget a server answering with a large `retry:` parks a thread of your application for as long as it likes. It defaults to `300` (5 minutes). The server's `retry:` is never shortened: when honoring it would run past the budget, the client stops trying to resume and raises instead, diff --git a/lib/mcp/client.rb b/lib/mcp/client.rb index a9ef4c84..5d3d8e25 100644 --- a/lib/mcp/client.rb +++ b/lib/mcp/client.rb @@ -127,7 +127,8 @@ def initialize(message, request, original_error: nil) # # @param transport [Object] The transport object to use for communication with the server. # The transport should be a duck type that responds to `send_request`. See the README for more details. - # @param input_required_max_rounds [Integer] Cap on SEP-2322 driver rounds. + # @param input_required_max_rounds [Integer] Non-negative cap on SEP-2322 driver rounds; with `0` + # no handler runs and {InputRequiredError} is raised for manual driving. # @param max_pages [Integer] Maximum number of pages the all-pages methods ({#tools}, {#resources}, # {#resource_templates}, {#prompts}) will walk before raising {MCP::Client::PaginationLimitError}. # @@ -146,6 +147,10 @@ def initialize(transport:, input_required_max_rounds: DEFAULT_INPUT_REQUIRED_MAX raise ArgumentError, "max_pages must be a positive Integer" end + unless input_required_max_rounds.is_a?(Integer) && !input_required_max_rounds.negative? + raise ArgumentError, "input_required_max_rounds must be a non-negative Integer" + end + @transport = transport @max_pages = max_pages # Populated by `on_elicitation`, `on_sampling`, and `on_roots`. The same handler answers both ways diff --git a/lib/mcp/client/http.rb b/lib/mcp/client/http.rb index cb7029ad..ae7e5658 100644 --- a/lib/mcp/client/http.rb +++ b/lib/mcp/client/http.rb @@ -3,6 +3,7 @@ require "securerandom" require_relative "../../json_rpc_handler" require_relative "../configuration" +require_relative "../duration" require_relative "../methods" require_relative "../protocol_deprecations" require_relative "../version" @@ -278,8 +279,8 @@ def initialize( raise ArgumentError, "max_message_bytes must be a positive Integer" end - unless max_reconnection_wait.is_a?(Numeric) && max_reconnection_wait > 0 - raise ArgumentError, "max_reconnection_wait must be a positive number" + unless Duration.positive_finite?(max_reconnection_wait) + raise ArgumentError, "max_reconnection_wait must be a positive finite number" end if oauth && !MCP::Client::OAuth::Discovery.secure_url?(url) diff --git a/lib/mcp/client/stdio.rb b/lib/mcp/client/stdio.rb index b224cd2a..b6430001 100644 --- a/lib/mcp/client/stdio.rb +++ b/lib/mcp/client/stdio.rb @@ -6,6 +6,7 @@ require "timeout" require_relative "../../json_rpc_handler" require_relative "../configuration" +require_relative "../duration" require_relative "../methods" require_relative "../protocol_deprecations" require_relative "../version" @@ -55,6 +56,10 @@ def initialize(command:, args: [], env: nil, inherit_env: false, read_timeout: n raise ArgumentError, "max_line_bytes must be a positive Integer" end + unless read_timeout.nil? || Duration.positive_finite?(read_timeout) + raise ArgumentError, "read_timeout must be a positive finite number or nil" + end + @command = command @args = args @env = env diff --git a/lib/mcp/duration.rb b/lib/mcp/duration.rb new file mode 100644 index 00000000..3aa9a589 --- /dev/null +++ b/lib/mcp/duration.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +module MCP + # @api private + module Duration + class << self + def positive_finite?(value) + value.is_a?(Numeric) && value.real? && value.finite? && value.positive? + end + end + end + private_constant :Duration +end diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index db5e6cf5..19c33187 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -3,6 +3,7 @@ require "json" require "set" require "timeout" +require_relative "../../duration" require_relative "../../result_type" require_relative "../../transport" @@ -135,6 +136,7 @@ class InvalidJsonError < StandardError; end DEFAULT_MAX_STREAM_LIFETIME = DEFAULT_SESSION_IDLE_TIMEOUT # Creates a Streamable HTTP transport that can be mounted as a Rack app. + # Timeouts and keepalive intervals take positive, finite durations in seconds. Optional bounds accept nil. # # @param server [MCP::Server] the server whose requests this transport dispatches. # @param stateless [Boolean] when `true`, no session is issued and each POST is self-contained. @@ -312,12 +314,13 @@ def initialize( session_idle_timeout end - if @session_idle_timeout - if @stateless - raise ArgumentError, "session_idle_timeout is not supported in stateless mode." - elsif @session_idle_timeout <= 0 - raise ArgumentError, "session_idle_timeout must be a positive number." + # The value is checked ahead of the mode, so that an invalid one such as `false` is reported as what it is in stateless mode too. + unless @session_idle_timeout.nil? + unless Duration.positive_finite?(@session_idle_timeout) + raise ArgumentError, "session_idle_timeout must be a positive finite number, or nil to disable the timeout." end + + raise ArgumentError, "session_idle_timeout is not supported in stateless mode." if @stateless end unless max_sessions.nil? || (max_sessions.is_a?(Integer) && max_sessions > 0) @@ -352,8 +355,8 @@ def initialize( @max_resource_subscription_bytes = max_resource_subscription_bytes - if !listen_keepalive_interval.nil? && !(listen_keepalive_interval.is_a?(Numeric) && listen_keepalive_interval > 0) - raise ArgumentError, "listen_keepalive_interval must be a positive number or nil" + unless listen_keepalive_interval.nil? || Duration.positive_finite?(listen_keepalive_interval) + raise ArgumentError, "listen_keepalive_interval must be a positive finite number or nil" end @listen_keepalive_interval = listen_keepalive_interval @@ -368,14 +371,14 @@ def initialize( @stream_request_notifications = stream_request_notifications - unless server_to_client_request_timeout.is_a?(Numeric) && server_to_client_request_timeout.positive? - raise ArgumentError, "server_to_client_request_timeout must be a positive number" + unless Duration.positive_finite?(server_to_client_request_timeout) + raise ArgumentError, "server_to_client_request_timeout must be a positive finite number" end @server_to_client_request_timeout = server_to_client_request_timeout - unless stream_write_timeout.nil? || (stream_write_timeout.is_a?(Numeric) && stream_write_timeout.positive?) - raise ArgumentError, "stream_write_timeout must be a positive number or nil" + unless stream_write_timeout.nil? || Duration.positive_finite?(stream_write_timeout) + raise ArgumentError, "stream_write_timeout must be a positive finite number or nil" end @stream_write_timeout = stream_write_timeout @@ -399,8 +402,8 @@ def initialize( @oauth_authenticator = nil end - unless max_stream_lifetime.nil? || (max_stream_lifetime.is_a?(Numeric) && max_stream_lifetime.positive?) - raise ArgumentError, "max_stream_lifetime must be a positive number or nil" + unless max_stream_lifetime.nil? || Duration.positive_finite?(max_stream_lifetime) + raise ArgumentError, "max_stream_lifetime must be a positive finite number or nil" end @max_stream_lifetime = max_stream_lifetime diff --git a/test/mcp/client/http_test.rb b/test/mcp/client/http_test.rb index a29af831..2d7019c2 100644 --- a/test/mcp/client/http_test.rb +++ b/test/mcp/client/http_test.rb @@ -1064,10 +1064,10 @@ def test_listener_applies_the_delay_floor_to_a_zero_retry_value end def test_raises_argument_error_when_max_reconnection_wait_is_not_positive - [0, -1, "60", nil].each do |value| + [0, -1, "60", nil, Float::INFINITY, Float::NAN, Complex(1, 2)].each do |value| error = assert_raises(ArgumentError) { HTTP.new(url: url, max_reconnection_wait: value) } - assert_equal("max_reconnection_wait must be a positive number", error.message) + assert_equal("max_reconnection_wait must be a positive finite number", error.message) end end diff --git a/test/mcp/client/stdio_test.rb b/test/mcp/client/stdio_test.rb index b4303d4a..2ab7da87 100644 --- a/test/mcp/client/stdio_test.rb +++ b/test/mcp/client/stdio_test.rb @@ -11,6 +11,16 @@ class Client class StdioTest < Minitest::Test include DeprecationWarningTestHelper + def test_read_timeout_requires_a_finite_positive_number_or_nil + [nil, 1, 0.5].each do |valid| + assert_instance_of Stdio, Stdio.new(command: "ruby", read_timeout: valid) + end + + [Float::INFINITY, Float::NAN, -1, 0, false, "5", Complex(1, 2)].each do |invalid| + assert_raises(ArgumentError) { Stdio.new(command: "ruby", read_timeout: invalid) } + end + end + def test_send_request_raises_when_connect_not_called Open3.expects(:popen3).never diff --git a/test/mcp/client_test.rb b/test/mcp/client_test.rb index 2acd41e2..a43c9a49 100644 --- a/test/mcp/client_test.rb +++ b/test/mcp/client_test.rb @@ -1819,6 +1819,23 @@ def test_tools_returns_every_page_when_the_server_stops_exactly_at_max_pages assert_equal(["tool1", "tool2"], tools.map(&:name)) end + def test_input_required_max_rounds_requires_a_non_negative_integer + [nil, -1, 1.5, Float::INFINITY].each do |invalid| + assert_raises(ArgumentError) { Client.new(transport: mock, input_required_max_rounds: invalid) } + end + end + + def test_input_required_max_rounds_of_zero_leaves_the_input_to_the_caller + transport = mock + transport.expects(:send_request).once.returns({ + "result" => { "resultType" => "input_required", "inputRequests" => { "a" => { "method" => "elicitation/create" } } }, + }) + client = Client.new(transport: transport, input_required_max_rounds: 0) + client.on_elicitation { flunk("No handler should run") } + + assert_raises(Client::InputRequiredError) { client.call_tool(name: "my_tool") } + end + def test_raises_argument_error_when_max_pages_is_not_positive error = assert_raises(ArgumentError) { Client.new(transport: mock, max_pages: 0) } diff --git a/test/mcp/server/transports/streamable_http_transport_test.rb b/test/mcp/server/transports/streamable_http_transport_test.rb index 4a575a0c..2ea899d4 100644 --- a/test/mcp/server/transports/streamable_http_transport_test.rb +++ b/test/mcp/server/transports/streamable_http_transport_test.rb @@ -5801,18 +5801,42 @@ def close end end + [:session_idle_timeout, :listen_keepalive_interval, :server_to_client_request_timeout, :stream_write_timeout, :max_stream_lifetime].each do |option| + test "#{option} requires a finite positive timeout" do + [Float::INFINITY, Float::NAN, -Float::INFINITY, Complex(1, 2), false, "5"].each do |invalid| + assert_raises(ArgumentError, "#{option}: #{invalid.inspect}") do + StreamableHTTPTransport.new(@server, **{ option => invalid }).close + end + end + end + end + + test "an invalid session_idle_timeout is reported as such whatever the mode" do + [true, false].each do |stateless| + [false, Float::INFINITY, Float::NAN, 0, -1, "5"].each do |invalid| + error = assert_raises(ArgumentError, "stateless: #{stateless}, #{invalid.inspect}") do + StreamableHTTPTransport.new(@server, stateless: stateless, session_idle_timeout: invalid).close + end + + assert_equal("session_idle_timeout must be a positive finite number, or nil to disable the timeout.", error.message) + end + + StreamableHTTPTransport.new(@server, stateless: stateless, session_idle_timeout: nil).close + end + end + test "raises ArgumentError when session_idle_timeout is zero" do error = assert_raises(ArgumentError) do StreamableHTTPTransport.new(@server, session_idle_timeout: 0) end - assert_equal("session_idle_timeout must be a positive number.", error.message) + assert_equal("session_idle_timeout must be a positive finite number, or nil to disable the timeout.", error.message) end test "raises ArgumentError when session_idle_timeout is negative" do error = assert_raises(ArgumentError) do StreamableHTTPTransport.new(@server, session_idle_timeout: -1) end - assert_equal("session_idle_timeout must be a positive number.", error.message) + assert_equal("session_idle_timeout must be a positive finite number, or nil to disable the timeout.", error.message) end test "raises ArgumentError when session_idle_timeout is used with stateless mode" do @@ -9302,11 +9326,11 @@ def wait_until_blocked_or_done(thread) transport.close end - test "stream_write_timeout must be a positive number or nil" do + test "stream_write_timeout must be a positive finite number or nil" do [0, -1, "10"].each do |value| error = assert_raises(ArgumentError) { StreamableHTTPTransport.new(@server, stream_write_timeout: value) } - assert_equal "stream_write_timeout must be a positive number or nil", error.message + assert_equal "stream_write_timeout must be a positive finite number or nil", error.message end end