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 This transport uses HTTP POST requests but expects Server-Sent Event formatted responses It’s designed for servers that support streaming responses over HTTP

Defined Under Namespace

Modules: JsonRpcTransport

Constant Summary collapse

DEFAULT_READ_TIMEOUT =

Default values for connection settings

30
DEFAULT_MAX_RETRIES =
3

Instance Attribute Summary collapse

Attributes inherited from ServerBase

#name

Instance Method Summary collapse

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.

Parameters:

  • The base URL of the MCP server

  • Server configuration options (same as ServerHTTP)

Raises:



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
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
# File 'lib/mcp_client/server_streamable_http.rb', line 41

def initialize(base_url:, **options)
  opts = default_options.merge(options)
  super(name: opts[:name])
  @logger = opts[:logger] || Logger.new($stdout, level: Logger::WARN)
  @logger.progname = self.class.name
  @logger.formatter = proc { |severity, _datetime, progname, msg| "#{severity} [#{progname}] #{msg}\n" }

  @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, deflate',
                                    'User-Agent' => "ruby-mcp-client/#{MCPClient::VERSION}",
                                    'Cache-Control' => 'no-cache'
                                  })

  @read_timeout = opts[:read_timeout]
  @tools = nil
  @tools_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]
end

Instance Attribute Details

#base_urlString (readonly)

Returns The base URL of the MCP server.

Returns:

  • The base URL of the MCP server



29
30
31
# File 'lib/mcp_client/server_streamable_http.rb', line 29

def base_url
  @base_url
end

#capabilitiesHash? (readonly)

Server capabilities from initialize response

Returns:

  • Server capabilities



37
38
39
# File 'lib/mcp_client/server_streamable_http.rb', line 37

def capabilities
  @capabilities
end

#endpointString (readonly)

Returns The JSON-RPC endpoint path.

Returns:

  • The JSON-RPC endpoint path



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

attr_reader :base_url, :endpoint, :tools

#server_infoHash? (readonly)

Server information from initialize response

Returns:

  • Server information



33
34
35
# File 'lib/mcp_client/server_streamable_http.rb', line 33

def server_info
  @server_info
end

#toolsObject (readonly)

Returns the value of attribute tools.



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

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



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/mcp_client/server_streamable_http.rb', line 195

def apply_request_headers(req, request)
  super

  # Add session header if we have one (for non-initialize requests)
  if @session_id && request['method'] != 'initialize'
    req.headers['Mcp-Session-Id'] = @session_id
    @logger.debug("Adding session header: Mcp-Session-Id: #{@session_id}")
  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

Parameters:

  • the name of the tool to call

  • the parameters to pass to the tool

Returns:

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

Raises:

  • if server returns an error

  • if response isn’t valid JSON

  • for other errors during tool execution

  • if server is disconnected



171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/mcp_client/server_streamable_http.rb', line 171

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 (default implementation returns single-value stream)

Parameters:

  • the name of the tool to call

  • the parameters to pass to the tool

Returns:

  • stream of results



188
189
190
191
192
# File 'lib/mcp_client/server_streamable_http.rb', line 188

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 and clears cached state



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/mcp_client/server_streamable_http.rb', line 243

def cleanup
  @mutex.synchronize do
    # Attempt to terminate session before cleanup
    terminate_session if @session_id

    @connection_established = false
    @initialized = false

    @logger.debug('Cleaning up Streamable HTTP connection')

    # Close HTTP connection if it exists
    @http_conn = nil
    @session_id = nil

    @tools = nil
    @tools_data = nil
  end
end

#connectBoolean

Connect to the MCP server over Streamable HTTP

Returns:

  • true if connection was successful

Raises:

  • if connection fails



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
# File 'lib/mcp_client/server_streamable_http.rb', line 104

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

    @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

#handle_successful_response(response, request) ⇒ Object

Override handle_successful_response to capture session ID



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/mcp_client/server_streamable_http.rb', line 212

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_toolsArray<MCPClient::Tool>

List all tools available from the MCP server

Returns:

  • list of available tools

Raises:

  • if server returns an error

  • if response isn’t valid JSON

  • for other errors during tool listing



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/mcp_client/server_streamable_http.rb', line 139

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

#terminate_sessionBoolean

Terminate the current session (if any)

Returns:

  • true if termination was successful or no session exists



233
234
235
236
237
238
239
# File 'lib/mcp_client/server_streamable_http.rb', line 233

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

    super
  end
end