Class: MCPClient::ServerStdio
- Inherits:
-
ServerBase
- Object
- ServerBase
- MCPClient::ServerStdio
- Includes:
- JsonRpcTransport
- Defined in:
- lib/mcp_client/server_stdio.rb,
lib/mcp_client/server_stdio/json_rpc_transport.rb
Overview
JSON-RPC implementation of MCP server over stdio.
Defined Under Namespace
Modules: JsonRpcTransport
Constant Summary collapse
- READ_TIMEOUT =
Timeout in seconds for responses
15- SHUTDOWN_GRACE_PERIOD =
Grace period in seconds allowed at each stage of the shutdown sequence (after closing stdin, then after SIGTERM) before escalating further, per MCP 2025-11-25 basic/lifecycle.mdx (Shutdown / stdio): close stdin, wait for the server to exit, send SIGTERM, then SIGKILL if it still runs.
2- STDERR_READ_CHUNK_SIZE =
Chunk size (bytes) used when draining the subprocess stderr pipe
8192- STDERR_MAX_LINE_SIZE =
Maximum bytes buffered for a single unterminated stderr line before it is flushed. Bounds memory when a server writes to stderr without newlines (e.g. progress output using carriage returns).
64 * 1024
Constants inherited from ServerBase
MCPClient::ServerBase::MAX_LIST_PAGES, MCPClient::ServerBase::RELATED_TASK_META_KEY
Instance Attribute Summary collapse
-
#capabilities ⇒ Hash?
readonly
Server capabilities from the initialize response.
-
#command ⇒ String, Array
readonly
The command used to launch the server.
-
#env ⇒ Object
readonly
Returns the value of attribute env.
-
#server_info ⇒ Hash?
readonly
Server info from the initialize response.
Attributes inherited from ServerBase
Instance Method Summary collapse
-
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters.
-
#cleanup ⇒ void
Clean up the server connection Closes all stdio handles and terminates any running processes and threads following the MCP 2025-11-25 stdio shutdown sequence (basic/lifecycle.mdx): close stdin, wait for the server to exit, send SIGTERM if it does not exit within a reasonable time, then SIGKILL if it still does not exit.
-
#complete(ref:, argument:, context: nil) ⇒ Hash
Request completion suggestions from the server (MCP 2025-06-18).
-
#connect ⇒ Boolean
Connect to the MCP server by launching the command process via stdin/stdout.
-
#flush_stderr_lines(buffer) ⇒ void
Emit and remove all newline-terminated lines from the stderr buffer.
-
#flush_stderr_overflow(buffer) ⇒ void
Flush an unterminated stderr fragment that has grown past the size cap, so a newline-less stderr stream cannot buffer without bound.
-
#get_prompt(prompt_name, parameters) ⇒ Object
Get a prompt with the given parameters.
-
#handle_elicitation_create(request_id, params) ⇒ void
Handle elicitation/create request from server (MCP 2025-06-18).
-
#handle_line(line) ⇒ void
Handle a line of output from the stdio server Parses JSON-RPC messages and adds them to pending responses.
-
#handle_ping(request_id) ⇒ void
Handle a server-initiated ping request (MCP ping utility) The receiver MUST respond promptly with an empty result.
-
#handle_roots_list(request_id, params) ⇒ void
Handle roots/list request from server (MCP 2025-06-18).
-
#handle_sampling_create_message(request_id, params) ⇒ void
Handle sampling/createMessage request from server (MCP 2025-11-25).
-
#handle_server_request(msg) ⇒ void
Handle incoming JSON-RPC request from server (MCP 2025-06-18).
-
#initialize(command:, retries: 0, retry_backoff: 1, read_timeout: READ_TIMEOUT, name: nil, logger: nil, env: {}) ⇒ ServerStdio
constructor
Initialize a new ServerStdio instance.
-
#list_prompts ⇒ Array<MCPClient::Prompt>
List all prompts available from the MCP server.
-
#list_resource_templates(cursor: nil) ⇒ Hash
List all resource templates available from the MCP server.
-
#list_resources(cursor: nil) ⇒ Hash
List all resources available from the MCP server.
-
#list_tools ⇒ Array<MCPClient::Tool>
List all tools available from the MCP server.
-
#log_level=(level) ⇒ Hash
Set the logging level on the server (MCP 2025-06-18).
-
#on_elicitation_request(&block) ⇒ void
Register a callback for elicitation requests (MCP 2025-06-18).
-
#on_roots_list_request(&block) ⇒ void
Register a callback for roots/list requests (MCP 2025-06-18).
-
#on_sampling_request(&block) ⇒ void
Register a callback for sampling requests (MCP 2025-11-25).
-
#pin_pipe_encodings ⇒ void
Pin the subprocess pipe encodings to UTF-8 instead of inheriting the process locale (Encoding.default_external).
-
#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>
Read a resource by its URI.
-
#send_elicitation_response(request_id, result) ⇒ void
Send elicitation response back to server (MCP 2025-06-18).
-
#send_error_response(request_id, code, message) ⇒ void
Send error response back to server (MCP 2025-06-18).
-
#send_message(message) ⇒ void
Send a JSON-RPC message to the server.
-
#send_roots_list_response(request_id, result) ⇒ void
Send roots/list response back to server (MCP 2025-06-18).
-
#send_sampling_response(request_id, result) ⇒ void
Send sampling response back to server (MCP 2025-11-25).
-
#signal_server_process(signal) ⇒ void
Send a signal to the server process, tolerating a process that has already exited or cannot be signalled.
-
#start_reader ⇒ Thread
Spawn a reader thread to collect JSON-RPC responses.
-
#start_stderr_reader ⇒ Thread
Spawn a thread to continuously drain the subprocess stderr.
-
#subscribe_resource(uri) ⇒ Boolean
Subscribe to resource updates.
-
#terminate_server_process ⇒ void
Terminate the spawned server process per the MCP 2025-11-25 stdio shutdown sequence (basic/lifecycle.mdx): stdin has already been closed, so wait for the process to exit on its own; if it does not exit within the grace period send SIGTERM, wait again, and finally send SIGKILL.
-
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates.
Methods included from JsonRpcTransport
#call_tool_streaming, #ensure_initialized, #next_id, #perform_initialize, #rpc_notify, #rpc_request, #send_cancellation_notification, #send_request, #wait_response
Methods included from JsonRpcCommon
#build_jsonrpc_notification, #build_jsonrpc_request, #build_named_request_params, #cancellable_request?, #client_capabilities, #client_info_payload, #declare_sampling_tools, #initialization_params, #ping, #process_jsonrpc_response, #registered_callback?, #sampling_tools_supported?, #split_request_meta, #validate_protocol_version!, #with_retry
Methods inherited from ServerBase
#call_tool_streaming, #capability?, #client_info=, #merge_related_task_meta, #on_notification, #ping, #require_capability!, #rpc_notify, #rpc_request
Constructor Details
#initialize(command:, retries: 0, retry_backoff: 1, read_timeout: READ_TIMEOUT, name: nil, logger: nil, env: {}) ⇒ ServerStdio
Initialize a new ServerStdio instance
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/mcp_client/server_stdio.rb', line 47 def initialize(command:, retries: 0, retry_backoff: 1, read_timeout: READ_TIMEOUT, name: nil, logger: nil, env: {}) super(name: name) @command_array = command.is_a?(Array) ? command : nil @command = command.is_a?(Array) ? command.join(' ') : command @mutex = Mutex.new @cond = ConditionVariable.new @next_id = 1 @pending = {} # Ids of requests awaiting a response; used to drop late/unsolicited # responses so @pending cannot grow without bound on a long-lived session @awaiting = {} @initialized = false @server_info = nil @capabilities = nil initialize_logger(logger) @max_retries = retries @retry_backoff = retry_backoff @read_timeout = read_timeout @env = env || {} @elicitation_request_callback = nil # MCP 2025-06-18 @roots_list_request_callback = nil # MCP 2025-06-18 @sampling_request_callback = nil # MCP 2025-11-25 @reader_thread = nil @stderr_thread = nil end |
Instance Attribute Details
#capabilities ⇒ Hash? (readonly)
Server capabilities from the initialize response
79 80 81 |
# File 'lib/mcp_client/server_stdio.rb', line 79 def capabilities @capabilities end |
#command ⇒ String, Array (readonly)
Returns the command used to launch the server.
19 20 21 |
# File 'lib/mcp_client/server_stdio.rb', line 19 def command @command end |
#env ⇒ Object (readonly)
Returns the value of attribute env.
19 |
# File 'lib/mcp_client/server_stdio.rb', line 19 attr_reader :command, :env |
#server_info ⇒ Hash? (readonly)
Server info from the initialize response
75 76 77 |
# File 'lib/mcp_client/server_stdio.rb', line 75 def server_info @server_info end |
Instance Method Details
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/mcp_client/server_stdio.rb', line 420 def call_tool(tool_name, parameters) ensure_initialized req_id = next_id # JSON-RPC method for calling a tool req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'tools/call', 'params' => build_named_request_params(tool_name, parameters) } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end res['result'] rescue StandardError => e raise MCPClient::Errors::ToolCallError, "Error calling tool '#{tool_name}': #{e.}" end |
#cleanup ⇒ void
This method returns an undefined value.
Clean up the server connection Closes all stdio handles and terminates any running processes and threads following the MCP 2025-11-25 stdio shutdown sequence (basic/lifecycle.mdx): close stdin, wait for the server to exit, send SIGTERM if it does not exit within a reasonable time, then SIGKILL if it still does not exit.
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 |
# File 'lib/mcp_client/server_stdio.rb', line 729 def cleanup return unless @stdin @stdin.close unless @stdin.closed? terminate_server_process @stdout.close unless @stdout.closed? @stderr.close unless @stderr.closed? @reader_thread&.kill @stderr_thread&.kill rescue StandardError # Clean up resources during unexpected termination ensure # Release any buffered responses / awaiting markers @mutex.synchronize do @pending.clear @awaiting.clear end @stdin = @stdout = @stderr = @wait_thread = @reader_thread = @stderr_thread = nil end |
#complete(ref:, argument:, context: nil) ⇒ Hash
Request completion suggestions from the server (MCP 2025-06-18)
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# File 'lib/mcp_client/server_stdio.rb', line 447 def complete(ref:, argument:, context: nil) ensure_initialized require_capability!('completions', method: 'completion/complete') req_id = next_id params = { 'ref' => ref, 'argument' => argument } params['context'] = context if context req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'completion/complete', 'params' => params } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end res.dig('result', 'completion') || { 'values' => [] } rescue MCPClient::Errors::CapabilityError raise rescue StandardError => e raise MCPClient::Errors::ServerError, "Error requesting completion: #{e.}" end |
#connect ⇒ Boolean
Connect to the MCP server by launching the command process via stdin/stdout
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/mcp_client/server_stdio.rb', line 84 def connect if @command_array if @env.any? @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(@env, *@command_array) else @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(*@command_array) end elsif @env.any? @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(@env, @command) else @stdin, @stdout, @stderr, @wait_thread = Open3.popen3(@command) end pin_pipe_encodings true rescue StandardError => e raise MCPClient::Errors::ConnectionError, "Failed to connect to MCP server: #{e.}" end |
#flush_stderr_lines(buffer) ⇒ void
This method returns an undefined value.
Emit and remove all newline-terminated lines from the stderr buffer.
705 706 707 708 709 710 |
# File 'lib/mcp_client/server_stdio.rb', line 705 def flush_stderr_lines(buffer) while (newline_index = buffer.index("\n")) line = buffer.slice!(0, newline_index + 1) @logger.debug("[stderr] #{line.chomp}") end end |
#flush_stderr_overflow(buffer) ⇒ void
This method returns an undefined value.
Flush an unterminated stderr fragment that has grown past the size cap, so a newline-less stderr stream cannot buffer without bound.
716 717 718 719 720 721 |
# File 'lib/mcp_client/server_stdio.rb', line 716 def flush_stderr_overflow(buffer) return if buffer.bytesize <= STDERR_MAX_LINE_SIZE @logger.debug("[stderr] #{buffer}") buffer.clear end |
#get_prompt(prompt_name, parameters) ⇒ Object
Get a prompt with the given parameters
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 |
# File 'lib/mcp_client/server_stdio.rb', line 235 def get_prompt(prompt_name, parameters) ensure_initialized req_id = next_id # JSON-RPC method for getting a prompt req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'prompts/get', 'params' => build_named_request_params(prompt_name, parameters) } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end res['result'] rescue StandardError => e raise MCPClient::Errors::PromptGetError, "Error calling prompt '#{prompt_name}': #{e.}" end |
#handle_elicitation_create(request_id, params) ⇒ void
This method returns an undefined value.
Handle elicitation/create request from server (MCP 2025-06-18)
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
# File 'lib/mcp_client/server_stdio.rb', line 566 def handle_elicitation_create(request_id, params) # Without a callback there is no user to interact with: answer with a # JSON-RPC error rather than fabricating a user "decline". unless @elicitation_request_callback @logger.warn('Received elicitation request but no callback registered') send_error_response(request_id, -32_601, 'Elicitation not supported: no handler configured') return end # Call the registered callback result = @elicitation_request_callback.call(request_id, params) # Send the response back to the server (echoing related-task _meta) send_elicitation_response(request_id, (result, params)) end |
#handle_line(line) ⇒ void
This method returns an undefined value.
Handle a line of output from the stdio server Parses JSON-RPC messages and adds them to pending responses
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/mcp_client/server_stdio.rb', line 161 def handle_line(line) msg = JSON.parse(line) @logger.debug("Received line: #{line.chomp}") # A JSON-parseable line that is not an object cannot be a JSON-RPC # message; skip it rather than raising inside the reader thread unless msg.is_a?(Hash) @logger.debug("Skipping non-object JSON-RPC line: #{line.chomp}") return end # Dispatch JSON-RPC requests from server (has id AND method) - MCP 2025-06-18 if msg['method'] && msg.key?('id') handle_server_request(msg) return end # Dispatch JSON-RPC notifications (no id, has method) if msg['method'] && !msg.key?('id') @notification_callback&.call(msg['method'], msg['params']) return end # Handle standard JSON-RPC responses (has id, no method) id = msg['id'] return unless id @mutex.synchronize do # Only retain a response that corresponds to an outstanding request. # Late responses (arriving after the caller timed out) and unsolicited # responses are dropped so @pending cannot grow without bound. if @awaiting.key?(id) @pending[id] = msg @cond.broadcast else @logger.debug("Discarding response for unknown or expired request id=#{id}") end end rescue JSON::ParserError, EncodingError # Skip non-JSONRPC or undecodable lines in the output stream so a single # bad line cannot kill the reader thread end |
#handle_ping(request_id) ⇒ void
This method returns an undefined value.
Handle a server-initiated ping request (MCP ping utility) The receiver MUST respond promptly with an empty result.
553 554 555 556 557 558 559 560 |
# File 'lib/mcp_client/server_stdio.rb', line 553 def handle_ping(request_id) response = { 'jsonrpc' => '2.0', 'id' => request_id, 'result' => {} } (response) end |
#handle_roots_list(request_id, params) ⇒ void
This method returns an undefined value.
Handle roots/list request from server (MCP 2025-06-18)
586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
# File 'lib/mcp_client/server_stdio.rb', line 586 def handle_roots_list(request_id, params) # If no callback is registered, return empty roots list unless @roots_list_request_callback @logger.debug('Received roots/list request but no callback registered, returning empty list') send_roots_list_response(request_id, { 'roots' => [] }) return end # Call the registered callback result = @roots_list_request_callback.call(request_id, params) # Send the response back to the server (echoing related-task _meta) send_roots_list_response(request_id, (result, params)) end |
#handle_sampling_create_message(request_id, params) ⇒ void
This method returns an undefined value.
Handle sampling/createMessage request from server (MCP 2025-11-25)
605 606 607 608 609 610 611 612 613 614 615 616 617 618 |
# File 'lib/mcp_client/server_stdio.rb', line 605 def (request_id, params) # If no callback is registered, return error unless @sampling_request_callback @logger.warn('Received sampling request but no callback registered, returning error') send_error_response(request_id, -1, 'Sampling not supported') return end # Call the registered callback result = @sampling_request_callback.call(request_id, params) # Send the response back to the server (echoing related-task _meta) send_sampling_response(request_id, (result, params)) end |
#handle_server_request(msg) ⇒ void
This method returns an undefined value.
Handle incoming JSON-RPC request from server (MCP 2025-06-18)
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 |
# File 'lib/mcp_client/server_stdio.rb', line 524 def handle_server_request(msg) request_id = msg['id'] method = msg['method'] params = msg['params'] || {} @logger.debug("Received server request: #{method} (id: #{request_id})") case method when 'ping' handle_ping(request_id) when 'elicitation/create' handle_elicitation_create(request_id, params) when 'roots/list' handle_roots_list(request_id, params) when 'sampling/createMessage' (request_id, params) else # Unknown request method, send error response send_error_response(request_id, -32_601, "Method not found: #{method}") end rescue StandardError => e @logger.error("Error handling server request: #{e.}") send_error_response(request_id, -32_603, "Internal error: #{e.}") end |
#list_prompts ⇒ Array<MCPClient::Prompt>
List all prompts available from the MCP server
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 |
# File 'lib/mcp_client/server_stdio.rb', line 208 def list_prompts ensure_initialized collect_paginated('prompts') do |cursor| params = {} params['cursor'] = cursor if cursor req_id = next_id req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'prompts/list', 'params' => params } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end result = res['result'] || {} prompts = (result['prompts'] || []).map { |td| MCPClient::Prompt.from_json(td, server: self) } [prompts, result['nextCursor']] end rescue StandardError => e raise MCPClient::Errors::PromptGetError, "Error listing prompts: #{e.}" end |
#list_resource_templates(cursor: nil) ⇒ Hash
List all resource templates available from the MCP server
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
# File 'lib/mcp_client/server_stdio.rb', line 313 def list_resource_templates(cursor: nil) ensure_initialized req_id = next_id params = {} params['cursor'] = cursor if cursor req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'resources/templates/list', 'params' => params } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end result = res['result'] || {} templates = (result['resourceTemplates'] || []).map { |td| MCPClient::ResourceTemplate.from_json(td, server: self) } { 'resourceTemplates' => templates, 'nextCursor' => result['nextCursor'] } rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error listing resource templates: #{e.}" end |
#list_resources(cursor: nil) ⇒ Hash
List all resources available from the MCP server
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
# File 'lib/mcp_client/server_stdio.rb', line 261 def list_resources(cursor: nil) ensure_initialized req_id = next_id params = {} params['cursor'] = cursor if cursor req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'resources/list', 'params' => params } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end result = res['result'] || {} resources = (result['resources'] || []).map { |td| MCPClient::Resource.from_json(td, server: self) } { 'resources' => resources, 'nextCursor' => result['nextCursor'] } rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error listing resources: #{e.}" end |
#list_tools ⇒ Array<MCPClient::Tool>
List all tools available from the MCP server
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 |
# File 'lib/mcp_client/server_stdio.rb', line 392 def list_tools ensure_initialized collect_paginated('tools') do |cursor| params = {} params['cursor'] = cursor if cursor req_id = next_id # JSON-RPC method for listing tools req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'tools/list', 'params' => params } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end result = res['result'] || {} tools = (result['tools'] || []).map { |td| MCPClient::Tool.from_json(td, server: self) } [tools, result['nextCursor']] end rescue StandardError => e raise MCPClient::Errors::ToolCallError, "Error listing tools: #{e.}" end |
#log_level=(level) ⇒ Hash
Set the logging level on the server (MCP 2025-06-18)
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
# File 'lib/mcp_client/server_stdio.rb', line 477 def log_level=(level) ensure_initialized require_capability!('logging', method: 'logging/setLevel') req_id = next_id req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'logging/setLevel', 'params' => { 'level' => level } } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end res['result'] || {} rescue MCPClient::Errors::CapabilityError raise rescue StandardError => e raise MCPClient::Errors::ServerError, "Error setting log level: #{e.}" end |
#on_elicitation_request(&block) ⇒ void
This method returns an undefined value.
Register a callback for elicitation requests (MCP 2025-06-18)
503 504 505 |
# File 'lib/mcp_client/server_stdio.rb', line 503 def on_elicitation_request(&block) @elicitation_request_callback = block end |
#on_roots_list_request(&block) ⇒ void
This method returns an undefined value.
Register a callback for roots/list requests (MCP 2025-06-18)
510 511 512 |
# File 'lib/mcp_client/server_stdio.rb', line 510 def on_roots_list_request(&block) @roots_list_request_callback = block end |
#on_sampling_request(&block) ⇒ void
This method returns an undefined value.
Register a callback for sampling requests (MCP 2025-11-25)
517 518 519 |
# File 'lib/mcp_client/server_stdio.rb', line 517 def on_sampling_request(&block) @sampling_request_callback = block end |
#pin_pipe_encodings ⇒ void
This method returns an undefined value.
Pin the subprocess pipe encodings to UTF-8 instead of inheriting the process locale (Encoding.default_external). JSON-RPC messages MUST be UTF-8 encoded (MCP 2025-11-25 basic/transports.mdx); under a non-UTF-8 locale (e.g. LANG=C) a valid UTF-8 message would otherwise fail to decode and kill the reader thread. The server MAY also write UTF-8 to stderr, so that pipe is pinned as well.
109 110 111 112 113 |
# File 'lib/mcp_client/server_stdio.rb', line 109 def pin_pipe_encodings [@stdin, @stdout, @stderr].each do |io| io&.set_encoding(Encoding::UTF_8) end end |
#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>
Read a resource by its URI
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/mcp_client/server_stdio.rb', line 285 def read_resource(uri) ensure_initialized req_id = next_id # JSON-RPC method for reading a resource req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'resources/read', 'params' => { 'uri' => uri } } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end result = res['result'] || {} contents = result['contents'] || [] contents.map { |content| MCPClient::ResourceContent.from_json(content) } rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error reading resource '#{uri}': #{e.}" end |
#send_elicitation_response(request_id, result) ⇒ void
This method returns an undefined value.
Send elicitation response back to server (MCP 2025-06-18)
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 |
# File 'lib/mcp_client/server_stdio.rb', line 656 def send_elicitation_response(request_id, result) # Error-shaped results become JSON-RPC error responses (e.g. -32602 for # an undeclared elicitation mode), mirroring the sampling error path. if result.is_a?(Hash) && result['error'] send_error_response(request_id, result['error']['code'] || -32_603, result['error']['message'] || 'Elicitation error') return end response = { 'jsonrpc' => '2.0', 'id' => request_id, 'result' => result } (response) end |
#send_error_response(request_id, code, message) ⇒ void
This method returns an undefined value.
Send error response back to server (MCP 2025-06-18)
678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/mcp_client/server_stdio.rb', line 678 def send_error_response(request_id, code, ) response = { 'jsonrpc' => '2.0', 'id' => request_id, 'error' => { 'code' => code, 'message' => } } (response) end |
#send_message(message) ⇒ void
This method returns an undefined value.
Send a JSON-RPC message to the server
693 694 695 696 697 698 699 700 |
# File 'lib/mcp_client/server_stdio.rb', line 693 def () json = JSON.generate() @stdin.puts(json) @stdin.flush @logger.debug("Sent message: #{json}") rescue StandardError => e @logger.error("Error sending message: #{e.}") end |
#send_roots_list_response(request_id, result) ⇒ void
This method returns an undefined value.
Send roots/list response back to server (MCP 2025-06-18)
624 625 626 627 628 629 630 631 |
# File 'lib/mcp_client/server_stdio.rb', line 624 def send_roots_list_response(request_id, result) response = { 'jsonrpc' => '2.0', 'id' => request_id, 'result' => result } (response) end |
#send_sampling_response(request_id, result) ⇒ void
This method returns an undefined value.
Send sampling response back to server (MCP 2025-11-25)
637 638 639 640 641 642 643 644 645 646 647 648 649 650 |
# File 'lib/mcp_client/server_stdio.rb', line 637 def send_sampling_response(request_id, result) # Check if result contains an error if result.is_a?(Hash) && result['error'] send_error_response(request_id, result['error']['code'] || -1, result['error']['message'] || 'Sampling error') return end response = { 'jsonrpc' => '2.0', 'id' => request_id, 'result' => result } (response) end |
#signal_server_process(signal) ⇒ void
This method returns an undefined value.
Send a signal to the server process, tolerating a process that has already exited or cannot be signalled.
769 770 771 772 773 |
# File 'lib/mcp_client/server_stdio.rb', line 769 def signal_server_process(signal) Process.kill(signal, @wait_thread.pid) rescue Errno::ESRCH, Errno::EPERM => e @logger.debug("Could not send SIG#{signal} to server process: #{e.class}") end |
#start_reader ⇒ Thread
Spawn a reader thread to collect JSON-RPC responses
117 118 119 120 121 122 123 124 125 |
# File 'lib/mcp_client/server_stdio.rb', line 117 def start_reader @reader_thread = Thread.new do @stdout.each_line do |line| handle_line(line) end rescue StandardError # Reader thread aborted unexpectedly end end |
#start_stderr_reader ⇒ Thread
Spawn a thread to continuously drain the subprocess stderr.
The child's stderr pipe has a fixed OS buffer (typically 64KB). If it is never read, a server that logs verbosely to stderr eventually blocks on write once the buffer fills, which stalls the whole subprocess (it stops producing stdout / reading stdin) and deadlocks the client. Draining stderr keeps the pipe empty; lines are surfaced at debug level.
Reads happen in bounded chunks (not IO#each_line) so that a server which writes to stderr without newline delimiters cannot make the client buffer a single "line" without limit: any pending fragment larger than STDERR_MAX_LINE_SIZE is flushed rather than retained.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
# File 'lib/mcp_client/server_stdio.rb', line 140 def start_stderr_reader @stderr_thread = Thread.new do buffer = +'' loop do buffer << @stderr.readpartial(STDERR_READ_CHUNK_SIZE) flush_stderr_lines(buffer) flush_stderr_overflow(buffer) end rescue IOError # EOFError (a subclass of IOError) on EOF, or IOError on close; # emit any trailing partial line before exiting @logger.debug("[stderr] #{buffer.chomp}") if buffer && !buffer.empty? rescue StandardError # reader aborted unexpectedly; nothing actionable end end |
#subscribe_resource(uri) ⇒ Boolean
Subscribe to resource updates
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 |
# File 'lib/mcp_client/server_stdio.rb', line 337 def subscribe_resource(uri) ensure_initialized require_capability!('resources', 'subscribe', method: 'resources/subscribe') req_id = next_id req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'resources/subscribe', 'params' => { 'uri' => uri } } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end true rescue MCPClient::Errors::CapabilityError raise rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error subscribing to resource '#{uri}': #{e.}" end |
#terminate_server_process ⇒ void
This method returns an undefined value.
Terminate the spawned server process per the MCP 2025-11-25 stdio shutdown sequence (basic/lifecycle.mdx): stdin has already been closed, so wait for the process to exit on its own; if it does not exit within the grace period send SIGTERM, wait again, and finally send SIGKILL.
754 755 756 757 758 759 760 761 762 763 |
# File 'lib/mcp_client/server_stdio.rb', line 754 def terminate_server_process return unless @wait_thread return if @wait_thread.join(SHUTDOWN_GRACE_PERIOD) signal_server_process('TERM') return if @wait_thread.join(SHUTDOWN_GRACE_PERIOD) signal_server_process('KILL') @wait_thread.join(SHUTDOWN_GRACE_PERIOD) end |
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 |
# File 'lib/mcp_client/server_stdio.rb', line 365 def unsubscribe_resource(uri) ensure_initialized require_capability!('resources', 'subscribe', method: 'resources/unsubscribe') req_id = next_id req = { 'jsonrpc' => '2.0', 'id' => req_id, 'method' => 'resources/unsubscribe', 'params' => { 'uri' => uri } } send_request(req) res = wait_response(req_id) if (err = res['error']) raise MCPClient::Errors::ServerError, err['message'] end true rescue MCPClient::Errors::CapabilityError raise rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error unsubscribing from resource '#{uri}': #{e.}" end |