Commit 62eb2fa
committed
Handle an Initialize Request Sent Without an Id
## Motivation and Context
`StreamableHTTPTransport#handle_post` routes to `handle_initialization` via `initialize_request?`,
which matches on the method name alone. An `initialize` message sent without an id (framed as a notification)
therefore reaches `handle_initialization`. `Server#init` runs and marks the session initialized,
but JSON-RPC emits no response for an id-less request, so `handle_json` returns nil.
Two things then went wrong:
- `handle_initialization` returned `[200, headers, [nil]]`. A `nil` body element is not a valid Rack response,
so the web server raises while serializing it (`NoMethodError` on `nil.bytesize`)
and the client gets a malformed response or a 500.
- The `if session_id && !server_session.initialized?` cleanup guard was skipped, because the session is marked initialized.
The session was retained with a `Mcp-Session-Id` header, so a stream of id-less `initialize` messages accumulates sessions
toward the `max_sessions` cap until the reaper reclaims them.
`handle_initialization` now treats a nil response as an id-less initialize: it discards the orphaned session
and acks with 202, mirroring how `handle_regular_request` already handles a nil response.
A well-formed `initialize` request (with an id) is unaffected.
## How Has This Been Tested?
A new test in `test/mcp/server/transports/streamable_http_transport_test.rb` posts an `initialize`
with no id and asserts a 202 with an empty body, no `Mcp-Session-Id` header, and an empty session map.
It fails against the previous code (a 200 with a nil body element and a retained session) and passes now.
## Breaking Changes
None. A conforming client sends `initialize` as a request with an id and is unaffected;
only the malformed id-less form changes, from a broken 200 to a 202 with no retained session.1 parent e85f6d0 commit 62eb2fa
2 files changed
Lines changed: 29 additions & 0 deletions
File tree
- lib/mcp/server/transports
- test/mcp/server/transports
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
844 | 844 | | |
845 | 845 | | |
846 | 846 | | |
| 847 | + | |
| 848 | + | |
| 849 | + | |
| 850 | + | |
| 851 | + | |
| 852 | + | |
| 853 | + | |
| 854 | + | |
| 855 | + | |
| 856 | + | |
| 857 | + | |
847 | 858 | | |
848 | 859 | | |
849 | 860 | | |
| |||
Lines changed: 18 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
315 | 315 | | |
316 | 316 | | |
317 | 317 | | |
| 318 | + | |
| 319 | + | |
| 320 | + | |
| 321 | + | |
| 322 | + | |
| 323 | + | |
| 324 | + | |
| 325 | + | |
| 326 | + | |
| 327 | + | |
| 328 | + | |
| 329 | + | |
| 330 | + | |
| 331 | + | |
| 332 | + | |
| 333 | + | |
| 334 | + | |
| 335 | + | |
318 | 336 | | |
319 | 337 | | |
320 | 338 | | |
| |||
0 commit comments