Class: MCP::Server::Transports::StreamableHTTPTransport
- Defined in:
- lib/mcp/server/transports/streamable_http_transport.rb
Defined Under Namespace
Classes: InvalidJsonError, StreamWriteTimeoutError
Constant Summary collapse
- SSE_HEADERS =
x-accel-buffering: notells reverse proxies (nginx and friends) not to buffer the response, which the spec asks of every SSE stream: a buffering proxy holds events back instead of delivering them as they are written, and on a long-livedsubscriptions/listenstream that also swallows the keepalive frames a dropped peer would otherwise be detected by. The TypeScript and Python SDKs send it on their SSE responses for the same reason. { "content-type" => "text/event-stream", "cache-control" => "no-cache", "connection" => "keep-alive", "x-accel-buffering" => "no", }.freeze
- DEFAULT_SESSION_IDLE_TIMEOUT =
Secure defaults for stateful mode. Without a finite idle timeout, sessions live until an explicit client DELETE, so an unauthenticated
initializeflood retains unboundedServerSessionobjects until memory is exhausted. These defaults expire idle sessions and cap the concurrent count, like the C# SDK (the only reference SDK that hardens this by default, with a 2h idle timeout and a 10k idle-session count). One difference: at the cap this transport rejects a newinitializewith 503 (after reclaiming any already-expired slots), whereas the C# SDK evicts the oldest idle session. Rejecting keeps established sessions stable and avoids evicting a legitimate idle session on an attacker's behalf, at the cost of refusing new sessions while genuinely full. Passsession_idle_timeout: nilto opt out of expiry andmax_sessions: nilto opt out of the cap. 1800- DEFAULT_MAX_SESSIONS =
10_000- DEFAULT_MAX_LISTEN_SUBSCRIPTIONS =
Cap on concurrent
subscriptions/listenstreams (SEP-2575). Each stream holds an open SSE connection for its lifetime, so without a bound an unauthenticated client can retain unbounded connections, like the session-flood caseDEFAULT_MAX_SESSIONSguards. A listen request past the cap is rejected with HTTP 503; passmax_listen_subscriptions: nilto opt out. 1_000- DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES =
Bound on the bytes of resource URIs one
subscriptions/listenrequest may name inresourceSubscriptions(the sum of their byte lengths after duplicates are dropped). The URIs are held for the life of the stream, so without a bound each stream could retain a request body's worth of URIs and the retained total would bemax_listen_subscriptionstimesmax_request_bytes. 64 KiB names about a thousand ordinary URIs; passmax_resource_subscription_bytes: nilto opt out. The specification sets no limit, nor do the TypeScript and Python SDKs; this is the same kind of local safety limit asmax_request_bytes. 64 * 1024
- MAX_RESOURCE_SUBSCRIPTION_URIS =
Bound on the number of distinct resource URIs one
subscriptions/listenrequest may name. A byte bound does not tightly bound the memory a stream keeps, since each retained URI carries a fixed per-object cost however short it is, so the count is bounded as well. LikeMAX_JSON_NESTING, it is a structural limit applied whatevermax_resource_subscription_bytesis, includingnil. 1_024- DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT =
Default deadline in seconds for a server-to-client request (sampling, elicitation,
roots/list,ping). The spec asks implementations to bound every sent request so a peer that never answers cannot exhaust the sender's resources; without one, a client that opens a session and simply never replies parks a worker thread for good.Ten minutes matches the TypeScript SDK, which raises its uniform 60-second request default to 600 seconds for the legs of its legacy
input_requiredshim because they are "human-paced, so the 60s protocol default is wrong". Every request this transport can send is that kind of leg: someone answering an elicitation prompt, or the client's own model producing a sample. (The Python SDK leaves the deadline unset and bounds nothing by default.) Deployments that want a tighter bound pass a smaller value here; a single handler that legitimately waits longer passestimeout:.https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#timeouts
600- DEFAULT_MAX_REQUEST_BYTES =
Default upper bound on the JSON-RPC request body.
handle_postreads the whole body into memory and parses it, so without a cap a single unauthenticated POST can allocate gigabytes and OOM the worker. 4 MiB comfortably fits a typical JSON-RPC request (a 4 MiB JSON string decodes to ~3 MiB of base64 payload); raisemax_request_bytes:for unusually large payloads. Matches the TypeScript SDK's 4 MB default. 4 * 1024 * 1024
- DEFAULT_MAX_INITIALIZE_REQUEST_BYTES =
Bound on the body of an
initializerequest in stateful mode. ItsclientInfoandcapabilitiesare kept for the life of the session, so without a bound of its own each session could retain a wholemax_request_bytesbody and the retained total would bemax_sessionstimes that. An ordinaryinitializeis under 2 KiB; 64 KiB leaves room for largeexperimentalcapabilities. Passmax_initialize_request_bytes: nilto opt out. The TypeScript and Python SDKs keep the initialize data whole with no bound of their own; this is the same kind of local safety limit asmax_request_bytes. 64 * 1024
- MAX_INITIALIZE_PARAMS_VALUES =
Bound on the number of JSON values (objects, arrays, keys, and scalars) in the
paramsof aninitializerequest in stateful mode. A byte bound alone does not tightly bound the memory a session keeps: a body of many small values parses into far more objects than its size suggests, so the parsed structure is bounded as well. LikeMAX_JSON_NESTING, it is a structural limit applied whatevermax_initialize_request_bytesis, includingnil. An ordinaryinitializeholds a few dozen values. 1_024- MAX_JSON_NESTING =
Conservative bound on JSON nesting depth, so a deeply nested body cannot exhaust the stack or amplify parse cost (complements the byte cap).
64- MAX_MODERN_REQUEST_NOTIFICATIONS =
Cap on the notifications buffered for one modern request (SEP-2575). The sink holds them in memory until the handler returns, so a handler that emits notifications in proportion to client-supplied input would otherwise let one request grow memory without bound. Notifications past the cap are not delivered and the notify helpers report
false, the same non-delivery degradation they have on every other undeliverable path. 1_000- DEFAULT_LISTEN_KEEPALIVE_INTERVAL =
Interval in seconds between SSE keepalive comment frames on a
subscriptions/listenstream. Without them a silently dropped connection holds its slot until the next fan-out write fails, so on a quiet server a dead peer would occupy amax_listen_subscriptionsslot indefinitely. The periodic write detects the dead peer and frees the slot. Matches the TypeScript SDK's 15-second default; passlisten_keepalive_interval: nilwhen an upstream proxy pings the stream. 15- LISTEN_DEADLINE_WAIT_FLOOR =
The shortest wait the listen keepalive makes when a stream's deadline is nearer than the interval.
0.01- DEFAULT_MAX_STREAM_LIFETIME =
How long an authenticated SSE stream may stay open before it is closed and the client has to present its token again. Bearer enforcement is per HTTP request, and a stream is one request, so without this an open stream outlives every later token check. The token's own expiry usually arrives first; the cap is what bounds a stream whose token reports no expiry at all (
expis optional in an RFC 7662 introspection response). Neither the specification nor the reference SDKs put a ceiling on a stream, so the value comes from this transport instead: it matchesDEFAULT_SESSION_IDLE_TIMEOUT, because a handshake session already ends after that long without a request, which would leave a longer cap inert, and a sessionlesssubscriptions/listenstream has no other bound at all. DEFAULT_SESSION_IDLE_TIMEOUT- REQUIRED_POST_ACCEPT_TYPES_SSE =
["application/json", "text/event-stream"].freeze
- REQUIRED_POST_ACCEPT_TYPES_JSON =
["application/json"].freeze
- REQUIRED_GET_ACCEPT_TYPES =
["text/event-stream"].freeze
- STREAM_WRITE_ERRORS =
[IOError, Errno::EPIPE, Errno::ECONNRESET].freeze
- DEFAULT_STREAM_WRITE_TIMEOUT =
A write blocks only once the peer's socket buffers are full, which takes a reader already hundreds of kilobytes behind; one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow.
10- RESUMABLE_PROTOCOL_VERSION =
The first protocol version whose clients parse an SSE event with empty data, which the priming event of SEP-1699 resumability is. A session that negotiated an earlier version gets no priming event and is never asked to resume, since it would have no event id to come back with; its other events still carry ids.
"2025-11-25"- REPLAY_PASS_LIMIT =
Replay passes a resume makes before it gives up attaching. Each pass takes the events stored since the previous one and a further pass follows whenever that batch was not empty, so a sender that stores at least one event during each write keeps the loop going; after this many passes that each found events, the connection is closed behind the last batch for the client to reconnect from.
16- SESSION_REAP_INTERVAL =
60- REAPER_JOIN_TIMEOUT =
Seconds
closewaits for a reap in progress to finish closing its streams before it kills the reaper. 5- LISTEN_TEARDOWN_TIMEOUT =
How long
closewaits in all for the closing results of the opensubscriptions/listenstreams before closing the streams still open without one. 5- SESSION_TERMINATED_REASON =
The reason the requests still in flight in a session are cancelled with when the session goes away: terminated by the client's DELETE, expired, torn down with its broken GET stream, or removed by
close. "Session terminated"- REQUEST_ID_CONFLICT_MESSAGE =
The error message a request reusing the id of one in flight in its session is refused with.
"Conflict: Request id is already in flight for this session"- DEFAULT_LOOPBACK_HOSTS =
Loopback hosts always accepted by DNS rebinding protection. A locally bound MCP server (the canonical pattern) is protected out of the box; non-loopback deployments widen the list via
allowed_hosts:. ["127.0.0.1", "::1", "localhost"].freeze
- NAME_MEMBER_BY_METHOD =
JSON-RPC methods whose target is mirrored into the
Mcp-Nameheader (SEP-2575), with theparamsmember that names it. The member is fixed per method: aresources/readis named by itsuriwhatever else itsparamscarry, so anameadded to them cannot stand in for the URI the header is checked against. { Methods::TOOLS_CALL => :name, Methods::RESOURCES_READ => :uri, Methods::PROMPTS_GET => :name, }.freeze
- NAME_BEARING_METHODS =
NAME_MEMBER_BY_METHOD.keys.freeze
- LISTEN_FILTER_FIELDS =
Maps broadcast notification methods to the
SubscriptionFilterfield that opts in to them on asubscriptions/listenstream (SEP-2575).notifications/resources/updatedis matched by URI againstresourceSubscriptionsinstead. { Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED => :toolsListChanged, Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED => :promptsListChanged, Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED => :resourcesListChanged, }.freeze
- MODERN_BAD_REQUEST_CODES =
JSON-RPC error codes that surface as HTTP 400 on the modern path.
-32601maps to 404 (disambiguating an unknown method from a legacy HTTP+SSE 404) and everything else, including internal errors, stays 200, matching the Python SDK's status ladder. [ ErrorCodes::HEADER_MISMATCH, ErrorCodes::MISSING_REQUIRED_CLIENT_CAPABILITY, ErrorCodes::UNSUPPORTED_PROTOCOL_VERSION, JsonRpcHandler::ErrorCode::PARSE_ERROR, JsonRpcHandler::ErrorCode::INVALID_REQUEST, JsonRpcHandler::ErrorCode::INVALID_PARAMS, ].freeze
Instance Method Summary collapse
-
#call(env) ⇒ Object
Rack app interface.
-
#cancel_pending_request(request_id, reason: nil) ⇒ Object
Unblocks a
send_requestawaiting a response when the peer is being cancelled. -
#close ⇒ Object
The reaper is asked to stop and joined before it is killed:
reap_expired_sessionsremoves expired sessions under@mutexand closes their streams after releasing it, and a kill landing between the two would leave those streams open with no session left to find them by. -
#close_sse_stream(session_id, request_id) ⇒ Object
private
Closes the SSE connection of the request
request_idwithout ending the request (SEP-1699), so the client reconnects withLast-Event-IDafter theretry_intervaland the handler's remaining messages, kept by the event store meanwhile, reach it through the resumed connection. -
#close_standalone_sse_stream(session_id) ⇒ Object
private
Closes the session's standalone GET stream the same way, so the client polls for server-initiated messages.
- #close_streams(streams) ⇒ Object
- #deliver_broadcast_notification(notification) ⇒ Object
- #deliver_targeted_notification(notification, session_id, related_request_id) ⇒ Object
-
#delivers_notifications? ⇒ Boolean
Stateless mode has no session streams to deliver notifications on (
send_notificationreports non-delivery), soServer#initadvertises nolistChanged/subscribeflags there. -
#drop_broken_stream(session_id, stream, related_request_id) ⇒ Object
Removes a stream that failed to accept a write.
- #handle_request(request) ⇒ Object
-
#initialize(server, stateless: false, enable_json_response: false, session_idle_timeout: UNSET_IDLE_TIMEOUT, max_sessions: DEFAULT_MAX_SESSIONS, allowed_origins: nil, allowed_hosts: nil, dns_rebinding_protection: true, session_request_validator: nil, max_request_bytes: DEFAULT_MAX_REQUEST_BYTES, max_initialize_request_bytes: DEFAULT_MAX_INITIALIZE_REQUEST_BYTES, max_listen_subscriptions: DEFAULT_MAX_LISTEN_SUBSCRIPTIONS, max_resource_subscription_bytes: DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES, listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL, serve_subscriptions_listen: true, stream_request_notifications: false, server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT, stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT, token_verifier: nil, required_scopes: [], resource_metadata: nil, resource_metadata_url: nil, scope_matcher: nil, max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME, event_store: nil, retry_interval: nil) ⇒ StreamableHTTPTransport
constructor
Creates a Streamable HTTP transport that can be mounted as a Rack app.
-
#logging_sessions ⇒ Array<ServerSession>
private
Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
- #send_notification(method, params = nil, session_id: nil, related_request_id: nil) ⇒ Object
-
#send_request(method, params = nil, session_id: nil, related_request_id: nil, parent_cancellation: nil, server_session: nil, timeout: nil) ⇒ Object
Sends a server-to-client JSON-RPC request (e.g.,
sampling/createMessage) and blocks until the client responds. -
#serves_subscriptions_listen? ⇒ Boolean
Whether this transport serves the
subscriptions/listennotification stream (SEP-2575).
Methods inherited from Transport
#handle_json_request, #open, #send_response
Constructor Details
#initialize(server, stateless: false, enable_json_response: false, session_idle_timeout: UNSET_IDLE_TIMEOUT, max_sessions: DEFAULT_MAX_SESSIONS, allowed_origins: nil, allowed_hosts: nil, dns_rebinding_protection: true, session_request_validator: nil, max_request_bytes: DEFAULT_MAX_REQUEST_BYTES, max_initialize_request_bytes: DEFAULT_MAX_INITIALIZE_REQUEST_BYTES, max_listen_subscriptions: DEFAULT_MAX_LISTEN_SUBSCRIPTIONS, max_resource_subscription_bytes: DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES, listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL, serve_subscriptions_listen: true, stream_request_notifications: false, server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT, stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT, token_verifier: nil, required_scopes: [], resource_metadata: nil, resource_metadata_url: nil, scope_matcher: nil, max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME, event_store: nil, retry_interval: nil) ⇒ StreamableHTTPTransport
Creates a Streamable HTTP transport that can be mounted as a Rack app.
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 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 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 238 def initialize( server, stateless: false, enable_json_response: false, session_idle_timeout: UNSET_IDLE_TIMEOUT, max_sessions: DEFAULT_MAX_SESSIONS, allowed_origins: nil, allowed_hosts: nil, dns_rebinding_protection: true, session_request_validator: nil, max_request_bytes: DEFAULT_MAX_REQUEST_BYTES, max_initialize_request_bytes: DEFAULT_MAX_INITIALIZE_REQUEST_BYTES, max_listen_subscriptions: DEFAULT_MAX_LISTEN_SUBSCRIPTIONS, max_resource_subscription_bytes: DEFAULT_MAX_RESOURCE_SUBSCRIPTION_BYTES, listen_keepalive_interval: DEFAULT_LISTEN_KEEPALIVE_INTERVAL, serve_subscriptions_listen: true, stream_request_notifications: false, server_to_client_request_timeout: DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT, stream_write_timeout: DEFAULT_STREAM_WRITE_TIMEOUT, token_verifier: nil, required_scopes: [], resource_metadata: nil, resource_metadata_url: nil, scope_matcher: nil, max_stream_lifetime: DEFAULT_MAX_STREAM_LIFETIME, event_store: nil, retry_interval: nil ) super(server) # Maps `session_id` to `{ get_sse_stream: stream_object, server_session: ServerSession, last_active_at: float_from_monotonic_clock, origin: origin_header }`. @sessions = {} @mutex = Mutex.new @stateless = stateless @enable_json_response = enable_json_response @session_request_validator = session_request_validator @dns_rebinding_protection = dns_rebinding_protection # A Symbol never equals an `Origin` value, so one other than `:any` would refuse every cross-origin request # without a hint that it was mistyped. if allowed_origins.is_a?(Symbol) && allowed_origins != :any raise ArgumentError, "allowed_origins must be an Array of Origin values or :any (got #{allowed_origins.inspect}); " \ ":any turns Origin validation off, for a server that requires a bearer token on every request" end # Host names are case-insensitive, so the allow lists are compared down-cased. @allowed_hosts = (DEFAULT_LOOPBACK_HOSTS + Array(allowed_hosts)).map(&:downcase).freeze @any_origin_allowed = allowed_origins == :any @allowed_origins = (@any_origin_allowed ? [] : Array(allowed_origins)).map(&:downcase).freeze @pending_responses = {} # Maps a key the transport mints for each `subscriptions/listen` stream to # `{ request_id: listen_request_id, stream: stream_object, filter: honored_list_changed_flags, # resource_uris: Set_of_honored_resource_uris, active: boolean, write_mutex: Mutex, # keepalive_wakeup: ConditionVariable }` (SEP-2575). The request id is the client's, # unique only among that client's own in-flight requests, so it stamps `subscriptionId` but cannot serve as the key: # two clients may pick the same one. Whoever removes an entry signals `keepalive_wakeup` under `@mutex`, # so the stream's keepalive thread ends with its slot instead of sleeping out its interval. # In-process only; a multi-worker deployment needs an external event bus to fan notifications out across processes, # which is a follow-up. @listen_subscriptions = {} # Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits; # `handle_modern` registers the sink and flushes it as SSE frames ahead of the final response (SEP-2575). # For a request served with `stream_request_notifications:` the sink is instead the open response stream, # `{ stream: stream_object, session: ServerSession, write_mutex: Mutex, keepalive_wakeup: ConditionVariable }`, # and each notification is written to it as it is emitted. @modern_request_sinks = {} # Resolve the idle timeout: an explicit value (including `nil` to opt out) wins; otherwise apply the secure default, # which does not apply to stateless mode since it retains no sessions. @session_idle_timeout = if session_idle_timeout.equal?(UNSET_IDLE_TIMEOUT) stateless ? nil : DEFAULT_SESSION_IDLE_TIMEOUT else session_idle_timeout end if @session_idle_timeout if @stateless raise ArgumentError, "session_idle_timeout is not supported in stateless mode." elsif @session_idle_timeout <= 0 raise ArgumentError, "session_idle_timeout must be a positive number." end end unless max_sessions.nil? || (max_sessions.is_a?(Integer) && max_sessions > 0) raise ArgumentError, "max_sessions must be a positive Integer or nil" end # The cap guards the stateful session store; stateless mode keeps none. @max_sessions = stateless ? nil : max_sessions unless max_request_bytes.is_a?(Integer) && max_request_bytes > 0 raise ArgumentError, "max_request_bytes must be a positive Integer" end @max_request_bytes = max_request_bytes if !max_initialize_request_bytes.nil? && !(max_initialize_request_bytes.is_a?(Integer) && max_initialize_request_bytes > 0) raise ArgumentError, "max_initialize_request_bytes must be a positive Integer or nil" end # The bound guards what stateful sessions retain; stateless mode keeps none. @max_initialize_request_bytes = stateless ? nil : max_initialize_request_bytes if !max_listen_subscriptions.nil? && !(max_listen_subscriptions.is_a?(Integer) && max_listen_subscriptions > 0) raise ArgumentError, "max_listen_subscriptions must be a positive Integer or nil" end @max_listen_subscriptions = max_listen_subscriptions if !max_resource_subscription_bytes.nil? && !(max_resource_subscription_bytes.is_a?(Integer) && max_resource_subscription_bytes > 0) raise ArgumentError, "max_resource_subscription_bytes must be a positive Integer or nil" end @max_resource_subscription_bytes = max_resource_subscription_bytes if !listen_keepalive_interval.nil? && !(listen_keepalive_interval.is_a?(Numeric) && listen_keepalive_interval > 0) raise ArgumentError, "listen_keepalive_interval must be a positive number or nil" end @listen_keepalive_interval = listen_keepalive_interval @serve_subscriptions_listen = serve_subscriptions_listen # `serve_subscriptions_listen: false` is how a host says it buffers responses, and a buffered response # cannot carry a notification before its handler has returned. if stream_request_notifications && !serve_subscriptions_listen raise ArgumentError, "stream_request_notifications needs a host that serves streaming responses, " \ "so it cannot be combined with serve_subscriptions_listen: false" end @stream_request_notifications = stream_request_notifications unless server_to_client_request_timeout.is_a?(Numeric) && server_to_client_request_timeout.positive? raise ArgumentError, "server_to_client_request_timeout must be a positive number" end @server_to_client_request_timeout = server_to_client_request_timeout unless stream_write_timeout.nil? || (stream_write_timeout.is_a?(Numeric) && stream_write_timeout.positive?) raise ArgumentError, "stream_write_timeout must be a positive number or nil" end @stream_write_timeout = stream_write_timeout # Keyed by identity and weak, so a stream is not kept alive for having been recorded here. @streams_with_abandoned_close = ObjectSpace::WeakMap.new if token_verifier @oauth_authenticator = OAuth::Authenticator.new( token_verifier: token_verifier, required_scopes: required_scopes, resource_metadata: , resource_metadata_url: , scope_matcher: scope_matcher, ) elsif !Array(required_scopes).empty? || || || scope_matcher # OAuth options without a verifier would look protected while enforcing nothing. raise ArgumentError, "required_scopes, resource_metadata, resource_metadata_url, and scope_matcher require token_verifier" else @oauth_authenticator = nil end unless max_stream_lifetime.nil? || (max_stream_lifetime.is_a?(Numeric) && max_stream_lifetime.positive?) raise ArgumentError, "max_stream_lifetime must be a positive number or nil" end @max_stream_lifetime = max_stream_lifetime if event_store raise ArgumentError, "event_store is not supported in stateless mode." if @stateless unless event_store.respond_to?(:store_event) && event_store.respond_to?(:events_after) raise ArgumentError, "event_store must respond to store_event and events_after (see MCP::Server::Transports::EventStore)" end end @event_store = event_store if retry_interval # A retry interval without a store would promise a resumable stream the transport cannot resume. raise ArgumentError, "retry_interval requires event_store" unless event_store unless retry_interval.is_a?(Integer) && retry_interval.positive? raise ArgumentError, "retry_interval must be a positive Integer of milliseconds or nil" end end @retry_interval = retry_interval # `close` sets the flag and signals the reaper under `@mutex`, so the reaper leaves its wait at once instead of # being killed in the middle of a reap. @closing = false @reaper_wakeup = ConditionVariable.new start_reaper_thread if @session_idle_timeout end |
Instance Method Details
#call(env) ⇒ Object
Rack app interface. This transport can be mounted as a Rack app.
511 512 513 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 511 def call(env) handle_request(Rack::Request.new(env)) end |
#cancel_pending_request(request_id, reason: nil) ⇒ Object
Unblocks a send_request awaiting a response when the peer is being cancelled.
The waiting thread will see :cancelled on its queue and raise MCP::CancelledError.
Race note: this is first-writer-wins on the pending-response queue. If a real response
has already been pushed (client responded before the cancel hook fired), that response
wins and :cancelled is enqueued behind it but never read - send_request returns
the real response and deletes the pending entry in its ensure block. Conversely,
if :cancelled arrives first, any later client response is silently dropped in handle_response
because the pending entry has been removed.
920 921 922 923 924 925 926 927 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 920 def cancel_pending_request(request_id, reason: nil) @mutex.synchronize do if (pending = @pending_responses[request_id]) pending[:cancel_reason] = reason pending[:queue].push(:cancelled) end end end |
#close ⇒ Object
The reaper is asked to stop and joined before it is killed: reap_expired_sessions removes expired sessions
under @mutex and closes their streams after releasing it, and a kill landing between the two would leave
those streams open with no session left to find them by. Waking the reaper ends its wait at once, and the join
lets a reap already past its removal finish its closes before the rest of the transport is torn down.
The join is bounded, so a stream whose close never returns cannot hold the shutdown, and a reaper that died
with a StandardError does not stop the teardown below: join re-raises the exception a thread died with,
which is not this method's to raise. A reaper still alive after the wait is killed as before, leaving
the streams of that reap it had not closed yet as they were.
A close running on the reaper thread itself, reached from a stream's close or from the exception reporter
during a reap, neither joins nor kills it: the join would fail on its own thread and the kill would end
this teardown with the reap that called it. The reaper leaves its loop on @closing once that reap returns.
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 596 def close reaper = @mutex.synchronize do @closing = true @reaper_wakeup.signal @reaper_thread end if reaper && !reaper.equal?(Thread.current) begin reaper.join(REAPER_JOIN_TIMEOUT) rescue StandardError # The reaper is gone either way; the exception that ended it is not this method's to report. end reaper.kill if reaper.alive? end @reaper_thread = nil teardown_listen_subscriptions removed_sessions = @mutex.synchronize do @sessions.each_key.filter_map { |session_id| cleanup_session_unsafe(session_id) } end release_sessions(removed_sessions) end |
#close_sse_stream(session_id, request_id) ⇒ 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.
Closes the SSE connection of the request request_id without ending the request (SEP-1699), so the client reconnects with
Last-Event-ID after the retry_interval and the handler's remaining messages, kept by the event store meanwhile,
reach it through the resumed connection. Returns false when there is nothing to close: no event_store:,
a client that negotiated a version before 2025-11-25 (it received no priming event to come back with),
a connection whose priming event the store failed to take (the client holds no cursor for it either),
an unknown session or request, or a connection already closed. Handlers reach this through server_context.close_sse_stream.
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 936 def close_sse_stream(session_id, request_id) stream = @mutex.synchronize do session = session_id && @sessions[session_id] next unless session && resumable_session?(session) entry = session.dig(:post_stream_entries, request_id) current = session.dig(:post_request_streams, request_id) next unless entry && current && entry[:primed_stream].equal?(current) session[:post_request_streams].delete(request_id) end return false unless stream close_stream_safely(stream) true end |
#close_standalone_sse_stream(session_id) ⇒ 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.
Closes the session's standalone GET stream the same way, so the client polls for server-initiated messages.
956 957 958 959 960 961 962 963 964 965 966 967 968 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 956 def close_standalone_sse_stream(session_id) stream = @mutex.synchronize do session = session_id && @sessions[session_id] next unless session && resumable_session?(session) next unless session[:get_sse_stream] && session[:get_primed_stream].equal?(session[:get_sse_stream]) detach_get_stream(session) end return false unless stream close_stream_safely(stream) true end |
#close_streams(streams) ⇒ Object
787 788 789 790 791 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 787 def close_streams(streams) streams.each do |stream| close_stream_safely(stream) end end |
#deliver_broadcast_notification(notification) ⇒ Object
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 715 def deliver_broadcast_notification(notification) removed_sessions = [] # Snapshot the sessions under the lock, then write to each outside it. A session whose GET stream is # closed at the moment still takes the notification when it has opened that stream before and an event # store keeps it for the reconnect; one that never opened the stream has no cursor to resume from. targets = @mutex.synchronize do expired_session_ids = [] collected = @sessions.filter_map do |session_id, session| next unless session[:get_sse_stream] || (@event_store && session[:get_stream_opened]) if session_expired?(session) expired_session_ids << session_id next end session_id end expired_session_ids.each do |session_id| cleanup_and_collect_session(session_id, removed_sessions) end collected end release_sessions(removed_sessions) json = notification.to_json targets.count do |session_id| store_and_write(session_id, nil, json) end end |
#deliver_targeted_notification(notification, session_id, related_request_id) ⇒ Object
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 690 def deliver_targeted_notification(notification, session_id, ) # JSON response mode returns a single JSON object as the POST response, # so request-scoped notifications (e.g. progress, log) cannot be delivered # alongside it. Session-scoped standalone notifications # (e.g. `resources/updated`, `elicitation/complete`) still flow via GET SSE. return false if @enable_json_response && removed_sessions = [] live = @mutex.synchronize do next false unless (session = @sessions[session_id]) if session_expired?(session) cleanup_and_collect_session(session_id, removed_sessions) next false end true end release_sessions(removed_sessions) return false unless live store_and_write(session_id, , notification.to_json) end |
#delivers_notifications? ⇒ Boolean
Stateless mode has no session streams to deliver notifications on (send_notification reports non-delivery),
so Server#init advertises no listChanged/subscribe flags there.
525 526 527 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 525 def delivers_notifications? !@stateless end |
#drop_broken_stream(session_id, stream, related_request_id) ⇒ Object
Removes a stream that failed to accept a write. A request-scoped stream is dropped on its own;
a session-scoped (GET SSE) failure tears down the whole session. The @sessions mutation runs
under @mutex, and the affected streams are closed outside it.
Only the GET stream the session still holds takes the session down with it, judged under the same hold of the lock that removes the session: the failed write may have been picked for a stream that was detached since, because its token expired and the client reopened, and the stream opened in its place must stay. A failed stream the session no longer holds was closed by whichever path detached it, so there is nothing left to do. With an event store the GET stream is detached instead and the session kept: the client resumes the stream from its last event id (SEP-1699), and the events it misses meanwhile are stored for it.
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 760 def drop_broken_stream(session_id, stream, ) streams_to_close = [] removed_sessions = [] @mutex.synchronize do session = @sessions[session_id] if # Unregister only our own stream: removing on the id alone would drop whichever stream currently holds it, # which is not necessarily the one that failed. The failed stream is closed either way, and a request-scoped # failure never reaches the session teardown below. registered = session&.dig(:post_request_streams, ) session[:post_request_streams].delete() if registered.equal?(stream) streams_to_close << stream elsif session && session[:get_sse_stream].equal?(stream) if @event_store streams_to_close << detach_get_stream(session) else cleanup_and_collect_session(session_id, removed_sessions) end end end close_streams(streams_to_close) release_sessions(removed_sessions) end |
#handle_request(request) ⇒ Object
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 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 529 def handle_request(request) rebinding_error = validate_dns_rebinding(request) return rebinding_error if rebinding_error # Bearer enforcement runs after the DNS-rebinding rejection (which must stay the cheapest gate and # never trigger verifier work) and before any body read, so an unauthenticated request costs no parsing. auth_error = authenticate_request(request) return auth_error if auth_error # Header-primary era routing (SEP-2575). An `MCP-Protocol-Version` header naming a version outside # every supported list routes to the sessionless modern path, so an unknown future version receives # the spec-mandated `-32022` with the supported list instead of the legacy path's generic invalid-request error. # Requests without the header, or with a stable-only version, take the existing paths untouched. # An empty header value is malformed rather than a version claim, so it stays on the legacy path # and fails legacy header validation as before. # # A modern header value (2026-07-28) alone cannot decide the era: sessionless modern traffic carries it, # and requests of an established legacy session may stamp it as well (the handshake itself never negotiates it): # an `Mcp-Session-Id` binds the request to an established legacy session (POST requests, the GET SSE stream, # and DELETE termination keep working), and a session-less POST whose body is `initialize` is # the legacy-distinctive handshake. Everything else under a dual-era header is sessionless modern traffic # (`server/discover`, envelope-carrying requests, and envelope-missing requests that get the modern path's error shape). header_version = request.env["HTTP_MCP_PROTOCOL_VERSION"] if header_version && !header_version.empty? && !stable_only_version?(header_version) unless MCP::Configuration.modern_protocol_version?(header_version) return handle_modern(request, header_version) end if extract_session_id(request).nil? return handle_modern(request, header_version) unless request.env["REQUEST_METHOD"] == "POST" # The body is readable only once (Rack 3 inputs need not be rewindable), so the era sniff reads it here, # bounded, and hands the string to whichever path serves the request. body_string = read_bounded_body(request) return payload_too_large_response if body_string.nil? unless legacy_handshake_body?(body_string) return handle_modern(request, header_version, body_string: body_string) end return handle_post(request, body_string: body_string) end end case request.env["REQUEST_METHOD"] when "POST" handle_post(request) when "GET" handle_get(request) when "DELETE" handle_delete(request) else method_not_allowed_response end end |
#logging_sessions ⇒ Array<ServerSession>
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.
Sessions a server-wide log broadcast is offered to, each applying its own level or the server default.
Public only so that Server#notify_log_message can call it. Custom transports may implement this hook;
returning nil keeps the server-wide filter.
629 630 631 632 633 634 635 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 629 def logging_sessions @mutex.synchronize do @sessions.values.filter_map do |session| session[:server_session] if session[:get_sse_stream] end end end |
#send_notification(method, params = nil, session_id: nil, related_request_id: nil) ⇒ Object
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 637 def send_notification(method, params = nil, session_id: nil, related_request_id: nil) # `subscriptions/listen` streams (SEP-2575) receive matching change notifications regardless of the delivery below: # a resource updated by one session's tool call changed globally, so modern subscribers hear about it too. # Runs before the per-request sink and the stateless guard because the listen registry does not depend on sessions, # and a sink capturing the notification for its own response stream must not hide it from other subscriptions. deliver_to_listen_subscriptions(method, params) notification = { jsonrpc: "2.0", method: method, } notification[:params] = params if params # A modern request's notifications ride its own response stream (SEP-2575): `handle_modern` registers # a per-request sink for its ephemeral session and flushes it as SSE frames ahead of the final response. # Checked before the stateless guard, since modern requests are served in stateless deployments too. # The sink is bounded; past `MAX_MODERN_REQUEST_NOTIFICATIONS` the notification is dropped as # non-delivery (`false`), never handed to the legacy paths below. It holds each notification as JSON, # generated here so that one that cannot be generated is dropped on its own instead of failing # the whole response when the sink is flushed. # # A sink that is the open response stream (`stream_request_notifications:`) is written to at once and is not # counted: each write waits for the peer, within `stream_write_timeout:`, so nothing accumulates here. sink = @mutex.synchronize { session_id && @modern_request_sinks[session_id] } if sink return false if sink.is_a?(Array) && sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS begin notification_json = notification.to_json rescue JSON::GeneratorError => e MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Failed to generate notification" }) return false end return write_to_request_stream(sink, notification_json) unless sink.is_a?(Array) sink << notification_json return true end # Stateless mode has no streams to deliver notifications on. Report non-delivery instead of raising # so the ephemeral per-request session's notify_* helpers (e.g. progress or log notifications from # a tool handler) degrade gracefully rather than spamming the exception reporter on every call. return false if @stateless if session_id deliver_targeted_notification(notification, session_id, ) else deliver_broadcast_notification(notification) end end |
#send_request(method, params = nil, session_id: nil, related_request_id: nil, parent_cancellation: nil, server_session: nil, timeout: nil) ⇒ Object
Sends a server-to-client JSON-RPC request (e.g., sampling/createMessage) and blocks until
the client responds.
Uses a PendingResponse for cross-thread synchronization: this method registers one,
sends the request via SSE stream, then waits on it. When the client POSTs a response,
handle_response matches it by request_id and resolves the pending response,
unblocking this thread. A cancellation and session teardown resolve it the same way.
The wait is bounded by timeout (defaulting to the transport's server_to_client_request_timeout),
so a client that never answers cannot park the calling thread for good. On expiry the peer is
sent notifications/cancelled and MCP::Server::RequestTimeoutError is raised.
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 804 def send_request(method, params = nil, session_id: nil, related_request_id: nil, parent_cancellation: nil, server_session: nil, timeout: nil) # The modern lifecycle (SEP-2575) forbids server-initiated JSON-RPC requests; # multi round-trip `input_required` results (SEP-2322) replace them. A modern session has never reached # the rest of this method anyway, since `handle_modern` mints its session without registering it in `@sessions`, # but that is incidental: without the rule stated here a modern handler that reaches for elicitation # or sampling is told "Session not found: <uuid>", which points at everything except the actual reason. # `StdioTransport#send_request` refuses the same way. if server_session&.era == :modern raise "Server-initiated requests are not available in the modern lifecycle (SEP-2575)." end if @stateless raise "Stateless mode does not support server-to-client requests." end if @enable_json_response raise "JSON response mode does not support server-to-client requests." end unless session_id raise "session_id is required for server-to-client requests." end request_id = generate_request_id pending_response = PendingResponse.new wait_timeout = timeout || @server_to_client_request_timeout cancel_hook = nil request = { jsonrpc: "2.0", id: request_id, method: method } request[:params] = params if params # Register the pending response under the lock before the request is written, so a response arriving at once finds its entry; # the write itself runs outside `@mutex`. @mutex.synchronize do unless @sessions.key?(session_id) raise "Session not found: #{session_id}." end @pending_responses[request_id] = { queue: pending_response, session_id: session_id } end # With an event store a request whose stream is disconnected is kept for replay, so the wait below can still # be answered once the client resumes the stream (SEP-1699); without one there is nothing the client could # come back to, so the wait is not started. unless store_and_write(session_id, , request.to_json) raise "No active stream for #{method} request." end if parent_cancellation && server_session cancel_hook = parent_cancellation.on_cancel do |reason| server_session.send_peer_cancellation( nested_request_id: request_id, related_request_id: , reason: reason, ) end end response = pending_response.pop(timeout: wait_timeout) do # Expiry cancels as well as stops waiting, so a client that answers late does not act on # a request the server has abandoned. Only connections speaking 2025-11-25 or earlier get here: # the modern lifecycle forbids server-to-client requests outright, and its sessionless requests # never register the session this method looks up. Those revisions ask the sender to "issue # a cancellation notification for that request and stop waiting", letting either side send one. # (The 2026-07-28 rule reserving `notifications/cancelled` for `subscriptions/listen` teardown # governs the era that has no such requests to cancel.) Both reference SDKs send this same # courtesy cancel on timeout. server_session&.send_peer_cancellation( nested_request_id: request_id, related_request_id: , reason: "Timed out after #{wait_timeout} seconds", ) raise RequestTimeoutError.new( "#{method} request timed out after #{wait_timeout} seconds", request_id: request_id, timeout: wait_timeout, ) end if response.is_a?(Hash) && response.key?(:error) raise StandardError, "Client returned an error for #{method} request (code: #{response[:error][:code]}): #{response[:error][:message]}" end if response == :session_closed raise "SSE session closed while waiting for #{method} response." end if response == :cancelled reason = @mutex.synchronize { @pending_responses.dig(request_id, :cancel_reason) } raise MCP::CancelledError.new( "#{method} request was cancelled", request_id: request_id, reason: reason, ) end response ensure parent_cancellation.off_cancel(cancel_hook) if cancel_hook if request_id @mutex.synchronize do @pending_responses.delete(request_id) end end end |
#serves_subscriptions_listen? ⇒ Boolean
Whether this transport serves the subscriptions/listen notification stream (SEP-2575).
Gates both the route (a refusing transport answers the method as unimplemented) and
the listChanged/subscribe capability flags Server#discover advertises,
so the two always agree. Set via the serve_subscriptions_listen: constructor keyword.
519 520 521 |
# File 'lib/mcp/server/transports/streamable_http_transport.rb', line 519 def serves_subscriptions_listen? @serve_subscriptions_listen end |