Class: MCPClient::ServerSSE
- Inherits:
-
ServerBase
- Object
- ServerBase
- MCPClient::ServerSSE
- Includes:
- JsonRpcTransport, ReconnectMonitor, SseParser
- Defined in:
- lib/mcp_client/server_sse.rb,
lib/mcp_client/server_sse/sse_parser.rb,
lib/mcp_client/server_sse/reconnect_monitor.rb,
lib/mcp_client/server_sse/json_rpc_transport.rb
Overview
Implementation of MCP server that communicates via Server-Sent Events (SSE) Useful for communicating with remote MCP servers over HTTP
Defined Under Namespace
Modules: JsonRpcTransport, ReconnectMonitor, SseParser
Constant Summary collapse
- CLOSE_AFTER_PING_RATIO =
Ratio of close_after timeout to ping interval
2.5
- DEFAULT_MAX_PING_FAILURES =
Default values for connection monitoring
3
- DEFAULT_MAX_RECONNECT_ATTEMPTS =
5
- BASE_RECONNECT_DELAY =
Reconnection backoff constants
0.5
- MAX_RECONNECT_DELAY =
30
- JITTER_FACTOR =
0.25
Instance Attribute Summary collapse
-
#base_url ⇒ String
readonly
The base URL of the MCP server.
-
#capabilities ⇒ Hash?
readonly
Server capabilities from initialize response.
-
#prompts ⇒ Array<MCPClient::Prompt>?
readonly
List of available prompts (nil if not fetched yet).
-
#resources ⇒ Object
readonly
Returns the value of attribute resources.
-
#server_info ⇒ Hash?
readonly
Server information from initialize response.
-
#tools ⇒ Array<MCPClient::Tool>?
readonly
List of available tools (nil if not fetched yet).
Attributes inherited from ServerBase
Instance Method Summary collapse
-
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters Call a tool with the given parameters.
-
#call_tool_streaming(tool_name, parameters) ⇒ Enumerator
Stream tool call fallback for SSE transport (yields single result).
-
#cleanup ⇒ Object
Clean up the server connection Properly closes HTTP connections and clears cached state.
-
#connect ⇒ Boolean
Connect to the MCP server over HTTP/HTTPS with SSE.
-
#get_prompt(prompt_name, parameters) ⇒ Object
Get a prompt with the given parameters.
-
#initialize(base_url:, headers: {}, read_timeout: 30, ping: 10, retries: 0, retry_backoff: 1, name: nil, logger: nil) ⇒ ServerSSE
constructor
A new instance of ServerSSE.
-
#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.
-
#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>
Read a resource by its URI.
-
#subscribe_resource(uri) ⇒ Boolean
Subscribe to resource updates.
-
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates.
Methods included from ReconnectMonitor
#activity_monitor_loop, #attempt_ping, #attempt_reconnection, #connection_active?, #handle_ping_failure, #handle_sse_auth_error, #record_activity, #reset_connection_state, #setup_sse_connection, #start_activity_monitor, #wait_for_connection
Methods included from JsonRpcTransport
Methods included from JsonRpcCommon
#build_jsonrpc_notification, #build_jsonrpc_request, #initialization_params, #ping, #process_jsonrpc_response, #with_retry
Methods included from SseParser
#handle_endpoint_event, #handle_message_event, #parse_and_handle_sse_event, #parse_sse_event, #process_error_in_message, #process_notification?, #process_response?
Methods inherited from ServerBase
#on_notification, #ping, #rpc_notify, #rpc_request
Constructor Details
#initialize(base_url:, headers: {}, read_timeout: 30, ping: 10, retries: 0, retry_backoff: 1, name: nil, logger: nil) ⇒ ServerSSE
Returns a new instance of ServerSSE.
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 |
# File 'lib/mcp_client/server_sse.rb', line 63 def initialize(base_url:, headers: {}, read_timeout: 30, ping: 10, retries: 0, retry_backoff: 1, name: nil, logger: nil) super(name: name) initialize_logger(logger) @max_retries = retries @retry_backoff = retry_backoff # Normalize base_url: preserve trailing slash if explicitly provided for SSE endpoints @base_url = base_url @headers = headers.merge({ 'Accept' => 'text/event-stream', 'Cache-Control' => 'no-cache', 'Connection' => 'keep-alive' }) # HTTP client is managed via Faraday @tools = nil @read_timeout = read_timeout @ping_interval = ping # Set close_after to a multiple of the ping interval @close_after = (ping * CLOSE_AFTER_PING_RATIO).to_i # SSE-provided JSON-RPC endpoint path for POST requests @rpc_endpoint = nil @tools_data = nil @request_id = 0 @sse_results = {} @mutex = Monitor.new @buffer = '' @sse_connected = false @connection_established = false @connection_cv = @mutex.new_cond @initialized = false @auth_error = nil # Whether to use SSE transport; may disable if handshake fails @use_sse = true # Time of last activity @last_activity_time = Time.now @activity_timer_thread = nil end |
Instance Attribute Details
#base_url ⇒ String (readonly)
Returns The base URL of the MCP server.
45 46 47 |
# File 'lib/mcp_client/server_sse.rb', line 45 def base_url @base_url end |
#capabilities ⇒ Hash? (readonly)
Server capabilities from initialize response
53 54 55 |
# File 'lib/mcp_client/server_sse.rb', line 53 def capabilities @capabilities end |
#prompts ⇒ Array<MCPClient::Prompt>? (readonly)
Returns List of available prompts (nil if not fetched yet).
45 |
# File 'lib/mcp_client/server_sse.rb', line 45 attr_reader :base_url, :tools, :prompts, :resources |
#resources ⇒ Object (readonly)
Returns the value of attribute resources.
45 |
# File 'lib/mcp_client/server_sse.rb', line 45 attr_reader :base_url, :tools, :prompts, :resources |
#server_info ⇒ Hash? (readonly)
Server information from initialize response
49 50 51 |
# File 'lib/mcp_client/server_sse.rb', line 49 def server_info @server_info end |
#tools ⇒ Array<MCPClient::Tool>? (readonly)
Returns List of available tools (nil if not fetched yet).
45 |
# File 'lib/mcp_client/server_sse.rb', line 45 attr_reader :base_url, :tools, :prompts, :resources |
Instance Method Details
#call_tool(tool_name, parameters) ⇒ Object
Call a tool with the given parameters Call a tool with the given parameters
312 313 314 315 316 317 318 319 320 321 322 323 |
# File 'lib/mcp_client/server_sse.rb', line 312 def call_tool(tool_name, parameters) rpc_request('tools/call', { name: tool_name, arguments: parameters }) 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.message}" end |
#call_tool_streaming(tool_name, parameters) ⇒ Enumerator
Stream tool call fallback for SSE transport (yields single result)
107 108 109 110 111 |
# File 'lib/mcp_client/server_sse.rb', line 107 def call_tool_streaming(tool_name, parameters) Enumerator.new do |yielder| yielder << call_tool(tool_name, parameters) end end |
#cleanup ⇒ Object
This method preserves ping failure and reconnection metrics between reconnection attempts, allowing the client to track failures across multiple connection attempts. This is essential for proper reconnection logic and exponential backoff.
Clean up the server connection Properly closes HTTP connections and clears cached state
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'lib/mcp_client/server_sse.rb', line 365 def cleanup @mutex.synchronize do # Set flags first before killing threads to prevent race conditions # where threads might check flags after they're set but before they're killed @connection_established = false @sse_connected = false @initialized = false # Reset initialization state for reconnection # Log cleanup for debugging @logger.debug('Cleaning up SSE connection') # Store threads locally to avoid race conditions sse_thread = @sse_thread activity_thread = @activity_timer_thread # Clear thread references first @sse_thread = nil @activity_timer_thread = nil # Kill threads outside the critical section begin sse_thread&.kill rescue StandardError => e @logger.debug("Error killing SSE thread: #{e.message}") end begin activity_thread&.kill rescue StandardError => e @logger.debug("Error killing activity thread: #{e.message}") end if @http_client @http_client.finish if @http_client.started? @http_client = nil end # Close Faraday connections if they exist @rpc_conn = nil @sse_conn = nil @tools = nil # Don't clear auth error as we need it for reporting the correct error # Don't reset @consecutive_ping_failures or @reconnect_attempts as they're tracked across reconnections end end |
#connect ⇒ Boolean
Connect to the MCP server over HTTP/HTTPS with SSE
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'lib/mcp_client/server_sse.rb', line 328 def connect return true if @mutex.synchronize { @connection_established } # Check for pre-existing auth error (needed for tests) pre_existing_auth_error = @mutex.synchronize { @auth_error } begin # Don't reset auth error if it's pre-existing @mutex.synchronize { @auth_error = nil } unless pre_existing_auth_error start_sse_thread effective_timeout = [@read_timeout || 30, 30].min wait_for_connection(timeout: effective_timeout) start_activity_monitor true rescue MCPClient::Errors::ConnectionError => e cleanup # Simply pass through any ConnectionError without wrapping it again # This prevents duplicate error messages in the stack raise e rescue StandardError => e cleanup # Check for stored auth error first as it's more specific auth_error = @mutex.synchronize { @auth_error } raise MCPClient::Errors::ConnectionError, auth_error if auth_error raise MCPClient::Errors::ConnectionError, "Failed to connect to MCP server at #{@base_url}: #{e.message}" end end |
#get_prompt(prompt_name, parameters) ⇒ Object
Get a prompt with the given parameters
150 151 152 153 154 155 156 157 158 159 160 161 |
# File 'lib/mcp_client/server_sse.rb', line 150 def get_prompt(prompt_name, parameters) rpc_request('prompts/get', { name: prompt_name, arguments: parameters }) 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 PromptGetError raise MCPClient::Errors::PromptGetError, "Error get prompt '#{prompt_name}': #{e.message}" end |
#list_prompts ⇒ Array<MCPClient::Prompt>
List all prompts available from the MCP server
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 |
# File 'lib/mcp_client/server_sse.rb', line 118 def list_prompts @mutex.synchronize do return @prompts if @prompts end begin ensure_initialized 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.message}" end end |
#list_resource_templates(cursor: nil) ⇒ Hash
List all resource templates available from the MCP server
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/mcp_client/server_sse.rb', line 224 def list_resource_templates(cursor: nil) ensure_initialized 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.message}" end |
#list_resources(cursor: nil) ⇒ Hash
List all resources available from the MCP server
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 |
# File 'lib/mcp_client/server_sse.rb', line 169 def list_resources(cursor: nil) @mutex.synchronize do return @resources_result if @resources_result && !cursor end begin ensure_initialized 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.message}" end end |
#list_tools ⇒ Array<MCPClient::Tool>
List all tools available from the MCP server
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
# File 'lib/mcp_client/server_sse.rb', line 276 def list_tools @mutex.synchronize do return @tools if @tools end begin ensure_initialized 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.message}" end end |
#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>
Read a resource by its URI
207 208 209 210 211 212 213 214 215 216 217 |
# File 'lib/mcp_client/server_sse.rb', line 207 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 to match test expectations raise rescue StandardError => e # For all other errors, wrap in ResourceReadError raise MCPClient::Errors::ResourceReadError, "Error reading resource '#{uri}': #{e.message}" end |
#subscribe_resource(uri) ⇒ Boolean
Subscribe to resource updates
246 247 248 249 250 251 252 253 254 |
# File 'lib/mcp_client/server_sse.rb', line 246 def subscribe_resource(uri) ensure_initialized 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.message}" end |
#unsubscribe_resource(uri) ⇒ Boolean
Unsubscribe from resource updates
261 262 263 264 265 266 267 268 269 |
# File 'lib/mcp_client/server_sse.rb', line 261 def unsubscribe_resource(uri) ensure_initialized 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.message}" end |