Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/_client/mrtr.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions docs/_client/transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
7 changes: 6 additions & 1 deletion lib/mcp/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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}.
#
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions lib/mcp/client/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions lib/mcp/client/stdio.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions lib/mcp/duration.rb
Original file line number Diff line number Diff line change
@@ -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
29 changes: 16 additions & 13 deletions lib/mcp/server/transports/streamable_http_transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require "json"
require "set"
require "timeout"
require_relative "../../duration"
require_relative "../../result_type"
require_relative "../../transport"

Expand Down Expand Up @@ -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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The commit message says that non-finite timeouts are rejected. It does not say that some values that work today stop working: Float::INFINITY for session_idle_timeout and max_stream_lifetime meant "never expire" (the issue notes this), false for session_idle_timeout disabled it, and input_required_max_rounds accepted a Float such as 10.0. Please state these in the commit message, with nil as the way to ask for no limit, so that the release notes can carry it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, the commit message now has a Breaking Changes section. Checking each value on main showed that my list, and the "two infinite values" in #735, were incomplete. stream_write_timeout: Float::INFINITY and session_idle_timeout: Float::NAN also meant no limit, and nil replaces both.

nil is not the replacement in two cases. input_required_max_rounds does not accept it, so Float::INFINITY there becomes a large Integer. listen_keepalive_interval: Float::INFINITY closed an authenticated stream at its deadline, which nil does not do while the stream is quiet, so the message suggests a large finite number. I corrected #735 and the PR description too.

#
# @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.
Expand Down Expand Up @@ -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?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session_idle_timeout: false disabled the timeout until now, since the old check tested truthiness. With this change it raises, and together with stateless: true the error is "session_idle_timeout is not supported in stateless mode.", which does not describe the problem. Is refusing false intended? If so, the message for it should say that nil disables the timeout.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, refusing false is intended: the documented type is [Numeric, nil], and the other duration options of this transport already refuse it. You are right about the message. The value is now checked before the mode, so false raises "session_idle_timeout must be a positive finite number, or nil to disable the timeout." with and without stateless: true, and a test covers both. I also changed the other duration messages to say "positive finite number", since "positive number" does not explain why Float::INFINITY is refused.

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)
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions test/mcp/client/http_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 10 additions & 0 deletions test/mcp/client/stdio_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
17 changes: 17 additions & 0 deletions test/mcp/client_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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) }

Expand Down
32 changes: 28 additions & 4 deletions test/mcp/server/transports/streamable_http_transport_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down