|
1 | 1 | """Tests for StreamableHTTPSessionManager.""" |
2 | 2 |
|
| 3 | +import json |
3 | 4 | from typing import Any |
4 | 5 | from unittest.mock import AsyncMock, patch |
5 | 6 |
|
|
11 | 12 | from mcp.server.lowlevel import Server |
12 | 13 | from mcp.server.streamable_http import MCP_SESSION_ID_HEADER, StreamableHTTPServerTransport |
13 | 14 | from mcp.server.streamable_http_manager import StreamableHTTPSessionManager |
| 15 | +from mcp.types import INVALID_REQUEST |
14 | 16 |
|
15 | 17 |
|
16 | 18 | @pytest.mark.anyio |
@@ -262,3 +264,52 @@ async def mock_receive(): |
262 | 264 |
|
263 | 265 | # Verify internal state is cleaned up |
264 | 266 | assert len(transport._request_streams) == 0, "Transport should have no active request streams" |
| 267 | + |
| 268 | + |
| 269 | +@pytest.mark.anyio |
| 270 | +async def test_unknown_session_id_returns_404(): |
| 271 | + """Test that requests with unknown session IDs return HTTP 404 per MCP spec.""" |
| 272 | + app = Server("test-unknown-session") |
| 273 | + manager = StreamableHTTPSessionManager(app=app) |
| 274 | + |
| 275 | + async with manager.run(): |
| 276 | + sent_messages: list[Message] = [] |
| 277 | + response_body = b"" |
| 278 | + |
| 279 | + async def mock_send(message: Message): |
| 280 | + nonlocal response_body |
| 281 | + sent_messages.append(message) |
| 282 | + if message["type"] == "http.response.body": |
| 283 | + response_body += message.get("body", b"") |
| 284 | + |
| 285 | + # Request with a non-existent session ID |
| 286 | + scope = { |
| 287 | + "type": "http", |
| 288 | + "method": "POST", |
| 289 | + "path": "/mcp", |
| 290 | + "headers": [ |
| 291 | + (b"content-type", b"application/json"), |
| 292 | + (b"accept", b"application/json, text/event-stream"), |
| 293 | + (b"mcp-session-id", b"non-existent-session-id"), |
| 294 | + ], |
| 295 | + } |
| 296 | + |
| 297 | + async def mock_receive(): |
| 298 | + return {"type": "http.request", "body": b"{}", "more_body": False} # pragma: no cover |
| 299 | + |
| 300 | + await manager.handle_request(scope, mock_receive, mock_send) |
| 301 | + |
| 302 | + # Find the response start message |
| 303 | + response_start = next( |
| 304 | + (msg for msg in sent_messages if msg["type"] == "http.response.start"), |
| 305 | + None, |
| 306 | + ) |
| 307 | + assert response_start is not None, "Should have sent a response" |
| 308 | + assert response_start["status"] == 404, "Should return HTTP 404 for unknown session ID" |
| 309 | + |
| 310 | + # Verify JSON-RPC error format |
| 311 | + error_data = json.loads(response_body) |
| 312 | + assert error_data["jsonrpc"] == "2.0" |
| 313 | + assert error_data["id"] == "server-error" |
| 314 | + assert error_data["error"]["code"] == INVALID_REQUEST |
| 315 | + assert error_data["error"]["message"] == "Session not found" |
0 commit comments