Skip to content

Commit da2a7f8

Browse files
committed
Stream modern request notifications and honor the envelope logLevel per SEP-2575
## Motivation and Context The modern (stateless) lifecycle of MCP 2026-07-28 serves each request as a self-contained exchange, and two delivery requirements of that model were unimplemented: - Notifications a handler emits while serving a modern request (progress, log messages) had nowhere to go: the modern path answered with a single JSON object, and the ephemeral per-request session degraded every notification to non-delivery. The conformance requirement expects them as frames on the request's own response stream (`tools-call-with-progress` fails with "No progress notifications received" at 2026-07-28). - The envelope's `logLevel` member, which replaces the removed `logging/setLevel` RPC, was parsed but never applied: log delivery fell back to the server-wide level, violating the requirement that no `notifications/message` is sent for requests that did not set `_meta` `logLevel`. The changes wire both up: - `StreamableHTTPTransport#handle_modern` registers a per-request notification sink for its ephemeral session; `send_notification` routes into the sink ahead of the stateless guard. A request whose handler emitted notifications answers as an SSE stream carrying them ahead of the final response; a request that emitted none keeps the single JSON exchange and its HTTP status ladder. - `Server#handle_request` applies the lifted envelope's `logLevel` to the session via the existing `configure_logging`, and on modern-era sessions `ServerSession#notify_log_message` no longer falls back to the server-wide level: without a per-request `logLevel` it stays silent, on every transport. An unrecognized level reads as absent, the safe direction, matching the Python SDK's `allowed_log_levels`. The `server-stateless` scenario of the 2026-07-28 conformance requirements probes two stream-discipline rules through diagnostic fixture tools the Ruby fixture did not define, so both checks failed as not testable: `sep-2575-http-server-no-independent-requests-on-stream` calls `test_streaming_elicitation` and requires that every frame on the request's response stream is a notification or the final response, and `sep-2575-server-no-log-without-loglevel` calls `test_logging_tool` without an envelope `logLevel` and requires that no `notifications/message` reaches the stream. The fixture now defines both tools. `test_streaming_elicitation` reports progress and completes; `test_logging_tool` calls `notify_log_message` unconditionally and relies on the SDK's per-request gate, which drops the notification for modern requests that did not authorize logging through `io.modelcontextprotocol/logLevel`. Both lean on the notification streaming this change adds: with a `progressToken` or an authorizing `logLevel`, the notification is delivered as an SSE frame ahead of the final response rather than being dropped. One known limitation relative to the TypeScript and Python SDKs, which stream notifications live while the handler runs: delivery here is buffered, flushing the frames after the handler returns. Ordering is preserved and the conformance checks are satisfied, but long-running handlers get no real-time interleaving. The sink is bounded (`MAX_MODERN_REQUEST_NOTIFICATIONS`, 1000): a handler emitting notifications in proportion to client-supplied input cannot grow one request's memory without bound, and past the cap the notify helpers report `false`, the same non-delivery degradation they have on every other undeliverable path. Live streaming can follow without changing the wire shape. ## How Has This Been Tested? `bundle exec rake test` passes with zero failures and RuboCop reports no offenses. New tests cover: a modern `tools/call` streaming `notifications/progress` frames ahead of the result, the single JSON exchange staying in place without notifications, log suppression without the envelope `logLevel`, log delivery with it, the modern-era session ignoring the server-wide level while honoring a per-request one, and the notification cap bounding one request's buffered frames while the notify helpers report `false` past it. Against the conformance fixture server, the `tools-call-with-progress` progress check passes at `--spec-version 2026-07-28` (its remaining wire-schema check belongs to the separate `resultType` change), the stream-discipline checks `sep-2575-http-server-no-independent-requests-on-stream` and `sep-2575-server-no-log-without-loglevel` report SUCCESS, and manual probes confirm the positive directions the suite leaves untested: with `io.modelcontextprotocol/logLevel` in `_meta`, `test_logging_tool` streams its `notifications/message` frame ahead of the result, and with a `progressToken`, `test_streaming_elicitation` streams its `notifications/progress` frame. The `--requirements 2025-11-25` server leg passes 78/78, unchanged. ## Breaking Changes None for stable protocol versions: legacy requests and their notification delivery are unchanged. Within the modern lifecycle, notifications become deliverable where they were previously dropped, and log messages without a per-request `logLevel` stop leaking through the server-wide level, as the specification requires.
1 parent 8e30f32 commit da2a7f8

6 files changed

Lines changed: 286 additions & 8 deletions

File tree

‎conformance/server.rb‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,21 @@ def call(server_context:, **_args)
344344
end
345345
end
346346

347+
class TestStreamingElicitation < MCP::Tool
348+
tool_name "test_streaming_elicitation"
349+
description "A tool whose response stream carries only notifications, never independent requests (SEP-2575)"
350+
351+
class << self
352+
def call(server_context:, **_args)
353+
# No independent server-to-client request is ever written to the response stream;
354+
# the progress notification only goes out when the request carried a progressToken.
355+
server_context.report_progress(50, total: 100)
356+
357+
MCP::Tool::Response.new([MCP::Content::Text.new("Streaming complete").to_h])
358+
end
359+
end
360+
end
361+
347362
class TestInputRequiredResultElicitation < MCP::Tool
348363
tool_name "test_input_required_result_elicitation"
349364
description "A tool that asks for the user's name through an input_required result (SEP-2322)"
@@ -609,6 +624,21 @@ def call(server_context:, **_args)
609624
end
610625
end
611626
end
627+
628+
class TestLoggingTool < MCP::Tool
629+
tool_name "test_logging_tool"
630+
description "A tool that logs only for requests opting in via the _meta logLevel (SEP-2575)"
631+
632+
class << self
633+
def call(server_context:, **_args)
634+
# On modern requests the notification is dropped unless `io.modelcontextprotocol/logLevel` authorized it,
635+
# so the call itself is unconditional.
636+
server_context.notify_log_message(data: "Log level honored", level: "info", logger: "conformance")
637+
638+
MCP::Tool::Response.new([MCP::Content::Text.new("Logging evaluated").to_h])
639+
end
640+
end
641+
end
612642
end
613643

614644
module Prompts
@@ -846,6 +876,8 @@ def build_server
846876
Tools::TestInputRequiredResultMultipleInputs,
847877
Tools::TestInputRequiredResultMultiRound,
848878
Tools::TestInputRequiredResultCapabilities,
879+
Tools::TestStreamingElicitation,
880+
Tools::TestLoggingTool,
849881
],
850882
prompts: [
851883
Prompts::TestSimplePrompt,

‎lib/mcp/server.rb‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,16 @@ def handle_request(request, method, session: nil, related_request_id: nil)
584584
exception_already_reported: ->(e) { reported_exception.equal?(e) },
585585
) do
586586
envelope = lift_request_envelope(params, method: method, session: session)
587+
588+
# The envelope's `logLevel` member replaces `logging/setLevel` in the modern lifecycle:
589+
# it authorizes `notifications/message` for this request only (SEP-2575). Without it,
590+
# `ServerSession#notify_log_message` stays silent on modern-era sessions. An unrecognized level
591+
# reads as absent, so delivery stays off (the safe direction), matching the Python SDK.
592+
if envelope&.log_level && session.respond_to?(:configure_logging)
593+
request_logging = LoggingMessageNotification.new(level: envelope.log_level)
594+
session.configure_logging(request_logging) if request_logging.valid_level?
595+
end
596+
587597
result = case method
588598
when Methods::INITIALIZE
589599
init(params, session: session)

‎lib/mcp/server/transports/streamable_http_transport.rb‎

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,13 @@ class InvalidJsonError < StandardError; end
5151
# the stack or amplify parse cost (complements the byte cap).
5252
MAX_JSON_NESTING = 64
5353

54+
# Cap on the notifications buffered for one modern request (SEP-2575). The sink holds them
55+
# in memory until the handler returns, so a handler that emits notifications in proportion to
56+
# client-supplied input would otherwise let one request grow memory without bound.
57+
# Notifications past the cap are not delivered and the notify helpers report `false`,
58+
# the same non-delivery degradation they have on every other undeliverable path.
59+
MAX_MODERN_REQUEST_NOTIFICATIONS = 1_000
60+
5461
# Creates a Streamable HTTP transport that can be mounted as a Rack app.
5562
#
5663
# @param server [MCP::Server] the server whose requests this transport dispatches.
@@ -107,6 +114,10 @@ def initialize(
107114
@allowed_origins = Array(allowed_origins).map(&:downcase).freeze
108115
@pending_responses = {}
109116

117+
# Maps a modern request's ephemeral session id to the Array collecting the notifications its handler emits;
118+
# `handle_modern` registers the sink and flushes it as SSE frames ahead of the final response (SEP-2575).
119+
@modern_request_sinks = {}
120+
110121
# Resolve the idle timeout: an explicit value (including `nil` to opt out) wins; otherwise apply the secure default,
111122
# which does not apply to stateless mode since it retains no sessions.
112123
@session_idle_timeout = if session_idle_timeout.equal?(UNSET_IDLE_TIMEOUT)
@@ -235,17 +246,30 @@ def close
235246
end
236247

237248
def send_notification(method, params = nil, session_id: nil, related_request_id: nil)
238-
# Stateless mode has no streams to deliver notifications on. Report non-delivery instead of raising
239-
# so the ephemeral per-request session's notify_* helpers (e.g. progress or log notifications from
240-
# a tool handler) degrade gracefully rather than spamming the exception reporter on every call.
241-
return false if @stateless
242-
243249
notification = {
244250
jsonrpc: "2.0",
245251
method: method,
246252
}
247253
notification[:params] = params if params
248254

255+
# A modern request's notifications ride its own response stream (SEP-2575): `handle_modern` registers
256+
# a per-request sink for its ephemeral session and flushes it as SSE frames ahead of the final response.
257+
# Checked before the stateless guard, since modern requests are served in stateless deployments too.
258+
# The sink is bounded; past `MAX_MODERN_REQUEST_NOTIFICATIONS` the notification is dropped as
259+
# non-delivery (`false`), never handed to the legacy paths below.
260+
sink = @mutex.synchronize { session_id && @modern_request_sinks[session_id] }
261+
if sink
262+
return false if sink.size >= MAX_MODERN_REQUEST_NOTIFICATIONS
263+
264+
sink << notification
265+
return true
266+
end
267+
268+
# Stateless mode has no streams to deliver notifications on. Report non-delivery instead of raising
269+
# so the ephemeral per-request session's notify_* helpers (e.g. progress or log notifications from
270+
# a tool handler) degrade gracefully rather than spamming the exception reporter on every call.
271+
return false if @stateless
272+
249273
if session_id
250274
deliver_targeted_notification(notification, session_id, related_request_id)
251275
else
@@ -564,12 +588,29 @@ def handle_modern(request, header_version, body_string: nil)
564588
mismatch_error = validate_modern_headers(request, body, header_version)
565589
return mismatch_error if mismatch_error
566590

567-
response = @server.handle(body, session: modern_session)
591+
session = modern_session
592+
notifications = @mutex.synchronize { @modern_request_sinks[session.session_id] = [] }
593+
begin
594+
response = @server.handle(body, session: session)
595+
ensure
596+
@mutex.synchronize { @modern_request_sinks.delete(session.session_id) }
597+
end
568598

569599
# `nil` covers notifications and cancellation-suppressed responses; ack with 202 like the legacy notification path.
570600
return handle_accepted if response.nil?
571601

572-
[modern_http_status(response), { "content-type" => "application/json" }, [response.to_json]]
602+
# Notifications a handler emitted during the request ride the request's own response stream as SSE frames ahead of
603+
# the final response (SEP-2575); a request that emitted none keeps the single JSON exchange and its HTTP status ladder.
604+
# Delivery is buffered: frames flush after the handler returns, preserving order but not real-time interleaving
605+
# (the TypeScript and Python SDKs stream live), and the sink grows with the handler's notification count.
606+
# Live streaming can follow without changing the wire shape.
607+
if notifications.empty?
608+
[modern_http_status(response), { "content-type" => "application/json" }, [response.to_json]]
609+
else
610+
frames = notifications + [response]
611+
sse_body = frames.map { |frame| "event: message\ndata: #{frame.to_json}\n\n" }.join
612+
[200, SSE_HEADERS.dup, [sse_body]]
613+
end
573614
rescue StandardError => e
574615
MCP.configuration.exception_reporter.call(e, { request: body_string })
575616
json_rpc_error_response(

‎lib/mcp/server_session.rb‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,15 @@ def notify_progress(progress_token:, progress:, total: nil, message: nil, relate
252252
def notify_log_message(data:, level:, logger: nil, related_request_id: nil)
253253
@server.send(:warn_if_deprecated_protocol_feature, :logging, session: self, uplevel: 2)
254254

255-
effective_logging = @logging_message_notification || @server.logging_message_notification
255+
# In the modern lifecycle, log delivery is authorized per request through the `_meta` envelope's `logLevel` member
256+
# (applied via `configure_logging`); without it no `notifications/message` is sent, and the server-wide level
257+
# does not apply (SEP-2575).
258+
effective_logging = if @era == :modern
259+
@logging_message_notification
260+
else
261+
@logging_message_notification || @server.logging_message_notification
262+
end
263+
256264
return unless effective_logging&.should_notify?(level)
257265

258266
params = { "data" => data, "level" => level }

‎test/mcp/server/transports/streamable_http_transport_test.rb‎

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5418,6 +5418,168 @@ def string
54185418
assert_equal({ "elicitation" => { "form" => {} } }, body.dig("error", "data", "requiredCapabilities"))
54195419
end
54205420

5421+
test "modern POST streams handler notifications ahead of the final response" do
5422+
@server.define_tool(name: "progress_tool") do |server_context:|
5423+
server_context.report_progress(50, total: 100)
5424+
Tool::Response.new([{ type: "text", text: "done" }])
5425+
end
5426+
5427+
body = {
5428+
jsonrpc: "2.0",
5429+
method: "tools/call",
5430+
id: 1,
5431+
params: {
5432+
name: "progress_tool",
5433+
arguments: {},
5434+
_meta: {
5435+
progressToken: "tok-1",
5436+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
5437+
"io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" },
5438+
"io.modelcontextprotocol/clientCapabilities": {},
5439+
},
5440+
},
5441+
}.to_json
5442+
5443+
response = @transport.handle_request(modern_rack_request(body))
5444+
5445+
assert_equal 200, response[0]
5446+
assert_equal "text/event-stream", response[1]["content-type"]
5447+
frames = response[2][0].split("\n\n").reject(&:empty?).map do |chunk|
5448+
JSON.parse(chunk.sub(/\Aevent: message\ndata: /, ""))
5449+
end
5450+
assert_equal "notifications/progress", frames.first["method"]
5451+
assert_equal "tok-1", frames.first.dig("params", "progressToken")
5452+
assert frames.last.key?("result"), "expected the final frame to carry the result"
5453+
assert_equal 1, frames.last["id"]
5454+
end
5455+
5456+
test "modern POST bounds the buffered notifications per request" do
5457+
# The sink holds notifications in memory until the handler returns, so a handler
5458+
# emitting in proportion to client input must not grow one request without bound.
5459+
overflow = 5
5460+
delivery_results = []
5461+
@server.define_tool(name: "flood_tool") do |server_context:|
5462+
(StreamableHTTPTransport::MAX_MODERN_REQUEST_NOTIFICATIONS + overflow).times do |i|
5463+
delivery_results << server_context.notify_log_message(data: "message #{i}", level: "info")
5464+
end
5465+
Tool::Response.new([{ type: "text", text: "done" }])
5466+
end
5467+
5468+
body = {
5469+
jsonrpc: "2.0",
5470+
method: "tools/call",
5471+
id: 1,
5472+
params: {
5473+
name: "flood_tool",
5474+
arguments: {},
5475+
_meta: {
5476+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
5477+
"io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" },
5478+
"io.modelcontextprotocol/clientCapabilities": {},
5479+
"io.modelcontextprotocol/logLevel": "info",
5480+
},
5481+
},
5482+
}.to_json
5483+
5484+
response = @transport.handle_request(modern_rack_request(body))
5485+
5486+
assert_equal 200, response[0]
5487+
assert_equal "text/event-stream", response[1]["content-type"]
5488+
frames = response[2][0].split("\n\n").reject(&:empty?)
5489+
assert_equal StreamableHTTPTransport::MAX_MODERN_REQUEST_NOTIFICATIONS + 1, frames.size
5490+
assert_equal overflow, delivery_results.count { |result| result == false }
5491+
end
5492+
5493+
test "modern POST without handler notifications keeps the single JSON exchange" do
5494+
response = @transport.handle_request(modern_rack_request(modern_body("tools/list", {})))
5495+
5496+
assert_equal 200, response[0]
5497+
assert_equal "application/json", response[1]["content-type"]
5498+
end
5499+
5500+
test "modern POST suppresses log notifications without the envelope logLevel" do
5501+
# SEP-2575: log delivery is authorized per request via the `_meta` logLevel;
5502+
# the server-wide level does not apply to modern requests.
5503+
@server.logging_message_notification = MCP::LoggingMessageNotification.new(level: "debug")
5504+
@server.define_tool(name: "logging_tool") do |server_context:|
5505+
server_context.notify_log_message(data: "hi", level: "info")
5506+
Tool::Response.new([{ type: "text", text: "done" }])
5507+
end
5508+
5509+
response = @transport.handle_request(modern_rack_request(
5510+
modern_body("tools/call", { name: "logging_tool", arguments: {} }),
5511+
))
5512+
5513+
assert_equal 200, response[0]
5514+
assert_equal "application/json", response[1]["content-type"]
5515+
refute_includes response[2][0], "notifications/message"
5516+
end
5517+
5518+
test "modern POST delivers log notifications when the envelope carries logLevel" do
5519+
@server.define_tool(name: "logging_tool") do |server_context:|
5520+
server_context.notify_log_message(data: "hi", level: "info")
5521+
Tool::Response.new([{ type: "text", text: "done" }])
5522+
end
5523+
5524+
body = {
5525+
jsonrpc: "2.0",
5526+
method: "tools/call",
5527+
id: 1,
5528+
params: {
5529+
name: "logging_tool",
5530+
arguments: {},
5531+
_meta: {
5532+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
5533+
"io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" },
5534+
"io.modelcontextprotocol/clientCapabilities": {},
5535+
"io.modelcontextprotocol/logLevel": "info",
5536+
},
5537+
},
5538+
}.to_json
5539+
5540+
response = @transport.handle_request(modern_rack_request(body))
5541+
5542+
assert_equal 200, response[0]
5543+
assert_equal "text/event-stream", response[1]["content-type"]
5544+
assert_includes response[2][0], "notifications/message"
5545+
end
5546+
5547+
test "modern POST treats an unrecognized envelope logLevel as absent" do
5548+
# Matching the Python SDK, an unrecognized level reads as absent:
5549+
# delivery stays off instead of erroring on every log call.
5550+
reported = []
5551+
configuration = MCP::Configuration.new(exception_reporter: ->(e, _ctx) { reported << e })
5552+
server = Server.new(name: "log_level_test", configuration: configuration)
5553+
transport = StreamableHTTPTransport.new(server, dns_rebinding_protection: false)
5554+
server.define_tool(name: "logging_tool") do |server_context:|
5555+
server_context.notify_log_message(data: "hi", level: "info")
5556+
Tool::Response.new([{ type: "text", text: "done" }])
5557+
end
5558+
5559+
body = {
5560+
jsonrpc: "2.0",
5561+
method: "tools/call",
5562+
id: 1,
5563+
params: {
5564+
name: "logging_tool",
5565+
arguments: {},
5566+
_meta: {
5567+
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
5568+
"io.modelcontextprotocol/clientInfo": { name: "modern_client", version: "2.0" },
5569+
"io.modelcontextprotocol/clientCapabilities": {},
5570+
"io.modelcontextprotocol/logLevel": "bogus",
5571+
},
5572+
},
5573+
}.to_json
5574+
5575+
response = transport.handle_request(modern_rack_request(body))
5576+
5577+
assert_equal 200, response[0]
5578+
assert_equal "application/json", response[1]["content-type"]
5579+
refute_includes response[2][0], "notifications/message"
5580+
assert_empty reported
5581+
end
5582+
54215583
test "modern POST serves server/discover without an envelope" do
54225584
response = @transport.handle_request(modern_rack_request(
54235585
{ jsonrpc: "2.0", method: "server/discover", id: 1 }.to_json,

‎test/mcp/server_notification_test.rb‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,31 @@ def handle_request(request); end
170170
assert_empty mock_transport.notifications
171171
end
172172

173+
test "ServerSession#notify_log_message on a modern-era session ignores the server-wide level" do
174+
# SEP-2575: on the modern lifecycle, log delivery is authorized per request via
175+
# the envelope's logLevel; the server-wide level MUST NOT apply.
176+
server = Server.new(name: "test_server", version: "1.0.0")
177+
mock_transport = MockTransport.new(server)
178+
server.logging_message_notification = MCP::LoggingMessageNotification.new(level: "debug")
179+
session = ServerSession.new(server: server, transport: mock_transport, era: :modern)
180+
181+
session.notify_log_message(data: { message: "test" }, level: "error")
182+
183+
assert_empty mock_transport.notifications
184+
end
185+
186+
test "ServerSession#notify_log_message on a modern-era session honors a per-request level" do
187+
server = Server.new(name: "test_server", version: "1.0.0")
188+
mock_transport = MockTransport.new(server)
189+
session = ServerSession.new(server: server, transport: mock_transport, era: :modern)
190+
session.configure_logging(MCP::LoggingMessageNotification.new(level: "info"))
191+
192+
session.notify_log_message(data: { message: "test" }, level: "error")
193+
194+
assert_equal 1, mock_transport.notifications.length
195+
assert_equal Methods::NOTIFICATIONS_MESSAGE, mock_transport.notifications.first[:method]
196+
end
197+
173198
test "#notify_log_message sends notification with logger through transport" do
174199
@server.logging_message_notification = MCP::LoggingMessageNotification.new(level: "error")
175200
@server.notify_log_message(data: { error: "Connection Failed" }, level: "error", logger: "DatabaseLogger")

0 commit comments

Comments
 (0)