ruby-sdk/lib/mcp/server_session.rb
Koichi ITO 48b7aaacd9 Stop negotiating modern protocol versions through the initialize handshake
## Motivation and Context

Follow-up to https://github.com/modelcontextprotocol/ruby-sdk/issues/512#issuecomment-5285679761

A comment on #512 reported that results stay unstamped when a client negotiates `2026-07-28` through
the legacy `initialize` handshake: the SEP-2322 `resultType` stamp and the SEP-2549 cache hints are
both gated on the per-request `_meta` envelope, which such a connection never carries,
so strictly validating clients reject every result as missing the REQUIRED `resultType`.

The root cause sits upstream of the stamp. Per the SEP-2575 era model, an era is a property of
the protocol version itself: legacy versions establish a session via `initialize`
(`2025-11-25` and earlier), and modern versions carry their version on every request in `_meta` with
no handshake at all - the 2026-07-28 schema defines no `initialize`, and a request without the envelope
is malformed. The negotiation list of this server still contained `2026-07-28`, producing a hybrid state
the spec does not define and the reference SDKs refuse to construct: the TypeScript server negotiates
from `SUPPORTED_PROTOCOL_VERSIONS`, which stops at `2025-11-25`, and counter-offers its first entry;
the Python server negotiates from `HANDSHAKE_PROTOCOL_VERSIONS`, which stops there too,
and counter-offers `LATEST_HANDSHAKE_VERSION`.

`initialize` now negotiates from a new `SUPPORTED_HANDSHAKE_PROTOCOL_VERSIONS` list
(`2025-11-25` and earlier): a request for `2026-07-28`, or for a version this server does not know,
is counter-offered `2025-11-25`, exactly as both reference SDKs answer. A counter-offered client proceeds on
`2025-11-25`, where `resultType` does not exist and its absence is the correct shape,
resolving the reported rejection. `2026-07-28` stays reachable through `server/discover` and
the per-request envelope, where the stamps already apply. The `envelope &&` stamp gates are
intentionally unchanged: with the handshake capped, an envelope-less `2026-07-28` connection is
no longer constructible, so the gates are correct by construction.

The client side is symmetrized the same way, matching both reference SDKs:
the legacy handshake offers `LATEST_HANDSHAKE_PROTOCOL_VERSION` by default,
passing an explicitly modern `protocol_version` to the legacy connect raises `ArgumentError`
(validated before the stdio transport spawns its child process), and a server answering `initialize` with
a modern version is rejected like an unknown one. `:auto` forwards an explicitly modern version to
the discovery probe and never downgrades it into the legacy fallback: the probe's failure is
the real answer and propagates, instead of the fallback dying on the handshake guard.
The handshake rule itself lives in one place (`Configuration.reject_modern_handshake_version!`),
and the handshake list is derived from the stable and modern lists so the era partition cannot drift
when the next revision lands.

Two consequences are worth naming. The roots/sampling deprecation warnings move to the modern connect
on the client, the revision where SEP-2577 actually deprecates them, since the handshake can no longer land
on a deprecating version and the call site the warnings used to sit on had become unreachable.
On the server the answer is removal: `Configuration#protocol_version` scopes the handshake,
so it now accepts handshake versions only and rejects a modern pin with `ArgumentError` at construction.
Accepting one would configure nothing (a modern version has no handshake to pin),
and neither reference SDK carries a config value that is accepted but inert:
Python's negotiation has no knob at all, and every entry of the TypeScript server's `supportedProtocolVersions`
is consumed by its own era's mechanism. With no path left onto a deprecating revision,
the server-side deprecation warning plumbing became unreachable and is removed along with it.
Keying those warnings on a modern-era session instead was tried and rejected,
because `notify_log_message` is the SEP-2575 sanctioned delivery path on that wire and every log line
would then carry a deprecation warning for doing exactly what the revision prescribes
(a single test file produced over a thousand of them).

A session-bound request may still stamp `MCP-Protocol-Version: 2026-07-28` after being counter-offered,
and such a request continues to be served at the negotiated revision rather than rejected.
Sending the negotiated version is a SHOULD on the client, and the spec's `400 Bad Request` rule
covers a version the server does not support, which is not the case here: this server does serve `2026-07-28`,
through the other lifecycle. The session it is bound to decides, and a test now pins that reading along with
its consequence, which is that no `resultType` appears on those results.

Two details follow from the pin being handshake-scoped. Reading it back when nothing is set
now answers `LATEST_HANDSHAKE_PROTOCOL_VERSION` rather than the newest version of any era,
so the getter no longer hands out a value its own writer rejects and round-tripping
the setting keeps working; only `Server#validate!` reads that default,
through three comparisons that answer the same for either value, so nothing else moves.
And the rejection names its reason instead of listing the accepted versions,
because this is the error an upgrade from a release that accepted the value lands on,
which makes it the migration note a bare list would not be.

`MCP::ProtocolDeprecations` says in its own documentation that only the client emits these warnings now,
and that `LOGGING_MESSAGE` has no caller left. It stays public and callable: removing it would be
a breaking change for no gain.

The handshake examples in `docs/building-clients.md` and the shared `initialize_params` test helper
now use the handshake version as well, and the README section on `protocol_version` describes the pin as
handshake-scoped: handshake versions only, `ArgumentError` for a modern one, the handshake version as the default,
and `2026-07-28` reached through `server/discover` with no configuration needed.

## How Has This Been Tested?

New regression tests pin the reported scenario end to end: an `initialize` requesting `2026-07-28` is
counter-offered `2025-11-25`, locks the legacy era, and subsequent results carry no `resultType`
(the correct shape at that revision). Client-side tests cover the default `2025-11-25` offer,
the `ArgumentError` for an explicitly modern version on the legacy connect
(asserting no child process is spawned on the stdio transport), the rejection of a modern `InitializeResult`
on both transports, the `:auto` probe failure propagating for an explicitly modern version instead of
falling back, and the deprecation warning firing on modern connects declaring roots/sampling capabilities.

Counter-offer adoption gets its own test on both transports, since the server-side fix only resolves anything for
clients that honor a counter-offer, and this client is one of them: the offer is the latest handshake version,
the answer is an older one, and the connection speaks the answer afterwards
(over HTTP the next request's `MCP-Protocol-Version` header carries it). The existing tests could not tell adoption
from an echo, because every one of them had the server answer with the version the client had just offered.
Both new tests were confirmed to fail when the client is made to report its own offer instead.

Tests that pinned the previous dual-lifecycle negotiation were inverted or reworked:
the server tests asserting `2026-07-28` echoes and fallbacks now assert the counter-offer,
and the deprecation warning tests keyed on a legacy-negotiated `2026-07-28` now assert no warning fires.
The server-side deprecation tests that reached their state by calling `mark_initialized!` with a modern version,
or by pinning one in `Configuration`, were replaced by tests asserting no warning fires on those paths,
since no code path can produce the warning state any more; `Configuration` rejecting a modern pin has its own tests
on the constructor and the setter, asserting the reason in the message rather than the list of accepted values.

The default-pin test now also round-trips what it reads back into a fresh `Configuration`,
which is what the old default could not do. The default move was checked for neutrality outside
the suite as well, by building a server that uses every feature `Server#validate!` gates on that value
(`description`, `title`, `website_url`, `instructions`, a `$ref` input schema, and tool annotations)
and confirming all of them are still accepted.

## Breaking Changes

Servers no longer echo `2026-07-28` from `initialize`: clients that negotiated it through
the handshake are counter-offered `2025-11-25` and are served at that revision, matching
the TypeScript and Python servers. `Configuration.new(protocol_version: "2026-07-28")` now
raises `ArgumentError` (the pin scopes the handshake, which cannot land there);
the value was only accepted since v1.1.0, whose handshake behavior this change replaces anyway.
Reading `Configuration#protocol_version` with no pin set answers `2025-11-25` instead of `2026-07-28`;
nothing in this SDK behaves differently for either value, but code comparing that reader against
a literal will see the change. The client no longer offers modern versions on the legacy handshake
and rejects a modern `InitializeResult`. Server-side deprecation warnings for SEP-2577 features
no longer fire at all, because no negotiation or configuration path can put a connection on a deprecating revision;
the client-side warning on a modern connect replaces them.
2026-08-14 16:08:07 +09:00

370 lines
16 KiB
Ruby

# frozen_string_literal: true
require_relative "cancellation"
require_relative "methods"
module MCP
# Holds per-connection state for a single client session.
# Created by the transport layer; delegates request handling to the shared `Server`.
class ServerSession
ERAS = [:legacy, :modern].freeze
attr_reader :session_id, :client, :logging_message_notification, :protocol_version
# 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.
attr_reader :era
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
@in_flight = {}
@in_flight_mutex = Mutex.new
@initialized = false
end
# Whether `initialize` has already completed for this session.
def initialized?
@initialized
end
# 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).
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
# 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.
def lock_era!(era)
validate_era!(era)
return if @era == era
raise "Session era already locked to #{@era}" if @era
@era = era
end
# Registers a `Cancellation` token for an in-flight request.
def register_in_flight(request_id)
return if request_id.nil?
cancellation = Cancellation.new(request_id: request_id)
@in_flight_mutex.synchronize { @in_flight[request_id] = cancellation }
cancellation
end
def unregister_in_flight(request_id)
return if request_id.nil?
@in_flight_mutex.synchronize { @in_flight.delete(request_id) }
end
def lookup_in_flight(request_id)
@in_flight_mutex.synchronize { @in_flight[request_id] }
end
# Flips the `Cancellation` for a matching in-flight request received from the peer.
# Silently ignores unknown IDs per MCP spec (cancellation utilities, item 5).
def cancel_incoming(request_id:, reason: nil)
cancellation = lookup_in_flight(request_id)
cancellation&.cancel(reason: reason)
end
# 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`.
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
def handle(request)
@server.handle(request, session: self)
end
def handle_json(request_json)
@server.handle_json(request_json, session: self)
end
# Called by `Server#init` during the initialization handshake.
def store_client_info(client:, capabilities: nil)
@client = client
@client_capabilities = capabilities
end
# Called by `Server#configure_logging_level`.
def configure_logging(logging_message_notification)
@logging_message_notification = logging_message_notification
end
# Returns per-session client capabilities, falling back to global.
def client_capabilities
@client_capabilities || @server.client_capabilities
end
# 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.
# @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.
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
# Sends a `ping` request scoped to this session.
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
# 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.
# @deprecated MCP Sampling (`sampling/createMessage`) is deprecated as of
# MCP protocol version 2026-07-28 (SEP-2577). Use direct LLM provider
# APIs instead.
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
# 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.
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
# 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.
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
# 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.
def fulfill_input_request(method, params, related_request_id:)
send_to_transport_request(method, params, related_request_id: related_request_id)
end
# 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.
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
# Sends an elicitation complete notification scoped to this session.
def notify_elicitation_complete(elicitation_id:)
send_to_transport(Methods::NOTIFICATIONS_ELICITATION_COMPLETE, { elicitationId: elicitation_id })
rescue => e
@server.report_exception(e, notification: "elicitation_complete")
end
# Sends a resource updated notification to this session only.
def notify_resources_updated(uri:)
send_to_transport(Methods::NOTIFICATIONS_RESOURCES_UPDATED, { "uri" => uri })
rescue => e
@server.report_exception(e, notification: "resources_updated")
end
# Sends a progress notification to this session only.
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.report_exception(e, notification: "progress")
end
# Sends a log message notification to this session only.
# @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.
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.report_exception(e, { notification: "log_message" })
end
private
def validate_era!(era)
raise ArgumentError, "era must be one of #{ERAS.inspect}" unless ERAS.include?(era)
end
# Forwards `send_notification` to the transport with only the kwargs the transport's method signature
# actually accepts. Custom transports that implement the abstract `send_notification(method, params = nil)`
# contract continue to work unchanged; bundled transports that declare `session_id:` / `related_request_id:`
# receive the session-scoped routing information.
def send_to_transport(method, params, related_request_id: nil)
kwargs = {
session_id: @session_id,
related_request_id: related_request_id,
}.compact
forward_to_transport(@transport.method(:send_notification), method, params, kwargs)
end
# Forwards `send_request` to the transport with only the kwargs the transport's method signature
# actually accepts. Custom transports that implement the abstract `send_request(method, params = nil)`
# contract continue to work; bundled transports that declare `session_id:` / `related_request_id:` /
# `parent_cancellation:` / `server_session:` receive the nested-cancellation plumbing.
# When `related_request_id` names an in-flight request, its `Cancellation` token is looked up
# so that cancelling the parent also cancels this nested server-to-client request.
def send_to_transport_request(method, params, related_request_id: nil, timeout: nil)
parent_cancellation = related_request_id ? lookup_in_flight(related_request_id) : nil
kwargs = {
session_id: @session_id,
related_request_id: related_request_id,
parent_cancellation: parent_cancellation,
server_session: self,
timeout: timeout,
}.compact
forward_to_transport(@transport.method(:send_request), method, params, kwargs)
end
# Calls `transport_method(method, params, **supported)` where `supported` contains only the keys
# the transport's method signature accepts. This keeps bundled transports (which declare the new kwargs)
# working while preserving compatibility with custom transports that implement only the abstract
# `(method, params = nil)` contract.
def forward_to_transport(transport_method, method, params, kwargs)
parameters = transport_method.parameters
accepts_keyrest = parameters.any? { |type, _| type == :keyrest }
supported = if accepts_keyrest
kwargs
else
allowed = parameters.filter_map { |type, name| name if type == :key || type == :keyreq }
kwargs.slice(*allowed)
end
# Always splat `**supported` even when empty: on Ruby 2.7 the bare `transport_method.call(method, params)`
# form would let the trailing `params` Hash be auto-promoted to keyword arguments when the receiver
# accepts `**kwargs`, breaking handlers that rely on `params` arriving as a positional Hash.
# The explicit splat suppresses that conversion and is a no-op when `supported` is empty.
transport_method.call(method, params, **supported)
end
# Per SEP-2260, servers MUST send `roots/list`, `sampling/createMessage`, and `elicitation/create` only
# in association with an originating client request (`ping` is exempt). A request without `related_request_id:` is
# delivered on the standalone GET stream by the Streamable HTTP transport, which the 2026-07-28 spec forbids;
# warn so callers migrate to the `server_context` helpers before this becomes an error.
# https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2260
def warn_unassociated_request(method_name, related_request_id)
return if related_request_id
warn(
"Calling `ServerSession##{method_name}` without `related_request_id:` is deprecated (SEP-2260): " \
"server-to-client #{method_name} requests must be associated with an originating client request. " \
"Use `server_context.#{method_name}` inside a handler, or pass `related_request_id:` explicitly.",
uplevel: 2,
)
end
end
end