Class: MCPClient::ServerStreamableHTTP
- Inherits:
-
ServerBase
- Object
- ServerBase
- MCPClient::ServerStreamableHTTP
- Includes:
- JsonRpcTransport
- Defined in:
- lib/mcp_client/server_streamable_http.rb,
lib/mcp_client/server_streamable_http/json_rpc_transport.rb
Overview
Implementation of MCP server that communicates via Streamable HTTP transport (MCP 2025-06-18) This transport uses HTTP POST for RPC calls with optional SSE responses, and GET for event streams Compliant with MCP specification version 2025-06-18
Key features:
-
Supports server-sent events (SSE) for real-time notifications
-
Handles ping/pong keepalive mechanism
-
Thread-safe connection management
-
Automatic reconnection with exponential backoff
Defined Under Namespace
Modules: JsonRpcTransport
Constant Summary collapse
- DEFAULT_READ_TIMEOUT =
Default values for connection settings
30- DEFAULT_MAX_RETRIES =
3- SSE_CONNECTION_TIMEOUT =
SSE connection settings
300- SSE_RECONNECT_DELAY =
5 minutes
1- SSE_MAX_RECONNECT_DELAY =
Initial reconnect delay in seconds
30- THREAD_JOIN_TIMEOUT =
Maximum reconnect delay in seconds
5
Instance Attribute Summary collapse
-
#base_url ⇒ String
readonly
The base URL of the MCP server.
-
#capabilities ⇒ Hash?
readonly
Server capabilities from initialize response.
-
#endpoint ⇒ String
readonly
The JSON-RPC endpoint path.
-
#server_info ⇒ Hash?
readonly
Server information from initialize response.
-
#tools ⇒ Object
readonly
Returns the value of attribute tools.
Attributes inherited from ServerBase
Instance Method Summary collapse
-
#apply_request_headers(req, request) ⇒ Object
Override apply_request_headers to add session and SSE headers for MCP protocol.
-
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters.
-
#call_tool_streaming(tool_name, parameters) ⇒ Enumerator
Stream tool call (default implementation returns single-value stream).
-
#cleanup ⇒ Object
Clean up the server connection Properly closes HTTP connections, stops threads, and clears cached state.
-
#complete(ref:, argument:, context: nil) ⇒ Hash
Request completion suggestions from the server (MCP 2025-06-18).
-
#connect ⇒ Boolean
Connect to the MCP server over Streamable HTTP.
-
#get_prompt(prompt_name, parameters) ⇒ Object
Get a prompt with the given parameters.
-
#handle_successful_response(response, request) ⇒ Object
Override handle_successful_response to capture session ID.
-
#initialize(base_url:, **options) ⇒ ServerStreamableHTTP
constructor
A new instance of ServerStreamableHTTP.
-
#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.
-
#subscribe_resource(uri) ⇒ Boolean
Subscribe to resource updates.
-
#terminate_session ⇒ Boolean
Terminate the current session (if any).
-
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates.
Methods included from HttpTransportBase
#rpc_notify, #rpc_request, #valid_server_url?, #valid_session_id?
Methods included from JsonRpcCommon
#build_jsonrpc_notification, #build_jsonrpc_request, #initialization_params, #ping, #process_jsonrpc_response, #with_retry
Methods inherited from ServerBase
#on_notification, #ping, #rpc_notify, #rpc_request
Constructor Details
#initialize(base_url:, **options) ⇒ ServerStreamableHTTP
Returns a new instance of ServerStreamableHTTP.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
# File 'lib/mcp_client/server_streamable_http.rb', line 54 def initialize(base_url:, **) opts = .merge() super(name: opts[:name]) initialize_logger(opts[:logger]) @max_retries = opts[:retries] @retry_backoff = opts[:retry_backoff] # Validate and normalize base_url raise ArgumentError, "Invalid or insecure server URL: #{base_url}" unless valid_server_url?(base_url) # Normalize base_url and handle cases where full endpoint is provided in base_url uri = URI.parse(base_url.chomp('/')) # Helper to build base URL without default ports build_base_url = lambda do |parsed_uri| port_part = if parsed_uri.port && !((parsed_uri.scheme == 'http' && parsed_uri.port == 80) || (parsed_uri.scheme == 'https' && parsed_uri.port == 443)) ":#{parsed_uri.port}" else '' end "#{parsed_uri.scheme}://#{parsed_uri.host}#{port_part}" end @base_url = build_base_url.call(uri) @endpoint = if uri.path && !uri.path.empty? && uri.path != '/' && opts[:endpoint] == '/rpc' # If base_url contains a path and we're using default endpoint, # treat the path as the endpoint and use the base URL without path uri.path else # Standard case: base_url is just scheme://host:port, endpoint is separate opts[:endpoint] end # Set up headers for Streamable HTTP requests @headers = opts[:headers].merge({ 'Content-Type' => 'application/json', 'Accept' => 'text/event-stream, application/json', 'Accept-Encoding' => 'gzip', 'User-Agent' => "ruby-mcp-client/#{MCPClient::VERSION}", 'Cache-Control' => 'no-cache' }) @read_timeout = opts[:read_timeout] @faraday_config = opts[:faraday_config] @tools = nil @tools_data = nil @prompts = nil @prompts_data = nil @resources = nil @resources_data = nil @request_id = 0 @mutex = Monitor.new @connection_established = false @initialized = false @http_conn = nil @session_id = nil @last_event_id = nil @oauth_provider = opts[:oauth_provider] # SSE events connection state @events_connection = nil @events_thread = nil @buffer = '' # Buffer for partial SSE event data @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 end |
Instance Attribute Details
#base_url ⇒ String (readonly)
Returns The base URL of the MCP server.
42 43 44 |
# File 'lib/mcp_client/server_streamable_http.rb', line 42 def base_url @base_url end |
#capabilities ⇒ Hash? (readonly)
Server capabilities from initialize response
50 51 52 |
# File 'lib/mcp_client/server_streamable_http.rb', line 50 def capabilities @capabilities end |
#endpoint ⇒ String (readonly)
Returns The JSON-RPC endpoint path.
42 |
# File 'lib/mcp_client/server_streamable_http.rb', line 42 attr_reader :base_url, :endpoint, :tools |
#server_info ⇒ Hash? (readonly)
Server information from initialize response
46 47 48 |
# File 'lib/mcp_client/server_streamable_http.rb', line 46 def server_info @server_info end |
#tools ⇒ Object (readonly)
Returns the value of attribute tools.
42 |
# File 'lib/mcp_client/server_streamable_http.rb', line 42 attr_reader :base_url, :endpoint, :tools |
Instance Method Details
#apply_request_headers(req, request) ⇒ Object
Override apply_request_headers to add session and SSE headers for MCP protocol
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
# File 'lib/mcp_client/server_streamable_http.rb', line 396 def apply_request_headers(req, request) super # Add session and protocol version headers for non-initialize requests if request['method'] != 'initialize' if @session_id req.headers['Mcp-Session-Id'] = @session_id @logger.debug("Adding session header: Mcp-Session-Id: #{@session_id}") end if @protocol_version req.headers['Mcp-Protocol-Version'] = @protocol_version @logger.debug("Adding protocol version header: Mcp-Protocol-Version: #{@protocol_version}") end end # Add Last-Event-ID header for resumability (if available) return unless @last_event_id req.headers['Last-Event-ID'] = @last_event_id @logger.debug("Adding Last-Event-ID header: #{@last_event_id}") end |
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters
198 199 200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/mcp_client/server_streamable_http.rb', line 198 def call_tool(tool_name, parameters) rpc_request('tools/call', { name: tool_name, arguments: parameters.except(:_meta), **parameters.slice(:_meta) }) rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError # Re-raise connection/transport errors directly to match test expectations raise rescue StandardError => e # For all other errors, wrap in ToolCallError raise MCPClient::Errors::ToolCallError, "Error calling tool '#{tool_name}': #{e.}" end |
#call_tool_streaming(tool_name, parameters) ⇒ Enumerator
Stream tool call (default implementation returns single-value stream)
216 217 218 219 220 |
# File 'lib/mcp_client/server_streamable_http.rb', line 216 def call_tool_streaming(tool_name, parameters) Enumerator.new do |yielder| yielder << call_tool(tool_name, parameters) end end |
#cleanup ⇒ Object
Clean up the server connection Properly closes HTTP connections, stops threads, and clears cached state
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 |
# File 'lib/mcp_client/server_streamable_http.rb', line 451 def cleanup @mutex.synchronize do return unless @connection_established || @initialized @logger.info('Cleaning up Streamable HTTP connection') # Mark connection as closed to stop reconnection attempts @connection_established = false @initialized = false # Attempt to terminate session before cleanup begin terminate_session if @session_id rescue StandardError => e @logger.warn("Failed to terminate session: #{e.}") end # Stop events thread gracefully if @events_thread&.alive? @logger.debug('Stopping events thread...') @events_thread.kill @events_thread.join(THREAD_JOIN_TIMEOUT) end @events_thread = nil # Clear connections and state @http_conn = nil @events_connection = nil @session_id = nil @last_event_id = nil # Clear cached data @tools = nil @tools_data = nil @prompts = nil @prompts_data = nil @resources = nil @resources_data = nil @buffer = '' @logger.info('Cleanup completed') end end |
#complete(ref:, argument:, context: nil) ⇒ Hash
Request completion suggestions from the server (MCP 2025-06-18)
228 229 230 231 232 233 234 235 236 237 |
# File 'lib/mcp_client/server_streamable_http.rb', line 228 def complete(ref:, argument:, context: nil) params = { ref: ref, argument: argument } params[:context] = context if context result = rpc_request('completion/complete', params) result['completion'] || { 'values' => [] } rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError raise rescue StandardError => e raise MCPClient::Errors::ServerError, "Error requesting completion: #{e.}" end |
#connect ⇒ Boolean
Connect to the MCP server over Streamable HTTP
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/mcp_client/server_streamable_http.rb', line 128 def connect return true if @mutex.synchronize { @connection_established } begin @mutex.synchronize do @connection_established = false @initialized = false end # Test connectivity with a simple HTTP request test_connection # Perform MCP initialization handshake perform_initialize # Start long-lived GET connection for server events start_events_connection @mutex.synchronize do @connection_established = true @initialized = true end true rescue MCPClient::Errors::ConnectionError => e cleanup raise e rescue StandardError => e cleanup raise MCPClient::Errors::ConnectionError, "Failed to connect to MCP server at #{@base_url}: #{e.}" end end |
#get_prompt(prompt_name, parameters) ⇒ Object
Get a prompt with the given parameters
284 285 286 287 288 289 290 291 292 293 294 295 296 |
# File 'lib/mcp_client/server_streamable_http.rb', line 284 def get_prompt(prompt_name, parameters) rpc_request('prompts/get', { name: prompt_name, arguments: parameters.except(:_meta), **parameters.slice(:_meta) }) rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError # Re-raise connection/transport errors directly raise rescue StandardError => e # For all other errors, wrap in PromptGetError raise MCPClient::Errors::PromptGetError, "Error getting prompt '#{prompt_name}': #{e.}" end |
#handle_successful_response(response, request) ⇒ Object
Override handle_successful_response to capture session ID
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/mcp_client/server_streamable_http.rb', line 420 def handle_successful_response(response, request) super # Capture session ID from initialize response with validation return unless request['method'] == 'initialize' && response.success? session_id = response.headers['mcp-session-id'] || response.headers['Mcp-Session-Id'] if session_id if valid_session_id?(session_id) @session_id = session_id @logger.debug("Captured session ID: #{@session_id}") else @logger.warn("Invalid session ID format received: #{session_id.inspect}") end else @logger.warn('No session ID found in initialize response headers') end end |
#list_prompts ⇒ Array<MCPClient::Prompt>
List all prompts available from the MCP server
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
# File 'lib/mcp_client/server_streamable_http.rb', line 255 def list_prompts @mutex.synchronize do return @prompts if @prompts end begin ensure_connected prompts_data = request_prompts_list @mutex.synchronize do @prompts = prompts_data.map do |prompt_data| MCPClient::Prompt.from_json(prompt_data, server: self) end end @mutex.synchronize { @prompts } rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError # Re-raise these errors directly raise rescue StandardError => e raise MCPClient::Errors::PromptGetError, "Error listing prompts: #{e.}" end end |
#list_resource_templates(cursor: nil) ⇒ Hash
List all resource templates available from the MCP server
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
# File 'lib/mcp_client/server_streamable_http.rb', line 353 def list_resource_templates(cursor: nil) params = {} params['cursor'] = cursor if cursor result = rpc_request('resources/templates/list', params) templates = (result['resourceTemplates'] || []).map do |template_data| MCPClient::ResourceTemplate.from_json(template_data, server: self) end { 'resourceTemplates' => templates, 'nextCursor' => result['nextCursor'] } rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError raise 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
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# File 'lib/mcp_client/server_streamable_http.rb', line 302 def list_resources(cursor: nil) @mutex.synchronize do return @resources_result if @resources_result && !cursor end begin ensure_connected params = {} params['cursor'] = cursor if cursor result = rpc_request('resources/list', params) resources = (result['resources'] || []).map do |resource_data| MCPClient::Resource.from_json(resource_data, server: self) end resources_result = { 'resources' => resources, 'nextCursor' => result['nextCursor'] } @mutex.synchronize do @resources_result = resources_result unless cursor end resources_result rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError # Re-raise these errors directly raise rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error listing resources: #{e.}" end end |
#list_tools ⇒ Array<MCPClient::Tool>
List all tools available from the MCP server
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
# File 'lib/mcp_client/server_streamable_http.rb', line 166 def list_tools @mutex.synchronize do return @tools if @tools end begin ensure_connected tools_data = request_tools_list @mutex.synchronize do @tools = tools_data.map do |tool_data| MCPClient::Tool.from_json(tool_data, server: self) end end @mutex.synchronize { @tools } rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError # Re-raise these errors directly raise rescue StandardError => e raise MCPClient::Errors::ToolCallError, "Error listing tools: #{e.}" end end |
#log_level=(level) ⇒ Hash
Set the logging level on the server (MCP 2025-06-18)
244 245 246 247 248 249 250 |
# File 'lib/mcp_client/server_streamable_http.rb', line 244 def log_level=(level) rpc_request('logging/setLevel', { level: level }) rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError 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)
498 499 500 |
# File 'lib/mcp_client/server_streamable_http.rb', line 498 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)
505 506 507 |
# File 'lib/mcp_client/server_streamable_http.rb', line 505 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)
512 513 514 |
# File 'lib/mcp_client/server_streamable_http.rb', line 512 def on_sampling_request(&block) @sampling_request_callback = block end |
#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>
Read a resource by its URI
337 338 339 340 341 342 343 344 345 346 347 |
# File 'lib/mcp_client/server_streamable_http.rb', line 337 def read_resource(uri) result = rpc_request('resources/read', { uri: uri }) contents = result['contents'] || [] contents.map { |content| MCPClient::ResourceContent.from_json(content) } rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError # Re-raise connection/transport errors directly raise rescue StandardError => e # For all other errors, wrap in ResourceReadError raise MCPClient::Errors::ResourceReadError, "Error reading resource '#{uri}': #{e.}" end |
#subscribe_resource(uri) ⇒ Boolean
Subscribe to resource updates
373 374 375 376 377 378 379 380 |
# File 'lib/mcp_client/server_streamable_http.rb', line 373 def subscribe_resource(uri) rpc_request('resources/subscribe', { uri: uri }) true rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError raise rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error subscribing to resource '#{uri}': #{e.}" end |
#terminate_session ⇒ Boolean
Terminate the current session (if any)
441 442 443 444 445 446 447 |
# File 'lib/mcp_client/server_streamable_http.rb', line 441 def terminate_session @mutex.synchronize do return true unless @session_id super end end |
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates
386 387 388 389 390 391 392 393 |
# File 'lib/mcp_client/server_streamable_http.rb', line 386 def unsubscribe_resource(uri) rpc_request('resources/unsubscribe', { uri: uri }) true rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError raise rescue StandardError => e raise MCPClient::Errors::ResourceReadError, "Error unsubscribing from resource '#{uri}': #{e.}" end |