Reject POST requests without session ID in stateful mode

Per the MCP specification (Streamable HTTP > Session Management):

> Servers that require a session ID SHOULD respond to requests without an `Mcp-Session-Id` header
> (other than initialization) with HTTP 400 Bad Request.

https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#session-management

Previously, non-initialize POST requests without `Mcp-Session-Id` in stateful mode were processed
with HTTP 200 (for regular requests) or HTTP 202 (for notifications/responses).

This change adds an explicit check in `handle_post` to return HTTP 400 Bad Request when the session
ID is missing in stateful mode for all non-initialize requests, aligning with the specification.
This commit is contained in:
Koichi ITO 2026-03-28 02:45:58 +09:00
commit 88d9bed69d

View file

@ -120,10 +120,14 @@ module MCP
if body["method"] == "initialize"
handle_initialization(body_string, body)
elsif notification?(body) || response?(body)
handle_accepted
else
handle_regular_request(body_string, session_id)
return missing_session_id_response if !@stateless && !session_id
if notification?(body) || response?(body)
handle_accepted
else
handle_regular_request(body_string, session_id)
end
end
rescue StandardError => e
MCP.configuration.exception_reporter.call(e, { request: body_string })