Skip to content
Merged
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
31 changes: 28 additions & 3 deletions lib/mcp/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,7 @@ def drive_input_required(method:, params:, cancellation:)
backoff = STATE_ONLY_BACKOFF_INITIAL_SECONDS

loop do
cancellation&.raise_if_cancelled!
result = response["result"]
rounds += 1
if rounds > @input_required_max_rounds
Expand All @@ -849,11 +850,11 @@ def drive_input_required(method:, params:, cancellation:)
input_requests = result["inputRequests"] || {}
responses = nil
if input_requests.empty?
sleep(backoff)
sleep_with_cancellation(backoff, cancellation)
backoff = [backoff * 2, STATE_ONLY_BACKOFF_CAP_SECONDS].min
else
backoff = STATE_ONLY_BACKOFF_INITIAL_SECONDS
responses = fulfill_input_requests(input_requests, result)
responses = fulfill_input_requests(input_requests, result, cancellation: cancellation)
end

retry_params = original_params.dup
Expand All @@ -873,8 +874,9 @@ def drive_input_required(method:, params:, cancellation:)
# Dispatches every embedded request to its configured handler and collects
# the answers under the same keys. A kind without a handler falls back to
# the manual path by raising `InputRequiredError` with the full result.
def fulfill_input_requests(input_requests, result)
def fulfill_input_requests(input_requests, result, cancellation:)
input_requests.each_with_object({}) do |(key, entry), responses|
cancellation&.raise_if_cancelled!
entry_method = entry.is_a?(Hash) ? entry["method"] || entry[:method] : nil
handler = @input_required_handlers[entry_method]
unless handler
Expand All @@ -891,6 +893,29 @@ def fulfill_input_requests(input_requests, result)
end
end

# Waits out `seconds`, returning early on cancellation. Re-issuing the request then raises `CancelledError`
# before anything is sent.
def sleep_with_cancellation(seconds, cancellation)
return sleep(seconds) unless cancellation

mutex = Mutex.new
wakeup = ConditionVariable.new
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
hook = cancellation.on_cancel { mutex.synchronize { wakeup.signal } }

# Check cancellation under the wait mutex so a signal between registration and waiting is handled too.
mutex.synchronize do
until cancellation.cancelled?
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
break if remaining <= 0

wakeup.wait(mutex, remaining)
end
end
ensure
cancellation.off_cancel(hook) if hook
end

def input_required?(response)
result = response.is_a?(Hash) ? response["result"] : nil
result.is_a?(Hash) && result["resultType"] == ResultType::INPUT_REQUIRED
Expand Down
120 changes: 120 additions & 0 deletions test/mcp/client_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,126 @@ def test_input_required_loop_backs_off_on_request_state_only_legs
assert_equal([0.05, 0.1], slept)
end

def test_input_required_cancellation_stops_dispatching_handlers
cancellation = MCP::Cancellation.new
transport = mock
transport.expects(:send_notification).never
transport.expects(:send_request).once.returns({
"result" => {
"resultType" => "input_required",
"inputRequests" => {
"first" => { "method" => "elicitation/create", "params" => { "message" => "First" } },
"second" => { "method" => "elicitation/create", "params" => { "message" => "Second" } },
},
},
})

handled = []
client = Client.new(transport: transport)
client.on_elicitation do |params|
handled << params["message"]
cancellation.cancel(reason: "user stopped")
{ action: "decline" }
end

error = assert_raises(MCP::CancelledError) { client.call_tool(name: "my_tool", cancellation: cancellation) }

assert_equal("user stopped", error.reason)
assert_equal(["First"], handled)
end

def test_input_required_cancellation_after_response_takes_precedence_over_round_limit
transport = mock
transport.expects(:send_notification).never
transport.expects(:send_request).once.returns({
"result" => { "resultType" => "input_required", "requestState" => "busy-state" },
})

cancellation = MCP::Cancellation.new
unregister = cancellation.method(:off_cancel)
cancellation.define_singleton_method(:off_cancel) do |handle|
unregister.call(handle)
cancel(reason: "after the response")
end

client = Client.new(transport: transport, input_required_max_rounds: 0)
client.on_elicitation { flunk("No handler should run") }

error = assert_raises(MCP::CancelledError) { client.call_tool(name: "my_tool", cancellation: cancellation) }

assert_equal("after the response", error.reason)
end

def test_input_required_cancellation_wakes_the_backoff_wait
transport = mock
transport.expects(:send_notification).never
state_only = { "result" => { "resultType" => "input_required", "requestState" => "busy-state" } }
final_response = { "result" => { "content" => [] } }
requests = []
transport.stubs(:send_request).with do |args|
requests << args[:request]
true
end.returns(state_only, final_response)

wait_state = Queue.new
backoff_condition = ConditionVariable.new
wait = backoff_condition.method(:wait)
backoff_condition.define_singleton_method(:wait) do |mutex, _timeout|
wait_state << :waiting
# The wait can only finish when the cancellation callback signals it.
wait.call(mutex)
end
ConditionVariable.stubs(:new).returns(ConditionVariable.new, backoff_condition)

cancellation = MCP::Cancellation.new
client = Client.new(transport: transport)
client.on_elicitation { flunk("No handler should run") }
worker = Thread.new do
client.call_tool(name: "my_tool", cancellation: cancellation)
rescue MCP::CancelledError => e
e
ensure
wait_state << :finished
end

canceller = Thread.new do
state = wait_state.pop
cancellation.cancel(reason: "while waiting") if state == :waiting
state
end

assert(canceller.join(5), "The backoff never started")
assert_equal(:waiting, canceller.value)
assert(worker.join(5), "Cancellation did not wake the backoff wait")
assert_kind_of(MCP::CancelledError, worker.value)
assert_equal("while waiting", worker.value.reason)
assert_equal(1, requests.size)
ensure
canceller&.kill&.join
worker&.kill&.join
end

def test_input_required_wait_with_cancellation_times_out_and_deregisters_its_hook
cancellation = MCP::Cancellation.new
handles = []
register = cancellation.method(:on_cancel)
cancellation.define_singleton_method(:on_cancel) do |&block|
register.call(&block).tap { |handle| handles << handle }
end

transport = mock
transport.expects(:send_notification).never
state_only = { "result" => { "resultType" => "input_required", "requestState" => "busy-state" } }
final_response = { "result" => { "content" => [] } }
transport.expects(:send_request).twice.returns(state_only, final_response)
client = Client.new(transport: transport)
client.on_elicitation { flunk("No handler should run") }

assert_equal(final_response, client.call_tool(name: "my_tool", cancellation: cancellation))
assert_equal(3, handles.size)
refute(cancellation.off_cancel(handles[1]), "The backoff hook is still registered")
end

def test_input_required_loop_raises_after_max_rounds
transport = mock
input_required_response = {
Expand Down