From 7b0993726be415fe6dd3d673d7a3bf6a533d3647 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 22 Nov 2026 00:40:10 +0900 Subject: [PATCH] Stream the notifications of a request as they are emitted ## Motivation On the 2026-07-28 lifecycle the notifications a handler emits ride the response of its own request. The transport collected them and sent them with the result once the handler had returned, so the progress of a long-running tool reached the client only when the tool was done: it could not reset a client timeout or show anything while the call ran, and past 1,000 notifications the rest were dropped. The TypeScript and Python SDKs write them to the response stream as they are emitted. `stream_request_notifications: true` on `StreamableHTTPTransport` does the same for a request that asks for progress: a `tools/call`, `prompts/get` or `resources/read` carrying `_meta.progressToken` is answered on an SSE stream that stays open until the result, its last event. It is opt-in because it changes how such a request is served: - The handler runs inside the streaming body, on the thread the host writes the response from. No thread or fiber is added for it, so an application keeps its thread-bound state, but the host has to serve streaming bodies. The option raises `ArgumentError` together with `serve_subscriptions_listen: false`. - Opening the stream commits HTTP 200 before the handler runs. The answers the spec ties to another status are ruled out first where they can be told ahead of the handler (a request that is not valid JSON-RPC, an unimplemented method, a missing or malformed envelope, a custom header that disagrees with the body), and those requests keep the buffered exchange. Any other error of a streamed request is the last event of the stream. One of them departs from the spec, which asks HTTP 400 for a missing client capability (`-32021`): only the handler finds that out, so a streamed request carries it on the stream, as the buffered exchange does once a notification was sent. - The headers of a `tools/call` are compared ahead of the stream only on a tool that is known without running the request. With a `tools_list_handler` the tool is the one the block returns for the dispatch itself, so such a server keeps the buffered exchange for `tools/call`, and an unknown tool is answered the same with and without the option. Each notification and keepalive write waits for the client within `stream_write_timeout:`, so the notifications of a streamed request are not counted. A write that fails or stalls cancels the request, since closing the response stream is how a client cancels on this lifecycle. Keepalive comment frames are written every `listen_keepalive_interval:` seconds while the handler is quiet, by one thread per streamed request, which also notices a client that went away. Closes #702. ## Tested `test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb` covers the option; without the change the constructor refuses the keyword. ## Breaking Changes None. The option is off by default, and a transport constructed without it serves every request as before. --- docs/_server/progress.md | 3 +- docs/_server/transports.md | 38 ++ lib/mcp/server.rb | 22 + .../transports/streamable_http_transport.rb | 245 +++++++- ..._http_stream_request_notifications_test.rb | 594 ++++++++++++++++++ 5 files changed, 886 insertions(+), 16 deletions(-) create mode 100644 test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb diff --git a/docs/_server/progress.md b/docs/_server/progress.md index a935fcfa..98e7a0b1 100644 --- a/docs/_server/progress.md +++ b/docs/_server/progress.md @@ -54,7 +54,8 @@ string tokens are supported. > On the [modern lifecycle](/server/discover/#the-stateless-modern-lifecycle), progress notifications emitted during a request ride > the request's own SSE response stream. The bundled transport buffers them and flushes after > the handler returns, so they preserve order but arrive together with the final response rather -> than in real time. +> than in real time. Construct the transport with `stream_request_notifications: true` to deliver them +> as they are emitted; see [Streaming Request Notifications](/server/transports/#streaming-request-notifications). ## Client Side diff --git a/docs/_server/transports.md b/docs/_server/transports.md index 9967d471..f92a632e 100644 --- a/docs/_server/transports.md +++ b/docs/_server/transports.md @@ -240,6 +240,44 @@ This mode is suitable for simple tool servers that do not need server-initiated > Requests of the [modern lifecycle](/server/discover/#the-stateless-modern-lifecycle) of MCP 2026-07-28 ignore `enable_json_response:` > and are served as SSE-framed single exchanges, so request-scoped notifications still reach the client. +### Streaming Request Notifications + +On the [modern lifecycle](/server/discover/#the-stateless-modern-lifecycle) of MCP 2026-07-28, the notifications a handler emits ride +the response of its own request. By default the transport collects them (up to 1,000 per request) and sends them together with +the result once the handler returns. Set `stream_request_notifications: true` to deliver them as they are emitted instead, +so a client sees the progress of a long-running call while it runs: + +```ruby +transport = MCP::Server::Transports::StreamableHTTPTransport.new(server, stream_request_notifications: true) +``` + +A request is streamed when it carries a `progressToken` in `_meta` and its method is `tools/call`, `prompts/get` or `resources/read`. +Its response is an SSE stream that stays open until the result, which is the last event; every other request is served as before. +While the handler is quiet, a keepalive comment frame is written every `listen_keepalive_interval` seconds. +Each notification and keepalive waits for the client, for at most `stream_write_timeout` seconds, +and the notifications of a streamed request are not counted. +A client that closes the stream cancels its request: the handler sees `server_context.cancelled?` at the next write that fails, +so with `listen_keepalive_interval: nil` a handler that emits nothing is not told. +As on every stream of the modern lifecycle, events carry no id and the stream cannot be resumed. + +The handler of a streamed request runs while the host writes the response body, on the thread that writes it, +so the host has to serve Rack streaming bodies, as it does for `subscriptions/listen`, and nothing in front of the transport may buffer the body +(`Rack::Deflater`, for example, or the [controller pattern](#rails-controller), with which the option cannot be combined: +it raises `ArgumentError` together with `serve_subscriptions_listen: false`). +By then the `call` of every middleware in front of the transport has returned, so request state that a middleware clears +when its `call` returns is gone when the handler runs; state released when the body is closed, as the Rails executor does, is still there. + +{: .important } +> Opening the stream commits HTTP 200 before the handler runs. The transport first rules out the answers that the spec ties to +> another status and that can be told ahead of the handler (a request that is not valid JSON-RPC, an unimplemented method, a malformed `_meta` envelope, +> a [custom header](/server/tools/) that disagrees with the body), and serves those requests as before. +> Any other error of a streamed request, such as invalid arguments or an unknown prompt or resource, +> is the last event of the stream, under HTTP 200. That includes one the spec asks HTTP 400 for: +> a client capability the handler finds missing (`-32021`, raised by `server_context.require_client_capability!`) +> is known only once the handler runs, so a streamed request carries it on the stream. +> A `tools/call` is streamed only when its tool can be looked up ahead of the handler: +> a server with a `tools_list_handler` decides that per request, so its `tools/call` requests are served as before. + ### Resumable SSE Streams Per MCP 2025-11-25 (SEP-1699), a client whose SSE stream is disconnected can reconnect with a GET carrying diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 7f610d41..97904ffe 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -503,6 +503,28 @@ def tools_list_handler(&block) @tools_list_handler = block end + # The tool a `tools/call` naming `name` resolves to when that can be told before the request is dispatched: + # `nil` for a name that is not registered, and always with a `tools_list_handler`, whose answer belongs to + # the dispatch that asks for it. + # + # @api private + def tool_known_ahead_of_dispatch(name) + tools[name] unless @tools_list_handler + end + + # Whether a request for `method` reaches a handler, by the two checks the dispatch makes first: a handler is registered, + # and the capability the method belongs to is declared. + # + # @api private + def implements_method?(method) + return false unless @handlers[method] + + Methods.ensure_capability!(method, effective_capabilities) + true + rescue Methods::MissingRequiredCapabilityError + false + end + # Sets a custom handler for `resources/list` requests, letting the visible list depend on request context such as # the authenticated principal or granted scope. The block returns the resource collection to serve; # the framework paginates it and stamps SEP-2549 cache hints exactly as it does for the constructor-provided resources, diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index 00d89f03..38f00bdf 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -188,6 +188,14 @@ class InvalidJsonError < StandardError; end # the method then answers 404 with JSON-RPC `-32601` like any unimplemented method, # and `Server#discover` stops advertising the `listChanged`/`subscribe` capability flags, # keeping the advertisement and the actual behavior in agreement. Defaults to `true`. + # @param stream_request_notifications [Boolean] whether a 2026-07-28 request that asks for progress + # (`_meta.progressToken` on a `tools/call`, `prompts/get` or `resources/read`) gets the notifications of its handler + # as they are emitted, on an SSE response held open until the result, instead of all at once after the handler returns. + # The handler then runs while the host writes the response body, so the host has to serve a streaming body, + # and an error of such a request is answered on the stream, under HTTP 200. A `tools/call` is streamed only when + # its tool is known ahead of the handler, which leaves out a server with a `tools_list_handler`. + # Keepalive comment frames are written every `listen_keepalive_interval` seconds. Defaults to `false`; + # cannot be combined with `serve_subscriptions_listen: false`. # @param server_to_client_request_timeout [Numeric] seconds a server-to-client request waits for its # response before the transport stops waiting and raises `MCP::Server::RequestTimeoutError`. # Defaults to `DEFAULT_SERVER_TO_CLIENT_REQUEST_TIMEOUT` (600); individual calls override it with `timeout:`. @@ -243,6 +251,7 @@ def initialize( 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, @@ -290,6 +299,9 @@ def initialize( # 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, @@ -347,6 +359,15 @@ def initialize( @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 @@ -622,16 +643,24 @@ def send_notification(method, params = nil, session_id: nil, related_request_id: # 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.size >= MAX_MODERN_REQUEST_NOTIFICATIONS + return false if sink.is_a?(Array) && sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS begin - sink << notification.to_json + 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 @@ -1100,9 +1129,14 @@ def handle_modern(request, header_version, body_string: nil) end session = modern_session + auth_info = request.env[OAuth::ENV_KEY] + if stream_modern_request?(body, request) + return streamed_modern_response(body, body_string, session, auth_info, tool_call_check) + end + notifications = @mutex.synchronize { @modern_request_sinks[session.session_id] = [] } begin - response = @server.handle(body, session: session, auth_info: request.env[OAuth::ENV_KEY], tool_call_check: tool_call_check) + response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check) ensure @mutex.synchronize { @modern_request_sinks.delete(session.session_id) } end @@ -1112,21 +1146,13 @@ def handle_modern(request, header_version, body_string: nil) # `nil` covers notifications and cancellation-suppressed responses; ack with 202 like the legacy notification path. return handle_accepted if response.nil? - # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json` - # does on the legacy paths, instead of failing the whole exchange with a 500. - response_json = begin - response.to_json - rescue JSON::GeneratorError => e - MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" }) - response = JsonRpcHandler.encodable_response(response) - response.to_json - end + response, response_json = modern_response_json(response) # Notifications a handler emitted during the request ride the request's own response stream as SSE frames ahead of # the final response (SEP-2575); a request that emitted none keeps the single JSON exchange and its HTTP status ladder. - # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving - # (the TypeScript and Python SDKs stream live), and the sink grows with the handler's notification count. - # Live streaming can follow without changing the wire shape. + # Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving, + # and the sink grows with the handler's notification count. `stream_request_notifications:` delivers them as + # they are emitted instead, for the requests `stream_modern_request?` selects. if notifications.empty? [modern_http_status(response), { "content-type" => "application/json" }, [response_json]] else @@ -1143,6 +1169,195 @@ def handle_modern(request, header_version, body_string: nil) ) end + # A response that cannot be generated answers its request with Internal error, as `JsonRpcHandler.handle_json` + # does on the legacy paths, instead of failing the whole exchange with a 500. Returns the response that was + # generated along with its JSON. + def modern_response_json(response) + [response, response.to_json] + rescue JSON::GeneratorError => e + MCP.configuration.exception_reporter.call(e, { error: "Failed to generate response" }) + response = JsonRpcHandler.encodable_response(response) + + [response, response.to_json] + end + + # The methods whose handlers report progress. + STREAMED_MODERN_METHODS = [Methods::TOOLS_CALL, Methods::PROMPTS_GET, Methods::RESOURCES_READ].freeze + private_constant :STREAMED_MODERN_METHODS + + # Whether this request is answered on an open SSE stream (`stream_request_notifications:`): one that asks for progress, + # of a method whose handler can report it. Opening the stream commits HTTP 200 before the handler runs, + # so every other request keeps the buffered exchange and the status its answer maps to. + # + # The answers the spec ties to a status of their own are therefore ruled out here, ahead of the stream, + # wherever they can be told without running the request: a request that is not valid JSON-RPC (400), + # a method the server does not implement (404), an envelope that is missing or malformed (400), + # and for a `tools/call` the header mismatch of SEP-2243 (400). + # The headers are checked only on a tool that is known without running the request: with a `tools_list_handler` + # the tool is the one the block returns for this very dispatch, which nothing ahead of the dispatch can stand in for. + # A tool that is not found, a disagreement, or an error while looking leaves the request to the buffered exchange, + # which answers it as it always has. What only the handler can decide, such as a client capability it finds missing, + # is answered on the stream. + def stream_modern_request?(body, request) + return false unless @stream_request_notifications + return false if body[:id].nil? || !STREAMED_MODERN_METHODS.include?(body[:method]) + return false unless JsonRpcHandler.valid_version?(body[:jsonrpc]) && JsonRpcHandler.valid_id?(body[:id]) + + params = body[:params] + meta = params[:_meta] if params.is_a?(Hash) + progress_token = meta[:progressToken] if meta.is_a?(Hash) + return false unless progress_token.is_a?(String) || progress_token.is_a?(Integer) + return false unless @server.implements_method?(body[:method]) + return false unless RequestEnvelope.modern?(params) + + RequestEnvelope.parse!(params, request: params) + return true unless body[:method] == Methods::TOOLS_CALL + + tool = @server.tool_known_ahead_of_dispatch(params[:name]) + + !tool.nil? && mcp_param_header_mismatch(tool, params, request).nil? + rescue StandardError + false + end + + # The Rack streaming body of a request served with `stream_request_notifications:`. As `ListenStreamBody`, + # it responds to `call` and not to `each`, and `first` turns the buffered-host mistake into guidance. + class RequestStreamBody + def initialize(&block) + @block = block + end + + def call(stream) + @block.call(stream) + end + + def first + raise <<~MESSAGE + The request was answered with a streaming SSE body, which cannot be buffered into a JSON response. \ + A host that cannot hold an SSE response open should construct the transport without `stream_request_notifications: true`. + See the Rails (controller) section at https://ruby.sdk.modelcontextprotocol.io/server/transports/ for the hosting patterns. + MESSAGE + end + end + private_constant :RequestStreamBody + + # Answers a request on an SSE stream that stays open while its handler runs. The handler runs inside the body, + # on the thread the host writes the response from, not on one of the transport's own: an application keeps + # its thread-bound state, and nothing outlives the response. + # + # The stream is the request's notification sink for as long as the handler runs, and the response is its last frame. + # A request whose response is suppressed (it was cancelled) ends the stream without one. + def streamed_modern_response(body, body_string, session, auth_info, tool_call_check) + response_body = RequestStreamBody.new do |stream| + sink = { stream: stream, session: session, write_mutex: Mutex.new, keepalive_wakeup: ConditionVariable.new } + + begin + @mutex.synchronize { @modern_request_sinks[session.session_id] = sink } + + start_request_stream_keepalive_thread(session.session_id, sink) + + response = @server.handle(body, session: session, auth_info: auth_info, tool_call_check: tool_call_check) + + finish_request_stream(sink, response) + rescue StandardError => e + MCP.configuration.exception_reporter.call(e, { request: body_string }) + + finish_request_stream(sink, { + jsonrpc: "2.0", + id: echoable_id(body[:id]), + error: { code: JsonRpcHandler::ErrorCode::INTERNAL_ERROR, message: "Internal server error" }, + }) + ensure + @mutex.synchronize do + @modern_request_sinks.delete(session.session_id) + sink[:keepalive_wakeup].signal + end + sink[:write_mutex].synchronize { sink[:closed] = true } + + close_stream_safely(stream) + end + end + + [200, SSE_HEADERS.dup, response_body] + end + + # Writes one frame to the response stream of a streamed request, under its write mutex so that it cannot land + # inside a keepalive or after the response. Returns whether the frame was written. + # + # A write that fails or stalls past `stream_write_timeout:` means the client is no longer reading. On this + # lifecycle closing the response stream is how a client cancels its request, so the request is cancelled: + # its handler observes it as it would `notifications/cancelled`, and nothing more is written. + def write_to_request_stream(sink, data) + guarded_request_stream_write(sink) { push_to_stream(sink[:stream], data, subscription: sink) } + end + + # The stream is marked closed before the write mutex is released, so a writer waiting on that mutex cannot put + # its frame after one that failed part way. The cancellation runs outside the mutex: it calls the hooks of + # the handler, which may themselves try to notify. + def guarded_request_stream_write(sink) + outcome = sink[:write_mutex].synchronize do + next :skipped if sink[:closed] + + begin + yield + + :written + rescue *STREAM_WRITE_ERRORS + sink[:closed] = true + + :failed + end + end + + sink[:session].cancel_all_incoming(reason: "The response stream was closed") if outcome == :failed + + outcome == :written + end + + # The response is written without the deadline of the frames above, as the response of any request is: + # it may be large, and it holds up no other stream. + def finish_request_stream(sink, response) + return if response.nil? + + _response, response_json = modern_response_json(response) + + sink[:write_mutex].synchronize do + next if sink[:closed] + + sink[:closed] = true + + send_to_stream(sink[:stream], response_json) + end + rescue *STREAM_WRITE_ERRORS + # The client went away before its response; there is no one left to answer. + end + + # Writes keepalive comment frames to the response stream of a streamed request while its handler is quiet, so + # an intermediary does not time the response out and a client that went away is noticed, and its request cancelled, + # without waiting for the next notification. Ends with the request: `streamed_modern_response` removes the sink and + # signals the wait. + def start_request_stream_keepalive_thread(session_id, sink) + return unless @listen_keepalive_interval + + Thread.new do + loop do + registered = @mutex.synchronize do + next false unless @modern_request_sinks[session_id].equal?(sink) + + sink[:keepalive_wakeup].wait(@mutex, @listen_keepalive_interval) + @modern_request_sinks[session_id].equal?(sink) + end + + break unless registered + + # A stream that is closed gets no more frames, so there is nothing left to keep alive. + break unless guarded_request_stream_write(sink) { push_ping_to_stream(sink[:stream], subscription: sink) } + end + rescue StandardError => e + MCP.configuration.exception_reporter.call(e, { session_id: session_id, error: "Request stream keepalive failed" }) + end + end + # Enforces the SEP-2575 header/body match rules (`-32020`, HTTP 400): the `MCP-Protocol-Version` header # MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST match # the body when sent. Absent mirror headers are tolerated for interoperability while other SDK serving stacks diff --git a/test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb b/test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb new file mode 100644 index 00000000..6606f851 --- /dev/null +++ b/test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb @@ -0,0 +1,594 @@ +# frozen_string_literal: true + +require "test_helper" +require "rack" + +module MCP + class Server + module Transports + # `stream_request_notifications:`: a 2026-07-28 request that asks for progress is answered on an SSE stream + # that carries each notification as its handler emits it. + class StreamableHTTPStreamRequestNotificationsTest < ActiveSupport::TestCase + # Hands each frame to a queue as it is written, so a test can wait for one while the handler is still running. + class FrameStream + attr_reader :frames + + def initialize(fail_writes_after: nil, block_writes_after: nil) + @frames = Queue.new + @written = [] + @closed = false + @fail_writes_after = fail_writes_after + @block_writes_after = block_writes_after + end + + def write(data) + raise IOError, "closed stream" if @closed + raise Errno::EPIPE if @fail_writes_after && @written.size >= @fail_writes_after + + sleep if @block_writes_after && @written.size >= @block_writes_after + + @written << data + @frames << data + end + + def flush + end + + def close + @closed = true + end + + def closed? + @closed + end + + def written + @written.dup + end + end + + setup do + @server = Server.new(name: "test_server", tools: [], prompts: [], resources: []) + @transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: nil) + end + + teardown do + @transport.close + end + + test "a notification reaches the stream while the handler is still running, and the response is the last frame" do + proceed = Queue.new + @server.define_tool(name: "slow") do |server_context:| + server_context.report_progress(1, total: 2) + proceed.pop + Tool::Response.new([{ type: "text", text: "done" }]) + end + + status, headers, body = post_tools_call("slow") + + assert_equal 200, status + assert_equal "text/event-stream", headers["content-type"] + refute_respond_to body, :each + + stream = FrameStream.new + handler = Thread.new { body.call(stream) } + progress = data_of(stream.frames.pop) + + assert_equal "notifications/progress", progress["method"] + assert_equal "token-1", progress.dig("params", "progressToken") + assert_predicate handler, :alive? + + proceed << true + handler.join + + response = data_of(stream.frames.pop) + assert_equal 7, response["id"] + assert_equal "done", response.dig("result", "content", 0, "text") + assert_equal 2, stream.written.size + assert_predicate stream, :closed? + end + + test "the handler runs on the thread that calls the body" do + # A mutex is owned by one thread only, so the handler sees it owned exactly when it runs on the caller's thread. + caller_lock = Mutex.new + on_caller_thread = nil + @server.define_tool(name: "where") do + on_caller_thread = caller_lock.owned? + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + _status, _headers, body = post_tools_call("where") + + assert_nil on_caller_thread + caller_lock.synchronize { body.call(FrameStream.new) } + assert on_caller_thread + end + + test "the setting is off by default and the notifications then arrive with the response" do + define_progress_tool("counted", notifications: 2) + transport = StreamableHTTPTransport.new(@server, listen_keepalive_interval: nil) + + status, headers, body = post_tools_call("counted", transport: transport) + + assert_equal 200, status + assert_equal "text/event-stream", headers["content-type"] + assert_equal 3, body[0].scan("event: message").size + ensure + transport.close + end + + test "a request without a progress token keeps the single JSON exchange" do + define_progress_tool("counted", notifications: 0) + + status, headers, body = post_tools_call("counted", progress_token: nil) + + assert_equal 200, status + assert_equal "application/json", headers["content-type"] + assert_equal "ok", JSON.parse(body[0]).dig("result", "content", 0, "text") + end + + test "a progress token that is neither a string nor an integer does not open a stream" do + define_progress_tool("counted", notifications: 0) + + [1.5, true, { a: 1 }, [1]].each do |token| + _status, headers, _body = post_tools_call("counted", progress_token: token) + + assert_equal "application/json", headers["content-type"], token.inspect + end + end + + test "a method outside tools/call, prompts/get and resources/read is not streamed" do + status, headers, body = post_modern("tools/list", { _meta: envelope.merge(progressToken: "token-1") }) + + assert_equal 200, status + assert_equal "application/json", headers["content-type"] + assert_equal [], JSON.parse(body[0]).dig("result", "tools") + end + + test "prompts/get and resources/read are streamed" do + @server.define_prompt(name: "greeting") do |_args, server_context:| + server_context.report_progress(1) + Prompt::Result.new(messages: []) + end + @server.resources = [Resource.new(uri: "test://a", name: "a")] + @server.resources_read_handler do |params, server_context:| + server_context.report_progress(1) + [{ uri: params[:uri], text: "a" }] + end + + { + "prompts/get" => [{ name: "greeting" }, { "HTTP_MCP_NAME" => "greeting" }], + "resources/read" => [{ uri: "test://a" }, { "HTTP_MCP_NAME" => "test://a" }], + }.each do |method, (params, headers)| + status, response_headers, body = post_modern(method, params.merge(_meta: envelope.merge(progressToken: 1)), headers: headers) + + assert_equal 200, status, method + assert_equal "text/event-stream", response_headers["content-type"], method + + stream = FrameStream.new + body.call(stream) + frames = stream.written.map { |frame| data_of(frame) } + + assert_equal "notifications/progress", frames[0]["method"], method + assert frames[1].key?("result"), "#{method}: #{frames[1]}" + end + end + + test "a header mismatch is refused with HTTP 400 before any stream is opened" do + ran = false + @server.define_tool( + name: "regional", + input_schema: { properties: { region: { type: "string", "x-mcp-header": "Region" } } }, + ) do |**_args| + ran = true + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + status, headers, body = post_tools_call("regional", arguments: { region: "us-west1" }, headers: { "HTTP_MCP_PARAM_REGION" => "us-east1" }) + + assert_equal 400, status + assert_equal "application/json", headers["content-type"] + assert_equal ErrorCodes::HEADER_MISMATCH, JSON.parse(body[0]).dig("error", "code") + refute ran + + status, headers, body = post_tools_call("regional", arguments: { region: "us-west1" }, headers: { "HTTP_MCP_PARAM_REGION" => "us-west1" }) + + assert_equal 200, status + assert_equal "text/event-stream", headers["content-type"] + body.call(FrameStream.new) + assert ran + end + + test "an unknown tool is answered as it is without the setting" do + plain = StreamableHTTPTransport.new(@server, listen_keepalive_interval: nil) + + assert_equal post_tools_call("missing", transport: plain), post_tools_call("missing") + ensure + plain.close + end + + test "with a tools_list_handler a tools/call is not streamed and the handler is asked once" do + tool = Tool.define(name: "listed") do |server_context:| + server_context.report_progress(1) + Tool::Response.new([{ type: "text", text: "ok" }]) + end + asked = 0 + @server.tools_list_handler do |_params| + asked += 1 + [tool] + end + plain = StreamableHTTPTransport.new(@server, listen_keepalive_interval: nil) + + hidden = post_tools_call("hidden") + listed = post_tools_call("listed") + + assert_equal post_tools_call("hidden", transport: plain), hidden + assert_equal 200, listed[0] + assert_kind_of Array, listed[2] + assert_equal 2, listed[2][0].scan("event: message").size + assert_equal 3, asked + ensure + plain.close + end + + test "a method the server does not implement keeps its 404" do + server = Server.new(name: "no_prompts", capabilities: { tools: {} }) + transport = StreamableHTTPTransport.new(server, stream_request_notifications: true, listen_keepalive_interval: nil) + + status, headers, body = post_modern("prompts/get", { name: "x", _meta: envelope.merge(progressToken: 1) }, headers: { "HTTP_MCP_NAME" => "x" }, transport: transport) + + assert_equal 404, status + assert_equal "application/json", headers["content-type"] + assert_equal JsonRpcHandler::ErrorCode::METHOD_NOT_FOUND, JSON.parse(body[0]).dig("error", "code") + ensure + transport.close + end + + test "a request that is not valid JSON-RPC keeps its 400" do + define_progress_tool("counted", notifications: 1) + plain = StreamableHTTPTransport.new(@server, listen_keepalive_interval: nil) + params = { name: "counted", _meta: envelope.merge(progressToken: 1) } + headers = { "HTTP_MCP_NAME" => "counted" } + + [{ jsonrpc: "1.0" }, { jsonrpc: nil }, { id: true }, { id: 1.5 }, { id: { a: 1 } }].each do |framing| + status, response_headers, body = post_modern("tools/call", params, headers: headers, framing: framing) + + assert_equal 400, status, framing.inspect + assert_equal "application/json", response_headers["content-type"], framing.inspect + assert_equal JsonRpcHandler::ErrorCode::INVALID_REQUEST, JSON.parse(body[0]).dig("error", "code"), framing.inspect + assert_equal post_modern("tools/call", params, headers: headers, framing: framing, transport: plain), [status, response_headers, body] + end + ensure + plain.close + end + + test "an envelope missing a required member keeps its 400" do + define_progress_tool("counted", notifications: 1) + meta = envelope.merge(progressToken: 1) + meta.delete(:"io.modelcontextprotocol/clientCapabilities") + + status, headers, body = post_modern("tools/call", { name: "counted", _meta: meta }, headers: { "HTTP_MCP_NAME" => "counted" }) + + assert_equal 400, status + assert_equal "application/json", headers["content-type"] + assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, JSON.parse(body[0]).dig("error", "code") + end + + test "an error the dispatch finds after the stream is opened is its last frame" do + define_progress_tool("counted", notifications: 0) + + status, headers, body = post_tools_call("counted", arguments: "not an object") + + assert_equal 200, status + assert_equal "text/event-stream", headers["content-type"] + + stream = FrameStream.new + body.call(stream) + + assert_equal 1, stream.written.size + assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, data_of(stream.written[0]).dig("error", "code") + end + + test "a client capability the handler finds missing is answered on the stream" do + @server.define_tool(name: "asks") do |server_context:| + server_context.require_client_capability!(:elicitation, :form) + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + status, _headers, body = post_tools_call("asks") + stream = FrameStream.new + body.call(stream) + + assert_equal 200, status + assert_equal 1, stream.written.size + assert_equal ErrorCodes::MISSING_REQUIRED_CLIENT_CAPABILITY, data_of(stream.written[0]).dig("error", "code") + end + + test "an exception inside the body is reported, answered as an internal error, and leaves nothing behind" do + define_progress_tool("counted", notifications: 0) + _status, _headers, body = post_tools_call("counted") + @server.stubs(:handle).raises(RuntimeError, "boom") + reported = [] + MCP.configuration.stubs(:exception_reporter).returns(->(error, context) { reported << [error.message, context[:request].class] }) + + stream = FrameStream.new + body.call(stream) + + assert_equal [["boom", String]], reported + assert_equal 1, stream.written.size + error = data_of(stream.written[0]) + assert_equal 7, error["id"] + assert_equal JsonRpcHandler::ErrorCode::INTERNAL_ERROR, error.dig("error", "code") + refute_includes stream.written[0], "boom" + assert_predicate stream, :closed? + assert_empty @transport.instance_variable_get(:@modern_request_sinks) + end + + test "a keepalive thread that cannot be started does not leave the sink or the stream behind" do + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: 0.02) + define_progress_tool("counted", notifications: 0) + _status, _headers, body = post_tools_call("counted", transport: transport) + transport.stubs(:start_request_stream_keepalive_thread).raises(ThreadError, "can't create Thread") + MCP.configuration.stubs(:exception_reporter).returns(->(_error, _context) {}) + + stream = FrameStream.new + body.call(stream) + + assert_equal JsonRpcHandler::ErrorCode::INTERNAL_ERROR, data_of(stream.written[0]).dig("error", "code") + assert_predicate stream, :closed? + assert_empty transport.instance_variable_get(:@modern_request_sinks) + ensure + transport.close + end + + test "a frame waiting behind a write that fails is not written after it" do + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: nil) + sink = { stream: nil, session: ServerSession.new(server: @server, transport: transport, session_id: "s", era: :modern), write_mutex: Mutex.new } + entered = Queue.new + release = Queue.new + second_ran = false + + first = Thread.new do + transport.send(:guarded_request_stream_write, sink) do + entered << true + release.pop + raise Errno::EPIPE + end + end + entered.pop + second = Thread.new { transport.send(:guarded_request_stream_write, sink) { second_ran = true } } + + # The first write holds the mutex, so the second can only be waiting on it once it sleeps. + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 + sleep(0.01) until second.status != "run" || Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline + assert_equal "sleep", second.status + release << true + + refute first.value + refute second.value + refute second_ran + assert sink[:closed] + ensure + release << true + [first, second].compact.each { |thread| thread.join(2) || thread.kill } + transport.close + end + + test "notifications past the buffered limit are all delivered" do + count = StreamableHTTPTransport::MAX_MODERN_REQUEST_NOTIFICATIONS + 5 + define_progress_tool("counted", notifications: count) + + _status, _headers, body = post_tools_call("counted") + stream = FrameStream.new + body.call(stream) + + assert_equal count + 1, stream.written.size + assert_equal count, data_of(stream.written[-2]).dig("params", "progress") + end + + test "a failed write cancels the request, and nothing more is written" do + cancelled = nil + delivered = [] + @server.define_tool(name: "watched") do |server_context:| + delivered << server_context.report_progress(1) + delivered << server_context.report_progress(2) + cancelled = server_context.cancelled? + delivered << server_context.report_progress(3) + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + _status, _headers, body = post_tools_call("watched") + stream = FrameStream.new(fail_writes_after: 1) + body.call(stream) + + assert cancelled + assert_equal 1, stream.written.size + assert_equal "notifications/progress", data_of(stream.written[0])["method"] + assert_predicate stream, :closed? + end + + test "a write that stalls past stream_write_timeout cancels the request" do + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: nil, stream_write_timeout: 0.05) + cancelled = nil + @server.define_tool(name: "stalled") do |server_context:| + server_context.report_progress(1) + cancelled = server_context.cancelled? + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + _status, _headers, body = post_tools_call("stalled", transport: transport) + stream = FrameStream.new(block_writes_after: 0) + body.call(stream) + + assert cancelled + assert_empty stream.written + assert_predicate stream, :closed? + ensure + transport.close + end + + test "keepalive comment frames are written while the handler is quiet and stop with the request" do + # Without a write deadline, so the only thread the request may start is its keepalive. + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: 0.02, stream_write_timeout: nil) + proceed = Queue.new + @server.define_tool(name: "quiet") do + proceed.pop + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + _status, _headers, body = post_tools_call("quiet", transport: transport) + stream = FrameStream.new + threads_before = Thread.list + handler = Thread.new { body.call(stream) } + + assert_match(/\A: ping /, stream.frames.pop) + + proceed << true + handler.join + + assert data_of(stream.written.last).key?("result") + assert(stream.written[0..-2].all? { |frame| frame.start_with?(": ping ") }) + assert_empty wait_for_threads_to_end(Thread.list - threads_before - [handler]) + ensure + transport.close + end + + test "a keepalive that cannot be written cancels the request" do + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: 0.02) + cancelled = Queue.new + @server.define_tool(name: "abandoned") do |server_context:| + sleep(0.01) until server_context.cancelled? + cancelled << true + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + _status, _headers, body = post_tools_call("abandoned", transport: transport) + stream = FrameStream.new(fail_writes_after: 0) + handler = Thread.new { body.call(stream) } + + assert cancelled.pop + handler.join + assert_empty stream.written + ensure + transport.close + end + + test "concurrent requests each receive only their own notifications" do + gates = { "a" => Queue.new, "b" => Queue.new } + @server.define_tool(name: "tagged", input_schema: { properties: { tag: { type: "string" } } }) do |tag:, server_context:| + gates[tag].pop + server_context.report_progress(1, message: tag) + server_context.notify_log_message(data: tag, level: "info") + Tool::Response.new([{ type: "text", text: tag }]) + end + + runs = ["a", "b"].map do |tag| + _status, _headers, body = post_tools_call("tagged", arguments: { tag: tag }, progress_token: "token-#{tag}", log_level: "info") + stream = FrameStream.new + [tag, stream, Thread.new { body.call(stream) }] + end + @server.notify_tools_list_changed + gates.each_value { |gate| gate << true } + runs.each { |_tag, _stream, thread| thread.join } + + runs.each do |tag, stream, _thread| + frames = stream.written.map { |frame| data_of(frame) } + + assert_equal ["notifications/progress", "notifications/message", nil], frames.map { |frame| frame["method"] } + assert_equal tag, frames[0].dig("params", "message") + assert_equal "token-#{tag}", frames[0].dig("params", "progressToken") + assert_equal tag, frames[1].dig("params", "data") + assert_equal tag, frames[2].dig("result", "content", 0, "text") + end + end + + test "a notification sent after the response is not written" do + late = nil + @server.define_tool(name: "leaky") do |server_context:| + late = server_context + Tool::Response.new([{ type: "text", text: "ok" }]) + end + + _status, _headers, body = post_tools_call("leaky") + stream = FrameStream.new + body.call(stream) + late.report_progress(9) + + assert_equal 1, stream.written.size + assert_empty @transport.instance_variable_get(:@modern_request_sinks) + end + + test "the body explains itself to a host that tries to buffer it" do + define_progress_tool("counted", notifications: 0) + + _status, _headers, body = post_tools_call("counted") + error = assert_raises(RuntimeError) { body.first } + + assert_includes error.message, "stream_request_notifications" + end + + test "the setting cannot be combined with serve_subscriptions_listen: false" do + error = assert_raises(ArgumentError) do + StreamableHTTPTransport.new(@server, stream_request_notifications: true, serve_subscriptions_listen: false) + end + + assert_includes error.message, "serve_subscriptions_listen: false" + end + + private + + def define_progress_tool(name, notifications:) + @server.define_tool(name: name) do |server_context:| + notifications.times { |index| server_context.report_progress(index + 1) } + Tool::Response.new([{ type: "text", text: "ok" }]) + end + end + + def post_tools_call(name, arguments: nil, progress_token: "token-1", log_level: nil, headers: {}, transport: @transport) + meta = envelope + meta[:progressToken] = progress_token unless progress_token.nil? + meta[:"io.modelcontextprotocol/logLevel"] = log_level if log_level + params = { name: name, _meta: meta } + params[:arguments] = arguments unless arguments.nil? + + post_modern("tools/call", params, headers: { "HTTP_MCP_NAME" => name }.merge(headers), transport: transport) + end + + # `framing` replaces members of the JSON-RPC request itself; a member given as nil is left out. + def post_modern(method, params, headers: {}, transport: @transport, framing: {}) + request = { jsonrpc: "2.0", id: 7, method: method, params: params }.merge(framing).compact + env = { + "REQUEST_METHOD" => "POST", + "PATH_INFO" => "/", + "HTTP_ACCEPT" => "application/json, text/event-stream", + "CONTENT_TYPE" => "application/json", + "HTTP_MCP_PROTOCOL_VERSION" => "2026-07-28", + "HTTP_MCP_METHOD" => method, + "rack.input" => StringIO.new(request.to_json), + }.merge(headers) + + transport.handle_request(Rack::Request.new(env)) + end + + def envelope + { + "io.modelcontextprotocol/protocolVersion": "2026-07-28", + "io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" }, + "io.modelcontextprotocol/clientCapabilities": {}, + } + end + + def data_of(frame) + JSON.parse(frame[/^data: (.*)$/, 1]) + end + + def wait_for_threads_to_end(threads) + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 2 + sleep(0.01) while threads.any?(&:alive?) && Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline + + threads.select(&:alive?) + end + end + end + end +end