Class: MCP::ServerSession

Inherits:
Object
  • Object
show all
Defined in:
lib/mcp/server_session.rb

Overview

Holds per-connection state for a single client session. Created by the transport layer; delegates request handling to the shared Server.

Constant Summary collapse

ERAS =
[:legacy, :modern].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server:, transport:, session_id: nil, era: nil) ⇒ ServerSession

Returns a new instance of ServerSession.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/mcp/server_session.rb', line 19

def initialize(server:, transport:, session_id: nil, era: nil)
  validate_era!(era) if era

  @server = server
  @transport = transport
  @session_id = session_id
  @era = era
  @client = nil
  @client_capabilities = nil
  @logging_message_notification = nil
  @protocol_version = nil
  @incoming_cancelled = false
  @incoming_cancel_reason = nil
  @in_flight = {}
  @in_flight_mutex = Mutex.new
  @last_request_finished_at = nil
  @initialized = false
end

Instance Attribute Details

#client ⇒ Object (readonly)

Returns the value of attribute client.



12
13
14
# File 'lib/mcp/server_session.rb', line 12

def client
  @client
end

#era ⇒ Object (readonly)

Connection-era lock of the dual-era serving model (SEP-2575): nil until the first era-distinctive message succeeds, then :legacy or :modern for the connection's lifetime. Modern-era transports construct their per-request sessions with era: :modern up front.



17
18
19
# File 'lib/mcp/server_session.rb', line 17

def era
  @era
end

#logging_message_notification ⇒ Object (readonly)

Returns the value of attribute logging_message_notification.



12
13
14
# File 'lib/mcp/server_session.rb', line 12

def logging_message_notification
  @logging_message_notification
end

#protocol_version ⇒ Object (readonly)

Returns the value of attribute protocol_version.



12
13
14
# File 'lib/mcp/server_session.rb', line 12

def protocol_version
  @protocol_version
end

#session_id ⇒ Object (readonly)

Returns the value of attribute session_id.



12
13
14
# File 'lib/mcp/server_session.rb', line 12

def session_id
  @session_id
end

Instance Method Details

#cancel_all_incoming(reason: nil) ⇒ Object

Flips the Cancellation of every request still in flight, for a transport ending the session they belong to: their handlers observe it as they would notifications/cancelled, and their responses are suppressed the same way. Requests registered afterwards are cancelled as they register. The cancellations run outside the registry lock, since each fires its on_cancel hooks synchronously. One that raises does not keep the rest from being cancelled: the first error is raised once all of them are.



136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/mcp/server_session.rb', line 136

def cancel_all_incoming(reason: nil)
  cancellations = @in_flight_mutex.synchronize do
    @incoming_cancelled = true
    @incoming_cancel_reason = reason
    @in_flight.values
  end

  first_error = nil

  cancellations.each do |cancellation|
    cancellation.cancel(reason: reason)
  rescue StandardError => e
    first_error ||= e
  end

  raise first_error if first_error
end

#cancel_incoming(request_id:, reason: nil) ⇒ Object

Flips the Cancellation for a matching in-flight request received from the peer. Silently ignores unknown IDs per MCP spec (cancellation utilities, item 5).



126
127
128
129
# File 'lib/mcp/server_session.rb', line 126

def cancel_incoming(request_id:, reason: nil)
  cancellation = lookup_in_flight(request_id)
  cancellation&.cancel(reason: reason)
end

#cancel_request(request_id:, reason: nil) ⇒ Object

Sends notifications/cancelled to the peer for a previously-issued request. Also unblocks any transport-level send_request waiting on a response for request_id.



156
157
158
159
160
161
162
163
164
165
166
# File 'lib/mcp/server_session.rb', line 156

def cancel_request(request_id:, reason: nil)
  params = { requestId: request_id }
  params[:reason] = reason if reason
  send_to_transport(Methods::NOTIFICATIONS_CANCELLED, params)

  if @transport.respond_to?(:cancel_pending_request)
    @transport.cancel_pending_request(request_id, reason: reason)
  end
rescue => e
  MCP.configuration.exception_reporter.call(e, { notification: "cancelled", request_id: request_id })
end

#client_capabilities ⇒ Object

Returns per-session client capabilities, falling back to global.



198
199
200
# File 'lib/mcp/server_session.rb', line 198

def client_capabilities
  @client_capabilities || @server.client_capabilities
end

#close_sse_stream(related_request_id:) ⇒ Object

Closes the SSE connection of the request related_request_id without ending the request (SEP-1699), so the client polls the stream by reconnecting with Last-Event-ID; prefer server_context.close_sse_stream inside a handler, which names the current request. Returns false on a transport without resumable streams.



374
375
376
377
378
# File 'lib/mcp/server_session.rb', line 374

def close_sse_stream(related_request_id:)
  return false unless @transport.respond_to?(:close_sse_stream)

  @transport.close_sse_stream(@session_id, related_request_id)
end

#close_standalone_sse_stream ⇒ Object

Closes the session's standalone GET stream the same way.



381
382
383
384
385
# File 'lib/mcp/server_session.rb', line 381

def close_standalone_sse_stream
  return false unless @transport.respond_to?(:close_standalone_sse_stream)

  @transport.close_standalone_sse_stream(@session_id)
end

#configure_logging(logging_message_notification) ⇒ Object

Called by Server#configure_logging_level.



193
194
195
# File 'lib/mcp/server_session.rb', line 193

def configure_logging(logging_message_notification)
  @logging_message_notification = logging_message_notification
end

#create_form_elicitation(message:, requested_schema:, related_request_id: nil, timeout: nil) ⇒ Object

Sends an elicitation/create request (form mode) scoped to this session.

Per SEP-2260, the request must be associated with an originating client request; prefer server_context.create_form_elicitation inside a handler, which stamps the association automatically.



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/mcp/server_session.rb', line 254

def create_form_elicitation(message:, requested_schema:, related_request_id: nil, timeout: nil)
  warn_unassociated_request(__method__, related_request_id)

  unless client_capabilities&.dig(:elicitation)
    raise "Client does not support elicitation. " \
      "The client must declare the `elicitation` capability during initialization."
  end

  params = { mode: "form", message: message, requestedSchema: requested_schema }
  send_to_transport_request(
    Methods::ELICITATION_CREATE,
    params,
    related_request_id: related_request_id,
    timeout: timeout,
  )
end

#create_sampling_message(related_request_id: nil, timeout: nil, **kwargs) ⇒ Object

Deprecated.

MCP Sampling (sampling/createMessage) is deprecated as of MCP protocol version 2026-07-28 (SEP-2577). Use direct LLM provider APIs instead.

Sends a sampling/createMessage request scoped to this session.

Per SEP-2260, the request must be associated with an originating client request; prefer server_context.create_sampling_message inside a handler, which stamps the association automatically.



237
238
239
240
241
242
243
244
245
246
247
# File 'lib/mcp/server_session.rb', line 237

def create_sampling_message(related_request_id: nil, timeout: nil, **kwargs)
  warn_unassociated_request(__method__, related_request_id)

  params = @server.build_sampling_params(client_capabilities, **kwargs)
  send_to_transport_request(
    Methods::SAMPLING_CREATE_MESSAGE,
    params,
    related_request_id: related_request_id,
    timeout: timeout,
  )
end

#create_url_elicitation(message:, url:, elicitation_id:, related_request_id: nil, timeout: nil) ⇒ Object

Sends an elicitation/create request (URL mode) scoped to this session.

Per SEP-2260, the request must be associated with an originating client request; prefer server_context.create_url_elicitation inside a handler, which stamps the association automatically.



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/mcp/server_session.rb', line 276

def create_url_elicitation(message:, url:, elicitation_id:, related_request_id: nil, timeout: nil)
  warn_unassociated_request(__method__, related_request_id)

  unless client_capabilities&.dig(:elicitation, :url)
    raise "Client does not support URL mode elicitation. " \
      "The client must declare the `elicitation.url` capability during initialization."
  end

  params = { mode: "url", message: message, url: url, elicitationId: elicitation_id }
  send_to_transport_request(
    Methods::ELICITATION_CREATE,
    params,
    related_request_id: related_request_id,
    timeout: timeout,
  )
end

#fulfill_input_request(method, params, related_request_id:) ⇒ Object

Sends an embedded SEP-2322 inputRequests entry as a real server-to-client request on the legacy wire, for the server's dual-era fulfilment shim. The entry is forwarded verbatim - per the spec, clients treat each entry exactly like the equivalent standalone request - and stays associated with the originating client request per SEP-2260. Returns the client's result.



298
299
300
# File 'lib/mcp/server_session.rb', line 298

def fulfill_input_request(method, params, related_request_id:)
  send_to_transport_request(method, params, related_request_id: related_request_id)
end

#handle(request = nil, auth_info: nil, **request_keywords) ⇒ Object

Accepts the request either as a positional Hash or as bare keyword arguments (session.handle(jsonrpc: "2.0", ...)), a calling style that predates this method having keyword parameters. auth_info: is honored only alongside a positional request: in the bare-keyword style every keyword belongs to the request body, and the body is attacker-authored JSON, so a captured auth_info keyword is folded back into the request rather than trusted as a verified credential.



172
173
174
175
176
177
178
179
180
# File 'lib/mcp/server_session.rb', line 172

def handle(request = nil, auth_info: nil, **request_keywords)
  if request.nil?
    request = request_keywords
    request[:auth_info] = auth_info unless auth_info.nil?
    auth_info = nil
  end

  @server.handle(request, session: self, auth_info: auth_info)
end

#handle_json(request_json, auth_info: nil) ⇒ Object



182
183
184
# File 'lib/mcp/server_session.rb', line 182

def handle_json(request_json, auth_info: nil)
  @server.handle_json(request_json, session: self, auth_info: auth_info)
end

#in_flight?(request_id) ⇒ Boolean

Whether request_id is currently in flight, so a transport can refuse a colliding request before registering any state of its own for it.

Returns:

  • (Boolean)


116
117
118
# File 'lib/mcp/server_session.rb', line 116

def in_flight?(request_id)
  !lookup_in_flight(request_id).nil?
end

#in_flight_activity ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

What a transport needs to tell whether the session is idle, read in one step so the two cannot disagree: whether a request is still in flight, and the monotonic clock reading at which the last one finished (nil when none has).



110
111
112
# File 'lib/mcp/server_session.rb', line 110

def in_flight_activity
  @in_flight_mutex.synchronize { [!@in_flight.empty?, @last_request_finished_at] }
end

#initialized? ⇒ Boolean

Whether initialize has already completed for this session.

Returns:

  • (Boolean)


39
40
41
# File 'lib/mcp/server_session.rb', line 39

def initialized?
  @initialized
end

#list_roots(related_request_id: nil, timeout: nil) ⇒ Object

Deprecated.

MCP Roots (roots/list and notifications/roots/list_changed) is deprecated as of MCP protocol version 2026-07-28 (SEP-2577). Use tool parameters, resource URIs, server configuration, or environment variables instead.

Sends a roots/list request scoped to this session.

Per SEP-2260, the request must be associated with an originating client request; prefer server_context.list_roots inside a handler, which stamps the association automatically.



211
212
213
214
215
216
217
218
219
# File 'lib/mcp/server_session.rb', line 211

def list_roots(related_request_id: nil, timeout: nil)
  warn_unassociated_request(__method__, related_request_id)

  unless client_capabilities&.dig(:roots)
    raise "Client does not support roots."
  end

  send_to_transport_request(Methods::ROOTS_LIST, nil, related_request_id: related_request_id, timeout: timeout)
end

#lock_era!(era) ⇒ Object

One-shot era lock. Locking the already-locked era is a no-op; flipping an established era raises, because a connection can never change eras.



56
57
58
59
60
61
62
# File 'lib/mcp/server_session.rb', line 56

def lock_era!(era)
  validate_era!(era)
  return if @era == era
  raise "Session era already locked to #{@era}" if @era

  @era = era
end

#lookup_in_flight(request_id) ⇒ Object



120
121
122
# File 'lib/mcp/server_session.rb', line 120

def lookup_in_flight(request_id)
  @in_flight_mutex.synchronize { @in_flight[request_id] }
end

#mark_initialized!(protocol_version: nil) ⇒ Object

Called by Server#init after a successful initialize response, so subsequent initialize requests on the same session can be rejected per MCP spec (the initialization phase MUST be the first interaction).



46
47
48
49
50
51
52
# File 'lib/mcp/server_session.rb', line 46

def mark_initialized!(protocol_version: nil)
  @initialized = true
  @protocol_version = protocol_version
  # A successful `initialize` is the legacy-distinctive message of the dual-era serving model (SEP-2575),
  # so it also locks the connection era.
  @era ||= :legacy
end

#notify_elicitation_complete(elicitation_id:) ⇒ Object

Sends an elicitation complete notification scoped to this session.



320
321
322
323
324
# File 'lib/mcp/server_session.rb', line 320

def notify_elicitation_complete(elicitation_id:)
  send_to_transport(Methods::NOTIFICATIONS_ELICITATION_COMPLETE, { elicitationId: elicitation_id })
rescue => e
  @server.configuration.exception_reporter.call(e, { notification: "elicitation_complete" })
end

#notify_log_message(data:, level:, logger: nil, related_request_id: nil) ⇒ Object

Deprecated.

MCP Logging (logging/setLevel and notifications/message) is deprecated as of MCP protocol version 2026-07-28 (SEP-2577). Use stderr or OpenTelemetry instead.

Sends a log message notification to this session only.



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/mcp/server_session.rb', line 351

def notify_log_message(data:, level:, logger: nil, related_request_id: nil)
  # In the modern lifecycle, log delivery is authorized per request through the `_meta` envelope's `logLevel` member
  # (applied via `configure_logging`); without it no `notifications/message` is sent, and the server-wide level
  # does not apply (SEP-2575).
  effective_logging = if @era == :modern
    @logging_message_notification
  else
    @logging_message_notification || @server.logging_message_notification
  end

  return unless effective_logging&.should_notify?(level)

  params = { "data" => data, "level" => level }
  params["logger"] = logger if logger

  send_to_transport(Methods::NOTIFICATIONS_MESSAGE, params, related_request_id: related_request_id)
rescue => e
  @server.configuration.exception_reporter.call(e, { notification: "log_message" })
end

#notify_progress(progress_token:, progress:, total: nil, message: nil, related_request_id: nil) ⇒ Object

Sends a progress notification to this session only.



334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/mcp/server_session.rb', line 334

def notify_progress(progress_token:, progress:, total: nil, message: nil, related_request_id: nil)
  params = {
    "progressToken" => progress_token,
    "progress" => progress,
    "total" => total,
    "message" => message,
  }.compact

  send_to_transport(Methods::NOTIFICATIONS_PROGRESS, params, related_request_id: related_request_id)
rescue => e
  @server.configuration.exception_reporter.call(e, { notification: "progress" })
end

#notify_resources_updated(uri:) ⇒ Object

Sends a resource updated notification to this session only.



327
328
329
330
331
# File 'lib/mcp/server_session.rb', line 327

def notify_resources_updated(uri:)
  send_to_transport(Methods::NOTIFICATIONS_RESOURCES_UPDATED, { "uri" => uri })
rescue => e
  @server.configuration.exception_reporter.call(e, { notification: "resources_updated" })
end

#ping(related_request_id: nil, timeout: nil) ⇒ Object

Sends a ping request scoped to this session.



222
223
224
225
226
227
# File 'lib/mcp/server_session.rb', line 222

def ping(related_request_id: nil, timeout: nil)
  result = send_to_transport_request(Methods::PING, nil, related_request_id: related_request_id, timeout: timeout)
  raise Server::ValidationError, "Response validation failed: invalid `result`" unless result.is_a?(Hash)

  result
end

#register_in_flight(request_id) ⇒ Object

Registers a Cancellation token for an in-flight request, or returns nil when request_id is already in flight. The request id is the only key that routes request-scoped notifications, server-to-client requests, and notifications/cancelled back to the request that caused them, so a second live request under the same id has no destination of its own. Rather than let the newcomer displace the registration, report the collision and leave the first request intact; the caller turns that into an Invalid Request.

Once cancel_all_incoming has run, the token comes back already cancelled with its reason and is not tracked: a transport can hand a request to a session it is ending, and that request must not outlive the session.



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/mcp/server_session.rb', line 72

def register_in_flight(request_id)
  return if request_id.nil?

  cancellation = Cancellation.new(request_id: request_id)
  cancel_reason = nil
  admission = @in_flight_mutex.synchronize do
    if @incoming_cancelled
      cancel_reason = @incoming_cancel_reason
      :cancelled
    elsif @in_flight.key?(request_id)
      nil
    else
      @in_flight[request_id] = cancellation
      :registered
    end
  end

  cancellation.cancel(reason: cancel_reason) if admission == :cancelled
  cancellation if admission
end

#send_peer_cancellation(nested_request_id:, related_request_id: nil, reason: nil) ⇒ Object

Sends notifications/cancelled to the peer for a nested server-to-client request that was started inside a now-cancelled parent request. related_request_id is the parent request id so the notification is routed to the same stream (e.g. the parent's POST response stream on StreamableHTTPTransport) rather than the GET SSE stream.



307
308
309
310
311
312
313
314
315
316
317
# File 'lib/mcp/server_session.rb', line 307

def send_peer_cancellation(nested_request_id:, related_request_id: nil, reason: nil)
  params = { requestId: nested_request_id }
  params[:reason] = reason if reason
  send_to_transport(Methods::NOTIFICATIONS_CANCELLED, params, related_request_id: related_request_id)

  if @transport.respond_to?(:cancel_pending_request)
    @transport.cancel_pending_request(nested_request_id, reason: reason)
  end
rescue => e
  MCP.configuration.exception_reporter.call(e, { notification: "cancelled", request_id: nested_request_id })
end

#store_client_info(client:, capabilities: nil) ⇒ Object

Called by Server#init during the initialization handshake.



187
188
189
190
# File 'lib/mcp/server_session.rb', line 187

def store_client_info(client:, capabilities: nil)
  @client = client
  @client_capabilities = capabilities
end

#unregister_in_flight(request_id, cancellation: nil) ⇒ Object

Removes an in-flight registration. Passing the Cancellation that register_in_flight returned removes the entry only while it is still that one, so a request can never evict a registration it does not own.



95
96
97
98
99
100
101
102
103
# File 'lib/mcp/server_session.rb', line 95

def unregister_in_flight(request_id, cancellation: nil)
  return if request_id.nil?

  @in_flight_mutex.synchronize do
    next if cancellation && !@in_flight[request_id].equal?(cancellation)

    @last_request_finished_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) if @in_flight.delete(request_id)
  end
end