Skip to content

Commit 84090a8

Browse files
authored
Merge pull request #456 from koic/handle_initialize_request_without_id
Handle an initialize request sent without an ID
2 parents 5425c9c + fc0c6b8 commit 84090a8

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -849,6 +849,17 @@ def handle_initialization(request, body_string, body)
849849

850850
response = server_session.handle_json(body_string)
851851

852+
# `initialize_request?` matches on the method alone, so an `initialize` sent without
853+
# an id (framed as a notification) reaches here. `Server#init` marks the session initialized,
854+
# but JSON-RPC emits no response for an id-less request, so `response` is nil.
855+
# Returning `[200, ..., [nil]]` would place nil in the Rack body (which the web server cannot serialize),
856+
# and the session would be retained since it is marked initialized. Discard the orphaned session
857+
# and ack with 202, mirroring the nil-response handling in a regular request.
858+
if response.nil?
859+
cleanup_session(session_id) if session_id
860+
return handle_accepted
861+
end
862+
852863
# If `Server#init` produced an error response (e.g., malformed JSON-RPC envelope),
853864
# `mark_initialized!` was never called. Discard the orphaned session and omit
854865
# the `Mcp-Session-Id` header so the client retries from a clean state instead of

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,24 @@ def string
315315
assert_equal({}, @transport.instance_variable_get(:@sessions))
316316
end
317317

318+
test "acks an initialize sent without an id and retains no session" do
319+
# `initialize` framed as a notification (no id) produces no JSON-RPC response.
320+
# The transport must not put nil in the Rack body or retain the orphaned session.
321+
request = create_rack_request(
322+
"POST",
323+
"/",
324+
{ "CONTENT_TYPE" => "application/json" },
325+
{ jsonrpc: "2.0", method: "initialize" }.to_json,
326+
)
327+
328+
response = @transport.handle_request(request)
329+
330+
assert_equal 202, response[0]
331+
refute response[1].key?("Mcp-Session-Id"), "no session id should leak from an id-less init"
332+
assert_equal [], response[2]
333+
assert_equal({}, @transport.instance_variable_get(:@sessions))
334+
end
335+
318336
test "rejects non-Hash JSON-RPC body with HTTP 400 and -32600" do
319337
request = create_rack_request(
320338
"POST",

0 commit comments

Comments
 (0)