Add client-level connect handshake to stdio transport

## Motivation and Context

This commit implements Phase 1 of 3 for #334.

The MCP specification requires an `initialize` request followed by
a `notifications/initialized` notification before any other interaction.
PR #327 added `MCP::Client#connect` and `MCP::Client::HTTP#connect`
to expose this handshake explicitly for the HTTP transport,
but stdio remained on its private `initialize_session` lazy-init path,
inconsistent with the Python SDK (`ClientSession.initialize()`) and
TypeScript SDK (`Client.connect(transport)`),
both of which require an explicit handshake call regardless of transport.

The implicit init path on the first `send_request` is
preserved as a non-breaking compatibility shim. Public API added on `Stdio`:

- `connect(client_info:, protocol_version:, capabilities:)` performs the
  handshake, validates the negotiated `protocolVersion` against
  `MCP::Configuration::SUPPORTED_STABLE_PROTOCOL_VERSIONS`,
  caches the `InitializeResult`, and is idempotent.
- `connected?` reports handshake completion.
- `server_info` exposes the cached `InitializeResult`.

Documentation and examples are updated so new users learn the explicit pattern
from the start.

## How Has This Been Tested?

Fifteen regression tests cover: explicit handshake, `server_info` caching,
idempotence, custom keyword arguments, JSON-RPC error response, missing
or non-Hash `result`, unsupported protocol version with state rollback,
state rollback when the `notifications/initialized` write fails,
retry after a failed handshake, and the `connected?` / `server_info` lifecycle.

The pre-existing stdio tests pass without modification, verifying that
the implicit-init compatibility path still works.

## Breaking Changes

None for the typical "implicit init via `client.tools` / `client.call_tool`" usage.
Existing stdio clients keep working unchanged.

Three observable behavior changes for code that inspects transport state directly:

- `Client#connected?` for a never-initialized stdio client returns `false`
  (previously fell through to a `true` default via the `respond_to?` fallback).
- `Client#server_info` for stdio returns the cached `InitializeResult`
  after the handshake (previously always `nil` via the fallback).
- The implicit handshake path now validates the server's negotiated
  protocol version, raising `RequestHandlerError` for unsupported versions.
  Production servers that return one of the supported versions are unaffected;
  this closes a pre-existing spec-conformance gap on stdio.
This commit is contained in:
Koichi ITO 2026-05-03 02:43:19 +09:00
commit 46b738e945

View file

@ -722,8 +722,453 @@ module MCP
stdout_write.close
end
def test_connect_performs_initialize_handshake_explicitly
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
received_methods = []
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
received_methods << init_request["method"]
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: {
protocolVersion: "2025-11-25",
capabilities: { tools: {} },
serverInfo: { name: "test-server", version: "1.0.0" },
},
))
stdout_write.flush
notification_line = stdin_read.gets
received_methods << JSON.parse(notification_line)["method"]
end
result = transport.connect
server_thread.join
assert_equal(["initialize", "notifications/initialized"], received_methods)
assert_equal("2025-11-25", result["protocolVersion"])
assert_equal({ "tools" => {} }, result["capabilities"])
assert_equal({ "name" => "test-server", "version" => "1.0.0" }, result["serverInfo"])
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connect_caches_server_info
transport, server_thread, pipes = stub_successful_connect
transport.connect
assert_equal("2025-11-25", transport.server_info["protocolVersion"])
assert_equal({ "tools" => {} }, transport.server_info["capabilities"])
ensure
server_thread.join
pipes.each(&:close)
end
def test_connect_is_idempotent
transport, server_thread, pipes = stub_successful_connect
first_result = transport.connect
second_result = transport.connect
assert_same(first_result, second_result)
ensure
server_thread.join
pipes.each(&:close)
end
def test_connect_accepts_custom_parameters
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
sent_init_params = nil
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
sent_init_params = init_request["params"]
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: { protocolVersion: "2025-03-26" },
))
stdout_write.flush
stdin_read.gets
end
transport.connect(
client_info: { name: "my-app", version: "9.9" },
protocol_version: "2025-03-26",
capabilities: { roots: { listChanged: true } },
)
assert_equal("2025-03-26", sent_init_params["protocolVersion"])
assert_equal({ "name" => "my-app", "version" => "9.9" }, sent_init_params["clientInfo"])
assert_equal({ "roots" => { "listChanged" => true } }, sent_init_params["capabilities"])
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connect_raises_on_jsonrpc_error_response
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
error: { code: -32602, message: "boom" },
))
stdout_write.flush
end
error = assert_raises(RequestHandlerError) do
transport.connect
end
assert_includes(error.message, "boom")
refute_predicate(transport, :connected?)
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connect_raises_on_missing_result
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
))
stdout_write.flush
end
error = assert_raises(RequestHandlerError) do
transport.connect
end
assert_includes(error.message, "missing result in response")
refute_predicate(transport, :connected?)
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connect_raises_on_non_hash_result
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: [],
))
stdout_write.flush
end
error = assert_raises(RequestHandlerError) do
transport.connect
end
assert_includes(error.message, "missing result in response")
refute_predicate(transport, :connected?)
assert_nil(transport.server_info)
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connect_clears_state_when_initialized_notification_fails
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
# Close stdin_read first so the next write to @stdin (the notification) raises EPIPE.
stdin_read.close
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: { protocolVersion: "2025-11-25" },
))
stdout_write.flush
end
assert_raises(RequestHandlerError) do
transport.connect
end
refute_predicate(transport, :connected?)
assert_nil(transport.server_info)
ensure
server_thread.join
[stdin_read, stdin_write, stdout_read, stdout_write].each do |io|
io.close unless io.closed?
end
end
def test_connect_can_be_retried_after_failed_handshake
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
server_thread = Thread.new do
# First handshake: server returns an unsupported protocol version.
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: { protocolVersion: "1999-01-01" },
))
stdout_write.flush
# Second handshake: server returns a supported protocol version.
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: { protocolVersion: "2025-11-25" },
))
stdout_write.flush
stdin_read.gets
end
assert_raises(RequestHandlerError) do
transport.connect
end
refute_predicate(transport, :connected?)
assert_nil(transport.server_info)
result = transport.connect
server_thread.join
assert_predicate(transport, :connected?)
assert_equal("2025-11-25", result["protocolVersion"])
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connect_raises_on_unsupported_protocol_version
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
sent_methods = []
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
sent_methods << init_request["method"]
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: { protocolVersion: "1999-01-01" },
))
stdout_write.flush
end
error = assert_raises(RequestHandlerError) do
transport.connect
end
assert_includes(error.message, "unsupported protocol version")
assert_includes(error.message, "1999-01-01")
assert_equal(["initialize"], sent_methods)
refute_predicate(transport, :connected?)
assert_nil(transport.server_info)
ensure
server_thread.join
stdin_read.close
stdin_write.close
stdout_read.close
stdout_write.close
end
def test_connected_is_false_before_first_send_request
transport = Stdio.new(command: "ruby", args: ["server.rb"])
refute_predicate(transport, :connected?)
end
def test_connected_is_true_after_explicit_connect
transport, server_thread, pipes = stub_successful_connect
refute_predicate(transport, :connected?)
transport.connect
assert_predicate(transport, :connected?)
ensure
server_thread.join
pipes.each(&:close)
end
def test_connected_is_false_after_close
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, stderr_write = IO.pipe
wait_thread = mock("wait_thread")
wait_thread.stubs(:alive?).returns(true)
wait_thread.stubs(:value).returns(nil)
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
transport.start
transport.instance_variable_set(:@initialized, true)
assert_predicate(transport, :connected?)
transport.close
refute_predicate(transport, :connected?)
ensure
[stdin_read, stdin_write, stdout_read, stdout_write, stderr_read, stderr_write].each do |io|
io.close unless io.closed?
end
end
def test_server_info_is_nil_before_connect
transport = Stdio.new(command: "ruby", args: ["server.rb"])
assert_nil(transport.server_info)
end
def test_server_info_is_cleared_after_close
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, stderr_write = IO.pipe
wait_thread = mock("wait_thread")
wait_thread.stubs(:alive?).returns(true)
wait_thread.stubs(:value).returns(nil)
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
transport.start
transport.instance_variable_set(:@initialized, true)
transport.instance_variable_set(:@server_info, { "protocolVersion" => "2025-11-25" })
transport.close
assert_nil(transport.server_info)
ensure
[stdin_read, stdin_write, stdout_read, stdout_write, stderr_read, stderr_write].each do |io|
io.close unless io.closed?
end
end
private
def stub_successful_connect
stdin_read, stdin_write = IO.pipe
stdout_read, stdout_write = IO.pipe
stderr_read, _ = IO.pipe
Open3.stubs(:popen3).returns([stdin_write, stdout_read, stderr_read, mock_wait_thread])
transport = Stdio.new(command: "ruby", args: ["server.rb"])
server_thread = Thread.new do
init_line = stdin_read.gets
init_request = JSON.parse(init_line)
stdout_write.puts(JSON.generate(
jsonrpc: "2.0",
id: init_request["id"],
result: {
protocolVersion: "2025-11-25",
capabilities: { tools: {} },
serverInfo: { name: "test-server", version: "1.0.0" },
},
))
stdout_write.flush
stdin_read.gets
end
[transport, server_thread, [stdin_read, stdin_write, stdout_read, stdout_write]]
end
def mock_wait_thread
thread = mock("wait_thread")
thread.stubs(:alive?).returns(true)