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- 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
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.
-
#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).
-
#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).
-
#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.
-
#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_request, #wait_response
Methods included from JsonRpcCommon
#build_jsonrpc_notification, #build_jsonrpc_request, #initialization_params, #ping, #process_jsonrpc_response, #with_retry
Methods inherited from ServerBase
#call_tool_streaming, #on_notification, #ping, #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
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/mcp_client/server_stdio.rb', line 41 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
73 74 75 |
# File 'lib/mcp_client/server_stdio.rb', line 73 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
69 70 71 |
# File 'lib/mcp_client/server_stdio.rb', line 69 def server_info @server_info end |
Instance Method Details
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 |
# File 'lib/mcp_client/server_stdio.rb', line 386 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' => { 'name' => tool_name, 'arguments' => 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
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 |
# File 'lib/mcp_client/server_stdio.rb', line 677 def cleanup return unless @stdin @stdin.close unless @stdin.closed? @stdout.close unless @stdout.closed? @stderr.close unless @stderr.closed? if @wait_thread&.alive? Process.kill('TERM', @wait_thread.pid) @wait_thread.join(1) end @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)
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
# File 'lib/mcp_client/server_stdio.rb', line 413 def complete(ref:, argument:, context: nil) ensure_initialized 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 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
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
# File 'lib/mcp_client/server_stdio.rb', line 78 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 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.
656 657 658 659 660 661 |
# File 'lib/mcp_client/server_stdio.rb', line 656 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.
667 668 669 670 671 672 |
# File 'lib/mcp_client/server_stdio.rb', line 667 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
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
# File 'lib/mcp_client/server_stdio.rb', line 207 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' => { 'name' => prompt_name, 'arguments' => 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)
526 527 528 529 530 531 532 533 534 535 536 537 538 539 |
# File 'lib/mcp_client/server_stdio.rb', line 526 def handle_elicitation_create(request_id, params) # If no callback is registered, decline the request unless @elicitation_request_callback @logger.warn('Received elicitation request but no callback registered, declining') send_elicitation_response(request_id, { 'action' => 'decline' }) return end # Call the registered callback result = @elicitation_request_callback.call(request_id, params) # Send the response back to the server send_elicitation_response(request_id, result) 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
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
# File 'lib/mcp_client/server_stdio.rb', line 141 def handle_line(line) msg = JSON.parse(line) @logger.debug("Received line: #{line.chomp}") # 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 # Skip non-JSONRPC lines in the output stream 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.
513 514 515 516 517 518 519 520 |
# File 'lib/mcp_client/server_stdio.rb', line 513 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)
545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
# File 'lib/mcp_client/server_stdio.rb', line 545 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 send_roots_list_response(request_id, result) 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)
564 565 566 567 568 569 570 571 572 573 574 575 576 577 |
# File 'lib/mcp_client/server_stdio.rb', line 564 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 send_sampling_response(request_id, result) end |
#handle_server_request(msg) ⇒ void
This method returns an undefined value.
Handle incoming JSON-RPC request from server (MCP 2025-06-18)
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
# File 'lib/mcp_client/server_stdio.rb', line 484 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
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/mcp_client/server_stdio.rb', line 180 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
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# File 'lib/mcp_client/server_stdio.rb', line 285 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
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
# File 'lib/mcp_client/server_stdio.rb', line 233 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
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
# File 'lib/mcp_client/server_stdio.rb', line 358 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)
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/mcp_client/server_stdio.rb', line 440 def log_level=(level) ensure_initialized 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 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)
463 464 465 |
# File 'lib/mcp_client/server_stdio.rb', line 463 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)
470 471 472 |
# File 'lib/mcp_client/server_stdio.rb', line 470 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)
477 478 479 |
# File 'lib/mcp_client/server_stdio.rb', line 477 def on_sampling_request(&block) @sampling_request_callback = block end |
#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>
Read a resource by its URI
257 258 259 260 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 257 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)
615 616 617 618 619 620 621 622 |
# File 'lib/mcp_client/server_stdio.rb', line 615 def send_elicitation_response(request_id, result) 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)
629 630 631 632 633 634 635 636 637 638 639 |
# File 'lib/mcp_client/server_stdio.rb', line 629 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
644 645 646 647 648 649 650 651 |
# File 'lib/mcp_client/server_stdio.rb', line 644 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)
583 584 585 586 587 588 589 590 |
# File 'lib/mcp_client/server_stdio.rb', line 583 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)
596 597 598 599 600 601 602 603 604 605 606 607 608 609 |
# File 'lib/mcp_client/server_stdio.rb', line 596 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 |
#start_reader ⇒ Thread
Spawn a reader thread to collect JSON-RPC responses
97 98 99 100 101 102 103 104 105 |
# File 'lib/mcp_client/server_stdio.rb', line 97 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.
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/mcp_client/server_stdio.rb', line 120 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
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
# File 'lib/mcp_client/server_stdio.rb', line 309 def subscribe_resource(uri) ensure_initialized 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 StandardError => e raise MCPClient::Errors::ResourceReadError, "Error subscribing to resource '#{uri}': #{e.}" end |
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# File 'lib/mcp_client/server_stdio.rb', line 334 def unsubscribe_resource(uri) ensure_initialized 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 StandardError => e raise MCPClient::Errors::ResourceReadError, "Error unsubscribing from resource '#{uri}': #{e.}" end |