Class: RubyLLM::MCP::Native::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_llm/mcp/native/client.rb

Overview

Native MCP protocol client implementation This is the core protocol implementation that handles all MCP operations It's self-contained and could potentially be extracted as a separate gem

Constant Summary collapse

TOOL_CALL_CANCELLED_MESSAGE =
"Tool call was cancelled by the client"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, transport_type:, transport_config: {}, human_in_the_loop_callback: nil, roots_callback: nil, logging_enabled: false, logging_level: nil, elicitation_enabled: false, elicitation_callback: nil, progress_tracking_enabled: false, sampling_callback: nil, notification_callback: nil, extensions_capabilities: nil, protocol_version: nil, request_timeout: nil) ⇒ Client

rubocop:disable Metrics/ParameterLists



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ruby_llm/mcp/native/client.rb', line 15

def initialize( # rubocop:disable Metrics/ParameterLists
  name:,
  transport_type:,
  transport_config: {},
  human_in_the_loop_callback: nil,
  roots_callback: nil,
  logging_enabled: false,
  logging_level: nil,
  elicitation_enabled: false,
  elicitation_callback: nil,
  progress_tracking_enabled: false,
  sampling_callback: nil,
  notification_callback: nil,
  extensions_capabilities: nil,
  protocol_version: nil,
  request_timeout: nil
)
  @name = name
  @transport_type = transport_type
  @config = transport_config.merge(request_timeout: request_timeout || MCP.config.request_timeout)
  @requested_protocol_version = protocol_version || MCP.config.protocol_version || Native::Protocol.latest_version
  @protocol_version = @requested_protocol_version
  @extensions_capabilities = extensions_capabilities || {}

  # Callbacks
  @human_in_the_loop_callback = human_in_the_loop_callback
  @roots_callback = roots_callback
  @logging_enabled = logging_enabled
  @logging_level = logging_level
  @elicitation_enabled = elicitation_enabled
  @elicitation_callback = elicitation_callback
  @progress_tracking_enabled = progress_tracking_enabled
  @sampling_callback = sampling_callback
  @notification_callback = notification_callback

  @transport = nil
  @capabilities = nil
  @task_registry = Native::TaskRegistry.new

  # Track in-flight server-initiated requests for cancellation
  @in_flight_requests = {}
  @in_flight_mutex = Mutex.new

  # Human-in-the-loop approvals are scoped per client lifecycle.
  @registry_owner_id = "native-client-#{SecureRandom.uuid}"
  @human_in_the_loop_registry = Handlers::HumanInTheLoopRegistry.for_owner(@registry_owner_id)
end

Instance Attribute Details

#capabilitiesObject (readonly)

Returns the value of attribute capabilities.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def capabilities
  @capabilities
end

#configObject (readonly)

Returns the value of attribute config.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def config
  @config
end

#elicitation_callbackObject (readonly)

Returns the value of attribute elicitation_callback.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def elicitation_callback
  @elicitation_callback
end

#human_in_the_loop_registryObject (readonly)

Returns the value of attribute human_in_the_loop_registry.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def human_in_the_loop_registry
  @human_in_the_loop_registry
end

#nameObject (readonly)

Returns the value of attribute name.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def name
  @name
end

#protocol_versionObject (readonly)

Returns the value of attribute protocol_version.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def protocol_version
  @protocol_version
end

#registry_owner_idObject (readonly)

Returns the value of attribute registry_owner_id.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def registry_owner_id
  @registry_owner_id
end

#sampling_callbackObject (readonly)

Returns the value of attribute sampling_callback.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def sampling_callback
  @sampling_callback
end

#task_registryObject (readonly)

Returns the value of attribute task_registry.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def task_registry
  @task_registry
end

#transport_typeObject (readonly)

Returns the value of attribute transport_type.



12
13
14
# File 'lib/ruby_llm/mcp/native/client.rb', line 12

def transport_type
  @transport_type
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


141
142
143
# File 'lib/ruby_llm/mcp/native/client.rb', line 141

def alive?
  !!@transport&.alive?
end

#cancel_in_flight_request(request_id) ⇒ Symbol

Cancel an in-flight server-initiated request

Parameters:

  • request_id (String)

    The ID of the request to cancel

Returns:

  • (Symbol)

    cancellation outcome :cancelled, :already_cancelled, :already_completed, :not_found, :not_cancellable, :failed



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/ruby_llm/mcp/native/client.rb', line 453

def cancel_in_flight_request(request_id)
  operation = nil
  @in_flight_mutex.synchronize do
    operation = @in_flight_requests[request_id.to_s]
  end

  unless operation
    RubyLLM::MCP.logger.debug("Request #{request_id} was not found for cancellation")
    return :not_found
  end

  unless operation.respond_to?(:cancel)
    RubyLLM::MCP.logger.warn("Request #{request_id} cannot be cancelled or was already completed")
    return :not_cancellable
  end

  outcome = normalize_cancellation_outcome(operation.cancel)
  if %i[cancelled already_cancelled already_completed].include?(outcome)
    unregister_in_flight_request(request_id)
  end

  outcome
end

#cancelled_notification(reason:, request_id:) ⇒ Object



336
337
338
339
# File 'lib/ruby_llm/mcp/native/client.rb', line 336

def cancelled_notification(reason:, request_id:)
  body = Native::Messages::Notifications.cancelled(request_id: request_id, reason: reason)
  request(body, wait_for_response: false)
end

#client_capabilitiesObject



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
411
412
413
414
# File 'lib/ruby_llm/mcp/native/client.rb', line 379

def client_capabilities
  capabilities_hash = {}

  if @roots_callback&.call&.any?
    capabilities_hash[:roots] = {
      listChanged: true
    }
  end

  if MCP.config.sampling.enabled?
    sampling_capabilities = {}
    sampling_capabilities[:tools] = {} if MCP.config.sampling.tools
    sampling_capabilities[:context] = {} if MCP.config.sampling.context
    capabilities_hash[:sampling] = sampling_capabilities
  end

  if @elicitation_enabled
    elicitation_capabilities = {}
    elicitation_capabilities[:form] = {} if MCP.config.elicitation.form
    elicitation_capabilities[:url] = {} if MCP.config.elicitation.url
    capabilities_hash[:elicitation] = elicitation_capabilities unless elicitation_capabilities.empty?
  end

  if MCP.config.respond_to?(:tasks) && MCP.config.tasks.enabled?
    capabilities_hash[:tasks] = {
      list: {},
      cancel: {}
    }
  end

  if @extensions_capabilities.any? && Native::Protocol.extensions_supported?(@protocol_version)
    capabilities_hash[:extensions] = @extensions_capabilities
  end

  capabilities_hash
end

#completion_prompt(name:, argument:, value:, context: nil) ⇒ Object



265
266
267
268
269
# File 'lib/ruby_llm/mcp/native/client.rb', line 265

def completion_prompt(name:, argument:, value:, context: nil)
  body = Native::Messages::Requests.completion_prompt(name: name, argument: argument, value: value,
                                                      context: context, tracking_progress: tracking_progress?)
  request(body)
end

#completion_resource(uri:, argument:, value:, context: nil) ⇒ Object



259
260
261
262
263
# File 'lib/ruby_llm/mcp/native/client.rb', line 259

def completion_resource(uri:, argument:, value:, context: nil)
  body = Native::Messages::Requests.completion_resource(uri: uri, argument: argument, value: value,
                                                        context: context, tracking_progress: tracking_progress?)
  request(body)
end

#elicitation_response(id:, elicitation:) ⇒ Object



373
374
375
376
377
# File 'lib/ruby_llm/mcp/native/client.rb', line 373

def elicitation_response(id:, elicitation:)
  body = Native::Messages::Responses.elicitation(id: id, action: elicitation[:action],
                                                 content: elicitation[:content])
  request(body, wait_for_response: false)
end

#error_response(id:, message:, code: Native::JsonRpc::ErrorCodes::SERVER_ERROR, data: nil) ⇒ Object



368
369
370
371
# File 'lib/ruby_llm/mcp/native/client.rb', line 368

def error_response(id:, message:, code: Native::JsonRpc::ErrorCodes::SERVER_ERROR, data: nil)
  body = Native::Messages::Responses.error(id: id, message: message, code: code, data: data)
  request(body, wait_for_response: false)
end

#execute_prompt(name:, arguments:) ⇒ Object



253
254
255
256
257
# File 'lib/ruby_llm/mcp/native/client.rb', line 253

def execute_prompt(name:, arguments:)
  body = Native::Messages::Requests.prompt_call(name: name, arguments: arguments,
                                                tracking_progress: tracking_progress?)
  request(body)
end

#execute_tool(name:, parameters:) ⇒ Object



190
191
192
193
194
195
196
197
198
199
# File 'lib/ruby_llm/mcp/native/client.rb', line 190

def execute_tool(name:, parameters:)
  if @human_in_the_loop_callback
    approved = evaluate_tool_approval(name: name, parameters: parameters)
    return create_cancelled_result unless approved
  end

  body = Native::Messages::Requests.tool_call(name: name, parameters: parameters,
                                              tracking_progress: tracking_progress?)
  request(body)
end

#initialize_notificationObject

Notifications



331
332
333
334
# File 'lib/ruby_llm/mcp/native/client.rb', line 331

def initialize_notification
  body = Native::Messages::Notifications.initialized
  request(body, wait_for_response: false)
end

#initialize_requestObject



170
171
172
173
174
175
176
# File 'lib/ruby_llm/mcp/native/client.rb', line 170

def initialize_request
  body = Native::Messages::Requests.initialize(
    protocol_version: protocol_version,
    capabilities: client_capabilities
  )
  request(body)
end

#pingObject



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/ruby_llm/mcp/native/client.rb', line 145

def ping
  body = Native::Messages::Requests.ping(tracking_progress: tracking_progress?)
  if alive?
    result = request(body)
  else
    transport.start

    result = request(body)
    @transport = nil
  end

  result.value == {}
rescue RubyLLM::MCP::Errors::TimeoutError, RubyLLM::MCP::Errors::TransportError
  false
end

#ping_response(id:) ⇒ Object

Responses



348
349
350
351
# File 'lib/ruby_llm/mcp/native/client.rb', line 348

def ping_response(id:)
  body = Native::Messages::Responses.ping(id: id)
  request(body, wait_for_response: false)
end

#process_notification(result) ⇒ Object



161
162
163
164
# File 'lib/ruby_llm/mcp/native/client.rb', line 161

def process_notification(result)
  notification = result.notification
  @notification_callback&.call(notification)
end

#process_request(result) ⇒ Object



166
167
168
# File 'lib/ruby_llm/mcp/native/client.rb', line 166

def process_request(result)
  Native::ResponseHandler.new(self).execute(result)
end

#process_result(result) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/ruby_llm/mcp/native/client.rb', line 72

def process_result(result)
  if result.notification?
    process_notification(result)
    return nil
  end

  if result.request?
    process_request(result) if alive?
    return nil
  end

  if result.response?
    return result
  end

  nil
end

#prompt_list(cursor: nil) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
# File 'lib/ruby_llm/mcp/native/client.rb', line 241

def prompt_list(cursor: nil)
  body = Native::Messages::Requests.prompt_list(cursor: cursor, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  if result.next_cursor?
    result.value["prompts"] + prompt_list(cursor: result.next_cursor)
  else
    result.value["prompts"]
  end
end

#register_in_flight_request(request_id, cancellable_operation = nil) ⇒ Object

Register a server-initiated request that can be cancelled

Parameters:

  • request_id (String)

    The ID of the request

  • cancellable_operation (CancellableOperation, nil) (defaults to: nil)

    The operation that can be cancelled



435
436
437
438
439
# File 'lib/ruby_llm/mcp/native/client.rb', line 435

def register_in_flight_request(request_id, cancellable_operation = nil)
  @in_flight_mutex.synchronize do
    @in_flight_requests[request_id.to_s] = cancellable_operation
  end
end

#request(body, **options) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/ruby_llm/mcp/native/client.rb', line 63

def request(body, **options)
  transport.request(body, **options)
rescue RubyLLM::MCP::Errors::TimeoutError => e
  if transport&.alive? && !e.request_id.nil?
    cancelled_notification(reason: "Request timed out", request_id: e.request_id)
  end
  raise e
end

#resource_list(cursor: nil) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
# File 'lib/ruby_llm/mcp/native/client.rb', line 201

def resource_list(cursor: nil)
  body = Native::Messages::Requests.resource_list(cursor: cursor, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  if result.next_cursor?
    result.value["resources"] + resource_list(cursor: result.next_cursor)
  else
    result.value["resources"]
  end
end

#resource_read(uri:) ⇒ Object



213
214
215
216
# File 'lib/ruby_llm/mcp/native/client.rb', line 213

def resource_read(uri:)
  body = Native::Messages::Requests.resource_read(uri: uri, tracking_progress: tracking_progress?)
  request(body)
end

#resource_template_list(cursor: nil) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/ruby_llm/mcp/native/client.rb', line 218

def resource_template_list(cursor: nil)
  body = Native::Messages::Requests.resource_template_list(cursor: cursor,
                                                           tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  if result.next_cursor?
    result.value["resourceTemplates"] + resource_template_list(cursor: result.next_cursor)
  else
    result.value["resourceTemplates"]
  end
end

#resources_subscribe(uri:) ⇒ Object



231
232
233
234
# File 'lib/ruby_llm/mcp/native/client.rb', line 231

def resources_subscribe(uri:)
  body = Native::Messages::Requests.resources_subscribe(uri: uri, tracking_progress: tracking_progress?)
  request(body, wait_for_response: false)
end

#resources_unsubscribe(uri:) ⇒ Object



236
237
238
239
# File 'lib/ruby_llm/mcp/native/client.rb', line 236

def resources_unsubscribe(uri:)
  body = Native::Messages::Requests.resources_unsubscribe(uri: uri, tracking_progress: tracking_progress?)
  request(body, wait_for_response: false)
end

#restart!Object



135
136
137
138
139
# File 'lib/ruby_llm/mcp/native/client.rb', line 135

def restart!
  @initialize_response = nil
  stop
  start
end

#result_response(id:, value:) ⇒ Object



358
359
360
361
# File 'lib/ruby_llm/mcp/native/client.rb', line 358

def result_response(id:, value:)
  body = Native::Messages::Responses.result(id: id, value: value)
  request(body, wait_for_response: false)
end

#roots_list_change_notificationObject



341
342
343
344
# File 'lib/ruby_llm/mcp/native/client.rb', line 341

def roots_list_change_notification
  body = Native::Messages::Notifications.roots_list_changed
  request(body, wait_for_response: false)
end

#roots_list_response(id:) ⇒ Object



353
354
355
356
# File 'lib/ruby_llm/mcp/native/client.rb', line 353

def roots_list_response(id:)
  body = Native::Messages::Responses.roots_list(id: id, roots_paths: roots_paths)
  request(body, wait_for_response: false)
end

#roots_pathsObject



416
417
418
# File 'lib/ruby_llm/mcp/native/client.rb', line 416

def roots_paths
  @roots_callback&.call || []
end

#sampling_callback_enabled?Boolean

Returns:

  • (Boolean)


424
425
426
# File 'lib/ruby_llm/mcp/native/client.rb', line 424

def sampling_callback_enabled?
  !@sampling_callback.nil?
end

#sampling_create_message_response(id:, model:, message:, **_options) ⇒ Object



363
364
365
366
# File 'lib/ruby_llm/mcp/native/client.rb', line 363

def sampling_create_message_response(id:, model:, message:, **_options)
  body = Native::Messages::Responses.sampling_create_message(id: id, model: model, message: message)
  request(body, wait_for_response: false)
end

#set_elicitation_enabled(enabled:) ⇒ Object



325
326
327
# File 'lib/ruby_llm/mcp/native/client.rb', line 325

def set_elicitation_enabled(enabled:)
  @elicitation_enabled = enabled
end

#set_logging(level:) ⇒ Object



271
272
273
274
# File 'lib/ruby_llm/mcp/native/client.rb', line 271

def set_logging(level:)
  body = Native::Messages::Requests.logging_set_level(level: level, tracking_progress: tracking_progress?)
  request(body)
end

#set_progress_tracking(enabled:) ⇒ Object



321
322
323
# File 'lib/ruby_llm/mcp/native/client.rb', line 321

def set_progress_tracking(enabled:)
  @progress_tracking_enabled = enabled
end

#startObject



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/ruby_llm/mcp/native/client.rb', line 90

def start
  return unless capabilities.nil?

  transport.start

  initialize_response = initialize_request
  initialize_response.raise_error! if initialize_response.error?

  # Extract and store the negotiated protocol version
  negotiated_version = initialize_response.value["protocolVersion"]

  if negotiated_version && !Native::Protocol.supported_version?(negotiated_version)
    raise Errors::UnsupportedProtocolVersion.new(
      message: <<~MESSAGE
        Unsupported protocol version, and could not negotiate a supported version: #{negotiated_version}.
        Supported versions: #{Native::Protocol.supported_versions.join(', ')}
      MESSAGE
    )
  end

  @protocol_version = negotiated_version if negotiated_version

  # Set the protocol version on the transport for subsequent requests
  if @transport.respond_to?(:set_protocol_version)
    @transport.set_protocol_version(@protocol_version)
  end

  @capabilities = RubyLLM::MCP::ServerCapabilities.new(initialize_response.value["capabilities"])
  initialize_notification

  if @logging_enabled && @logging_level
    set_logging(level: @logging_level)
  end
end

#stopObject



125
126
127
128
129
130
131
132
133
# File 'lib/ruby_llm/mcp/native/client.rb', line 125

def stop
  @transport&.close
  @capabilities = nil
  @transport = nil
  @task_registry = Native::TaskRegistry.new
  @protocol_version = @requested_protocol_version || MCP.config.protocol_version || Native::Protocol.latest_version
  Handlers::HumanInTheLoopRegistry.release(@registry_owner_id)
  @human_in_the_loop_registry = Handlers::HumanInTheLoopRegistry.for_owner(@registry_owner_id)
end

#task_cancel(task_id:) ⇒ Object



308
309
310
311
312
313
314
315
# File 'lib/ruby_llm/mcp/native/client.rb', line 308

def task_cancel(task_id:)
  body = Native::Messages::Requests.task_cancel(task_id: task_id, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  task_registry.upsert(result.value)
  result
end

#task_get(task_id:) ⇒ Object



290
291
292
293
294
295
296
297
# File 'lib/ruby_llm/mcp/native/client.rb', line 290

def task_get(task_id:)
  body = Native::Messages::Requests.task_get(task_id: task_id, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  task_registry.upsert(result.value)
  result
end

#task_result(task_id:) ⇒ Object



299
300
301
302
303
304
305
306
# File 'lib/ruby_llm/mcp/native/client.rb', line 299

def task_result(task_id:)
  body = Native::Messages::Requests.task_result(task_id: task_id, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  task_registry.store_payload(task_id, result.value)
  result
end

#task_status_notification(task:) ⇒ Object



317
318
319
# File 'lib/ruby_llm/mcp/native/client.rb', line 317

def task_status_notification(task:)
  task_registry.upsert(task)
end

#tasks_list(cursor: nil) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/ruby_llm/mcp/native/client.rb', line 276

def tasks_list(cursor: nil)
  body = Native::Messages::Requests.tasks_list(cursor: cursor, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  task_registry.upsert_many(result.value["tasks"])

  if result.next_cursor?
    result.value["tasks"] + tasks_list(cursor: result.next_cursor)
  else
    result.value["tasks"] || []
  end
end

#tool_list(cursor: nil) ⇒ Object



178
179
180
181
182
183
184
185
186
187
188
# File 'lib/ruby_llm/mcp/native/client.rb', line 178

def tool_list(cursor: nil)
  body = Native::Messages::Requests.tool_list(cursor: cursor, tracking_progress: tracking_progress?)
  result = request(body)
  result.raise_error! if result.error?

  if result.next_cursor?
    result.value["tools"] + tool_list(cursor: result.next_cursor)
  else
    result.value["tools"]
  end
end

#tracking_progress?Boolean

Returns:

  • (Boolean)


420
421
422
# File 'lib/ruby_llm/mcp/native/client.rb', line 420

def tracking_progress?
  @progress_tracking_enabled
end

#transportObject



428
429
430
# File 'lib/ruby_llm/mcp/native/client.rb', line 428

def transport
  @transport ||= Native::Transport.new(@transport_type, self, config: @config)
end

#unregister_in_flight_request(request_id) ⇒ Object

Unregister a completed or cancelled request

Parameters:

  • request_id (String)

    The ID of the request



443
444
445
446
447
# File 'lib/ruby_llm/mcp/native/client.rb', line 443

def unregister_in_flight_request(request_id)
  @in_flight_mutex.synchronize do
    @in_flight_requests.delete(request_id.to_s)
  end
end