Class: MCPClient::ServerStreamableHTTP

Inherits:
ServerBase
  • Object
show all
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
MIN_RESUMPTION_RECONNECT_DELAY =

Floor for the delay between resumption GETs. SEP-1699's polling pattern wants fast reconnects, so this is far smaller than the events-stream floor — it only prevents a peer-supplied "retry: 0" from turning the deadline window into a back-to-back request loop.

0.01
MAX_EVENT_ID_LENGTH =

Maximum length of a server-supplied SSE event id retained as the resumption cursor. The id is echoed in the Last-Event-ID header of subsequent requests, so an unbounded value means unbounded retained memory and oversized outbound headers.

1024
EVENT_ID_PATTERN =

Characters allowed in a retained event id: printable ASCII, since the value becomes an HTTP header value. Notably excludes CR/LF. The range starts at 0x20 because a space is legal inside a field value, and rejecting ids like "cursor 42" would silently strand resumption on a stale cursor.

/\A[\x20-\x7E]+\z/
MAX_CONCURRENT_RESPONSE_POSTS =

Ceiling on concurrent threads POSTing server-initiated responses (pongs, roots/sampling/elicitation replies, error responses). Each server request on the events stream costs one blocking HTTP POST in its own thread; without a bound, a peer flooding requests could accumulate threads and connections until the host is exhausted. Responses beyond the budget are dropped, with saturation logged at most once per SATURATION_LOG_INTERVAL seconds.

8
SATURATION_LOG_INTERVAL =

Minimum gap between "response budget saturated" warnings

5
MIN_EVENTS_RECONNECT_DELAY =

Floor for server-supplied retry directives on the long-lived events stream. The directive is peer-controlled: honoring "retry: 0" literally would let a hostile server that closes every stream drive a tight reconnect loop (sustained CPU/TLS/connection churn). Waiting longer than the directive stays SEP-1699 compliant — the retry field is a lower bound on the reconnect delay, not an exact schedule.

0.1
MAX_SSE_BUFFER_BYTES =

Maximum bytes an SSE parse buffer (events stream or resumption GET) may hold while waiting for an event terminator. The stream is peer-controlled: without a cap, a hostile server could withhold the blank-line delimiter forever and grow the buffer until the host runs out of memory. Generous enough for any legitimate JSON-RPC event.

32 * 1024 * 1024

Constants included from JsonRpcTransport

JsonRpcTransport::DECOMPRESS_CHUNK_BYTES, JsonRpcTransport::MAX_DECOMPRESSED_BODY_BYTES

Constants included from HttpTransportBase

HttpTransportBase::AUTH_PARAM, HttpTransportBase::AUTH_PARAMS_RUN

Constants included from JsonRpcCommon

JsonRpcCommon::NON_IDEMPOTENT_METHODS

Constants inherited from ServerBase

MCPClient::ServerBase::MAX_LIST_PAGES, MCPClient::ServerBase::RELATED_TASK_META_KEY

Instance Attribute Summary collapse

Attributes inherited from ServerBase

#instructions, #name

Instance Method Summary collapse

Methods included from HttpTransportBase

#resend_after_session_restart, #rpc_notify, #rpc_request, #send_cancellation_notification, #valid_server_url?, #valid_session_id?

Methods included from JsonRpcCommon

#build_jsonrpc_notification, #build_jsonrpc_request, #build_named_request_params, #cancellable_request?, #client_capabilities, #client_info_payload, #declare_sampling_tools, #describe_body_size, #describe_jsonrpc_message, #describe_parse_error, #initialization_params, #ping, #process_jsonrpc_response, #registered_callback?, #sampling_tools_supported?, #split_request_meta, #validate_protocol_version!, #with_retry

Methods inherited from ServerBase

#capability?, #client_info=, #merge_related_task_meta, #on_notification, #ping, #require_capability!, #rpc_notify, #rpc_request

Constructor Details

#initialize(base_url:, **options) ⇒ ServerStreamableHTTP

Returns a new instance of ServerStreamableHTTP.

Parameters:

  • base_url (String)

    The base URL of the MCP server

  • options (Hash)

    Server configuration options (same as ServerHTTP)

Raises:

  • (ArgumentError)


100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/mcp_client/server_streamable_http.rb', line 100

def initialize(base_url:, **options)
  opts = default_options.merge(options)
  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]
  @max_decompressed_body_bytes = validate_decompression_limit(opts[:max_decompressed_body_bytes])
  @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
  @sse_retry_ms = nil
  @pending_stream_responses = {}
  @response_post_count = 0
  # Saturation bookkeeping for the response-POST budget
  @dropped_response_posts = 0
  @last_saturation_log_at = nil
  @oauth_provider = opts[:oauth_provider]

  # SSE events connection state
  @events_connection = nil
  @events_thread = nil
  @buffer = +'' # Buffer for partial SSE event data
  # How much of @buffer has already been searched for an event terminator
  @buffer_scanned = 0
  @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_urlString (readonly)

Returns The base URL of the MCP server.

Returns:

  • (String)

    The base URL of the MCP server



88
89
90
# File 'lib/mcp_client/server_streamable_http.rb', line 88

def base_url
  @base_url
end

#capabilitiesHash? (readonly)

Server capabilities from initialize response

Returns:

  • (Hash, nil)

    Server capabilities



96
97
98
# File 'lib/mcp_client/server_streamable_http.rb', line 96

def capabilities
  @capabilities
end

#endpointString (readonly)

Returns The JSON-RPC endpoint path.

Returns:

  • (String)

    The JSON-RPC endpoint path



88
# File 'lib/mcp_client/server_streamable_http.rb', line 88

attr_reader :base_url, :endpoint, :tools

#server_infoHash? (readonly)

Server information from initialize response

Returns:

  • (Hash, nil)

    Server information



92
93
94
# File 'lib/mcp_client/server_streamable_http.rb', line 92

def server_info
  @server_info
end

#toolsObject (readonly)

Returns the value of attribute tools.



88
# File 'lib/mcp_client/server_streamable_http.rb', line 88

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



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# File 'lib/mcp_client/server_streamable_http.rb', line 455

def apply_request_headers(req, request)
  super

  # Add session and protocol version headers for non-initialize requests
  return unless request['method'] != 'initialize'

  if @session_id
    req.headers['Mcp-Session-Id'] = @session_id
    @logger.debug("Adding session header: Mcp-Session-Id: #{@session_id}")
  end

  return unless @protocol_version

  req.headers['Mcp-Protocol-Version'] = @protocol_version
  @logger.debug("Adding protocol version header: Mcp-Protocol-Version: #{@protocol_version}")

  # NOTE: Last-Event-ID is deliberately NOT sent on POSTs — per SEP-1699,
  # resumption is always via HTTP GET with Last-Event-ID.
end

#call_tool(tool_name, parameters) ⇒ Object

Call a tool with the given parameters

Parameters:

  • tool_name (String)

    the name of the tool to call

  • parameters (Hash)

    the parameters to pass to the tool

Returns:

  • (Object)

    the result of the tool invocation (with string keys for backward compatibility)

Raises:



253
254
255
256
257
258
259
260
261
# File 'lib/mcp_client/server_streamable_http.rb', line 253

def call_tool(tool_name, parameters)
  rpc_request('tools/call', build_named_request_params(tool_name, 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 (default implementation returns single-value stream)

Parameters:

  • tool_name (String)

    the name of the tool to call

  • parameters (Hash)

    the parameters to pass to the tool

Returns:

  • (Enumerator)

    stream of results



267
268
269
270
271
# File 'lib/mcp_client/server_streamable_http.rb', line 267

def call_tool_streaming(tool_name, parameters)
  Enumerator.new do |yielder|
    yielder << call_tool(tool_name, parameters)
  end
end

#cleanupObject

Clean up the server connection Properly closes HTTP connections, stops threads, and clears cached state



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
# File 'lib/mcp_client/server_streamable_http.rb', line 507

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.message}")
    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
    @sse_retry_ms = nil
    @pending_stream_responses.each_value(&:close)
    @pending_stream_responses.clear

    # Clear cached data
    @tools = nil
    @tools_data = nil
    @prompts = nil
    @prompts_data = nil
    @resources = nil
    @resources_data = nil
    @buffer = +''
    @buffer_scanned = 0

    @logger.info('Cleanup completed')
  end
end

#complete(ref:, argument:, context: nil) ⇒ Hash

Request completion suggestions from the server (MCP 2025-06-18)

Parameters:

  • ref (Hash)

    reference object (e.g., { 'type' => 'ref/prompt', 'name' => 'prompt_name' })

  • argument (Hash)

    the argument being completed (e.g., { 'name' => 'arg_name', 'value' => 'partial' })

  • context (Hash, nil) (defaults to: nil)

    optional context for the completion (MCP 2025-11-25)

Returns:

  • (Hash)

    completion result with 'values', optional 'total', and 'hasMore' fields

Raises:



279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/mcp_client/server_streamable_http.rb', line 279

def complete(ref:, argument:, context: nil)
  ensure_connected
  require_capability!('completions', method: 'completion/complete')
  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,
       MCPClient::Errors::CapabilityError
  raise
rescue StandardError => e
  raise MCPClient::Errors::ServerError, "Error requesting completion: #{e.message}"
end

#connectBoolean

Connect to the MCP server over Streamable HTTP

Returns:

  • (Boolean)

    true if connection was successful

Raises:



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/mcp_client/server_streamable_http.rb', line 183

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.message}"
  end
end

#get_prompt(prompt_name, parameters) ⇒ Object

Get a prompt with the given parameters

Parameters:

  • prompt_name (String)

    the name of the prompt to get

  • parameters (Hash)

    the parameters to pass to the prompt

Returns:

  • (Object)

    the result of the prompt (with string keys for backward compatibility)

Raises:



341
342
343
344
345
346
347
348
349
# File 'lib/mcp_client/server_streamable_http.rb', line 341

def get_prompt(prompt_name, parameters)
  rpc_request('prompts/get', build_named_request_params(prompt_name, parameters))
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.message}"
end

#handle_successful_response(response, request) ⇒ Object

Override handle_successful_response to capture session ID



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 476

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_promptsArray<MCPClient::Prompt>

List all prompts available from the MCP server

Returns:

Raises:



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/mcp_client/server_streamable_http.rb', line 312

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.message}"
  end
end

#list_resource_templates(cursor: nil) ⇒ Hash

List all resource templates available from the MCP server

Parameters:

  • cursor (String, nil) (defaults to: nil)

    optional cursor for pagination

Returns:

  • (Hash)

    result containing resourceTemplates array and optional nextCursor

Raises:



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/mcp_client/server_streamable_http.rb', line 406

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.message}"
end

#list_resources(cursor: nil) ⇒ Hash

List all resources available from the MCP server

Parameters:

  • cursor (String, nil) (defaults to: nil)

    optional cursor for pagination

Returns:

  • (Hash)

    result containing resources array and optional nextCursor

Raises:



355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/mcp_client/server_streamable_http.rb', line 355

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.message}"
  end
end

#list_toolsArray<MCPClient::Tool>

List all tools available from the MCP server

Returns:

Raises:



221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/mcp_client/server_streamable_http.rb', line 221

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.message}"
  end
end

#log_level=(level) ⇒ Hash

Set the logging level on the server (MCP 2025-06-18)

Parameters:

  • level (String)

    the log level ('debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency')

Returns:

  • (Hash)

    empty result on success

Raises:



298
299
300
301
302
303
304
305
306
307
# File 'lib/mcp_client/server_streamable_http.rb', line 298

def log_level=(level)
  ensure_connected
  require_capability!('logging', method: 'logging/setLevel')
  rpc_request('logging/setLevel', { level: level })
rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError,
       MCPClient::Errors::CapabilityError
  raise
rescue StandardError => e
  raise MCPClient::Errors::ServerError, "Error setting log level: #{e.message}"
end

#on_elicitation_request(&block) ⇒ void

This method returns an undefined value.

Register a callback for elicitation requests (MCP 2025-06-18)

Parameters:

  • block (Proc)

    callback that receives (request_id, params) and returns response hash



558
559
560
# File 'lib/mcp_client/server_streamable_http.rb', line 558

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)

Parameters:

  • block (Proc)

    callback that receives (request_id, params) and returns response hash



565
566
567
# File 'lib/mcp_client/server_streamable_http.rb', line 565

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)

Parameters:

  • block (Proc)

    callback that receives (request_id, params) and returns response hash



572
573
574
# File 'lib/mcp_client/server_streamable_http.rb', line 572

def on_sampling_request(&block)
  @sampling_request_callback = block
end

#read_resource(uri) ⇒ Array<MCPClient::ResourceContent>

Read a resource by its URI

Parameters:

  • uri (String)

    the URI of the resource to read

Returns:

Raises:



390
391
392
393
394
395
396
397
398
399
400
# File 'lib/mcp_client/server_streamable_http.rb', line 390

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.message}"
end

#subscribe_resource(uri) ⇒ Boolean

Subscribe to resource updates

Parameters:

  • uri (String)

    the URI of the resource to subscribe to

Returns:

  • (Boolean)

    true if subscription successful

Raises:



426
427
428
429
430
431
432
433
434
435
436
# File 'lib/mcp_client/server_streamable_http.rb', line 426

def subscribe_resource(uri)
  ensure_connected
  require_capability!('resources', 'subscribe', method: 'resources/subscribe')
  rpc_request('resources/subscribe', { uri: uri })
  true
rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError,
       MCPClient::Errors::CapabilityError
  raise
rescue StandardError => e
  raise MCPClient::Errors::ResourceReadError, "Error subscribing to resource '#{uri}': #{e.message}"
end

#terminate_sessionBoolean

Terminate the current session (if any)

Returns:

  • (Boolean)

    true if termination was successful or no session exists



497
498
499
500
501
502
503
# File 'lib/mcp_client/server_streamable_http.rb', line 497

def terminate_session
  @mutex.synchronize do
    return true unless @session_id

    super
  end
end

#unsubscribe_resource(uri) ⇒ Boolean

Unsubscribe from resource updates

Parameters:

  • uri (String)

    the URI of the resource to unsubscribe from

Returns:

  • (Boolean)

    true if unsubscription successful

Raises:



442
443
444
445
446
447
448
449
450
451
452
# File 'lib/mcp_client/server_streamable_http.rb', line 442

def unsubscribe_resource(uri)
  ensure_connected
  require_capability!('resources', 'subscribe', method: 'resources/unsubscribe')
  rpc_request('resources/unsubscribe', { uri: uri })
  true
rescue MCPClient::Errors::ConnectionError, MCPClient::Errors::TransportError, MCPClient::Errors::ServerError,
       MCPClient::Errors::CapabilityError
  raise
rescue StandardError => e
  raise MCPClient::Errors::ResourceReadError, "Error unsubscribing from resource '#{uri}': #{e.message}"
end