From 60d4fe2339f4ce6b1cf629fcb1f248a231f1a1c4 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 27 Nov 2026 12:24:03 +0900 Subject: [PATCH] Bound the write of the response of a streamed request ## Motivation and Context With `stream_request_notifications: true`, the notifications and keepalives of a streamed request each wait for the client for at most `stream_write_timeout:` seconds, but the response that ends the stream was written without any deadline, since it may be large. The stream of a 2026-07-28 request belongs to no session, so nothing else ends it either: a client that stopped reading held the thread serving the request, and the keepalive thread waiting on the stream's write mutex, until it closed the connection. The response is now written in pieces of 64 KiB, each given `stream_write_timeout:` seconds. A client that takes each piece in that time receives all of it however long the whole takes, and one that does not is dropped as it is for any other frame. `stream_write_timeout: nil` still waits without limit. ## How Has This Been Tested? `test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb`. Against the previous library the request of a client that does not read never ends. ## Breaking Changes None. --- docs/_server/transports.md | 2 + .../transports/streamable_http_transport.rb | 34 +++++++-- ..._http_stream_request_notifications_test.rb | 74 +++++++++++++++++++ 3 files changed, 103 insertions(+), 7 deletions(-) diff --git a/docs/_server/transports.md b/docs/_server/transports.md index f92a632e..2c9ef846 100644 --- a/docs/_server/transports.md +++ b/docs/_server/transports.md @@ -256,6 +256,8 @@ Its response is an SSE stream that stays open until the result, which is the las 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. +The result is written in pieces of 64 KiB, each with the same wait: a large result reaches a client that takes each piece in that time, +however long the whole takes, and a client that does not is dropped. 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. diff --git a/lib/mcp/server/transports/streamable_http_transport.rb b/lib/mcp/server/transports/streamable_http_transport.rb index d8b38565..7a229e60 100644 --- a/lib/mcp/server/transports/streamable_http_transport.rb +++ b/lib/mcp/server/transports/streamable_http_transport.rb @@ -446,6 +446,10 @@ class StreamWriteTimeoutError < IOError; end # one that still has not taken the frame after this long is dropped whether it stopped reading or is only that slow. DEFAULT_STREAM_WRITE_TIMEOUT = 10 + # How much of the response of a streamed request is written under one `stream_write_timeout:` deadline. + RESPONSE_FRAME_PIECE_BYTES = 64 * 1024 + private_constant :RESPONSE_FRAME_PIECE_BYTES + # 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. @@ -1000,11 +1004,14 @@ def reap_expired_sessions # One `write` per frame, so the frames of concurrent writers cannot interleave in the middle of each other. def send_to_stream(stream, data, event_id: nil) + stream.write(sse_frame(data, event_id: event_id)) + stream.flush + end + + def sse_frame(data, event_id: nil) message = data.is_a?(String) ? data : data.to_json - frame = event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n" - stream.write(frame) - stream.flush + event_id ? "id: #{event_id}\ndata: #{message}\n\n" : "data: #{message}\n\n" end # The priming event of SEP-1699: an id for the client to resume from, the `retry` field when configured, and @@ -1321,22 +1328,35 @@ def guarded_request_stream_write(sink) 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. + # The response may be large, so it is not held to one deadline as the frames above are: it is written in pieces, + # each given `stream_write_timeout:` seconds. A client that takes each piece in that time receives all of it, + # however long the whole takes, and one that does not is dropped. Nothing else would end this stream: it belongs + # to no session, so until the write returns it holds the thread that serves the request and the keepalive waiting + # on the mutex. def finish_request_stream(sink, response) return if response.nil? _response, response_json = modern_response_json(response) + frame = sse_frame(response_json) sink[:write_mutex].synchronize do next if sink[:closed] sink[:closed] = true - send_to_stream(sink[:stream], response_json) + stream = sink[:stream] + offset = 0 + + while offset < frame.bytesize + piece = frame.byteslice(offset, RESPONSE_FRAME_PIECE_BYTES) + within_stream_write_timeout(stream, sink) { stream.write(piece) } + offset += piece.bytesize + end + + within_stream_write_timeout(stream, sink) { stream.flush } end rescue *STREAM_WRITE_ERRORS - # The client went away before its response; there is no one left to answer. + # The client went away before its response, or stopped reading it; 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 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 index 6606f851..97c62ced 100644 --- a/test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb +++ b/test/mcp/server/transports/streamable_http_stream_request_notifications_test.rb @@ -427,6 +427,80 @@ def written transport.close end + test "a response the client does not read ends the request after stream_write_timeout" do + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: 0.02, stream_write_timeout: 0.05) + @server.define_tool(name: "unread") { Tool::Response.new([{ type: "text", text: "ok" }]) } + + _status, _headers, body = post_tools_call("unread", transport: transport) + stream = FrameStream.new(block_writes_after: 0) + threads_before = Thread.list + handler = Thread.new { body.call(stream) } + + assert handler.join(2), "the request is still waiting for a client that does not read" + assert_empty stream.written + assert_predicate stream, :closed? + assert_empty transport.instance_variable_get(:@modern_request_sinks) + assert_empty wait_for_threads_to_end(Thread.list - threads_before - [handler]) + ensure + handler&.kill + transport.close + end + + test "a response the client stops reading part way is cut there, and nothing is written after it" do + text = "x" * (4 * 64 * 1024) + @server.define_tool(name: "large") { Tool::Response.new([{ type: "text", text: text }]) } + stalled_flush = Class.new(FrameStream) do + def flush + sleep + end + end + streams = { + "a write that stalls after two pieces" => [FrameStream.new(block_writes_after: 2), 2], + "a flush that stalls" => [stalled_flush.new, 5], + } + + streams.each do |label, (stream, pieces)| + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: 0.02, stream_write_timeout: 0.05) + _status, _headers, body = post_tools_call("large", transport: transport) + threads_before = Thread.list + handler = Thread.new { body.call(stream) } + + assert handler.join(2), label + assert_equal pieces, stream.written.size, label + assert_predicate stream, :closed?, label + assert_empty transport.instance_variable_get(:@modern_request_sinks), label + # Whether or not the keepalive reached the write mutex while the response was being written, it ends without writing. + assert_empty wait_for_threads_to_end(Thread.list - threads_before - [handler]), label + assert(stream.written.none? { |piece| piece.start_with?(": ping ") }, label) + ensure + handler&.kill + transport&.close + end + end + + test "a large response reaches a client that takes longer than stream_write_timeout to read all of it" do + transport = StreamableHTTPTransport.new(@server, stream_request_notifications: true, listen_keepalive_interval: nil, stream_write_timeout: 0.1) + # Three bytes a character, so pieces end inside one. + text = "\u3042" * (2 * 64 * 1024) + @server.define_tool(name: "large") { Tool::Response.new([{ type: "text", text: text }]) } + slow_stream = Class.new(FrameStream) do + def write(data) + sleep(0.03) + super + end + end + + _status, _headers, body = post_tools_call("large", transport: transport) + stream = slow_stream.new + body.call(stream) + + assert_operator stream.written.size, :>=, 5 + assert(stream.written.all? { |piece| piece.bytesize <= 64 * 1024 }) + assert_equal text, data_of(stream.written.join).dig("result", "content", 0, "text") + 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)