Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(mcp): refuse sessionless and stale-session POSTs that skip initialize while mcp_allowed_clients is set

yassinc23039373160
diff --git a/litellm/proxy/_experimental/mcp_server/client_allowlist.py b/litellm/proxy/_experimental/mcp_server/client_allowlist.py
index b1afec397c2..eca1f4eb026 100644
--- a/litellm/proxy/_experimental/mcp_server/client_allowlist.py
+++ b/litellm/proxy/_experimental/mcp_server/client_allowlist.py
@@ -37,6 +37,11 @@ class MCPClientForbiddenBody(TypedDict):
details: ReadOnly[str]
+class MCPSessionNotFoundBody(TypedDict):
+ error: ReadOnly[Literal["Not Found"]]
+ details: ReadOnly[str]
+
+
@dataclass(frozen=True, slots=True)
class MCPClientRejection:
client_name: str | None
@@ -68,6 +73,28 @@ def oversized_unidentified_request_body() -> MCPClientForbiddenBody:
return body
+def unidentified_sessionless_request_body() -> MCPClientForbiddenBody:
+ body: Final[MCPClientForbiddenBody] = {
+ "error": "Forbidden",
+ "details": (
+ f"While {MCP_ALLOWED_CLIENTS_SETTING} is set, an MCP POST without a live mcp-session-id must be an "
+ "initialize request; open a session with initialize from a listed client application first."
+ ),
+ }
+ return body
+
+
+def unknown_session_request_body(session_id: str) -> MCPSessionNotFoundBody:
+ body: Final[MCPSessionNotFoundBody] = {
+ "error": "Not Found",
+ "details": (
+ f"mcp-session-id '{session_id}' is not known to this gateway worker. While {MCP_ALLOWED_CLIENTS_SETTING} "
+ "is set the request cannot fall back to a sessionless call; start a new session with initialize."
+ ),
+ }
+ return body
+
+
def parse_allowed_mcp_clients(raw_setting: object) -> frozenset[str] | None:
"""None when the setting is absent (not enforced). A malformed setting admits nobody."""
if raw_setting is None:
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index c18d0f0e471..6a794502f77 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -468,6 +468,8 @@ if MCP_AVAILABLE:
allowed_mcp_clients_from_general_settings,
check_mcp_client_allowed,
oversized_unidentified_request_body,
+ unidentified_sessionless_request_body,
+ unknown_session_request_body,
)
from litellm.proxy._experimental.mcp_server.faults.list_outcomes import (
SERVER_OUTCOMES_META_KEY,
@@ -3845,6 +3847,31 @@ if MCP_AVAILABLE:
forbidden: Final = JSONResponse(status_code=403, content=oversized_unidentified_request_body())
await forbidden(scope, receive, send)
+ async def _reject_unidentified_sessionless_request(
+ scope: Scope,
+ receive: Receive,
+ send: Send,
+ client_ip: str | None,
+ stale_session_id: str | None,
+ ) -> None:
+ if stale_session_id is not None:
+ verbose_logger.warning(
+ "Rejecting MCP POST for unknown session '%s' (ip=%s): no stateless fallback while %s is set",
+ stale_session_id,
+ client_ip,
+ MCP_ALLOWED_CLIENTS_SETTING,
+ )
+ not_found: Final = JSONResponse(status_code=404, content=unknown_session_request_body(stale_session_id))
+ await not_found(scope, receive, send)
+ return
+ verbose_logger.warning(
+ "Rejecting sessionless MCP POST (ip=%s): only initialize is accepted without a session while %s is set",
+ client_ip,
+ MCP_ALLOWED_CLIENTS_SETTING,
+ )
+ forbidden: Final = JSONResponse(status_code=403, content=unidentified_sessionless_request_body())
+ await forbidden(scope, receive, send)
+
async def _reject_initialize_from_disallowed_client(
scope: Scope,
receive: Receive,
@@ -4541,6 +4568,7 @@ if MCP_AVAILABLE:
# - No session ID + initialize → stateful (so client gets mcp-session-id)
# - No session ID + other → stateless (curl, Inspector, Notion)
session_id = _get_session_id_from_scope(scope)
+ presented_session_id: Final = session_id
is_initialize = False
consumed_messages: list[Message] = []
@@ -4594,6 +4622,11 @@ if MCP_AVAILABLE:
scope, receive, send, body, _client_ip, allowed_clients
):
return
+ if allowed_clients is not None and not is_initialize and not session_id:
+ await _reject_unidentified_sessionless_request(
+ scope, receive, send, _client_ip, presented_session_id
+ )
+ return
use_stateful: Final = bool(session_id or is_initialize)
target_manager: Final = session_manager_stateful if use_stateful else session_manager_stateless
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
index 78b108096fb..dd2bf213690 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py
@@ -2220,7 +2220,78 @@ async def test_streamable_http_empty_or_malformed_allowlist_admits_nobody(
@pytest.mark.asyncio
-async def test_streamable_http_allowlist_only_inspects_initialize_requests() -> None:
+async def test_streamable_http_allowlist_refuses_sessionless_posts_that_are_not_initialize() -> None:
+ from starlette.types import Scope
+
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+
+ scope: Final[Scope] = {"type": "http", "method": "POST", "path": "/mcp", "headers": []}
+ receive: Final = AsyncMock(side_effect=[{"type": "http.request", "body": _TOOLS_LIST, "more_body": False}])
+ send: Final = AsyncMock()
+ stateful_handle: Final = AsyncMock()
+ stateless_handle: Final = AsyncMock()
+
+ with (
+ _client_allowlist_patches(["antigravity-cli"]),
+ patch( # test-quality-ok: session managers are module singletons; the downstream call is the observable
+ "litellm.proxy._experimental.mcp_server.server.session_manager_stateful",
+ SimpleNamespace(handle_request=stateful_handle),
+ ),
+ patch( # test-quality-ok: session managers are module singletons; the downstream call is the observable
+ "litellm.proxy._experimental.mcp_server.server.session_manager_stateless",
+ SimpleNamespace(handle_request=stateless_handle),
+ ),
+ ):
+ await mcp_module.handle_streamable_http_mcp(scope, receive, send)
+
+ status, body = _forbidden_client_response(send)
+ assert status == 403
+ assert body["error"] == "Forbidden"
+ assert body["details"].startswith("While mcp_allowed_clients is set, an MCP POST without a live mcp-session-id")
+ stateful_handle.assert_not_awaited()
+ stateless_handle.assert_not_awaited()
+
+
+async def test_streamable_http_allowlist_returns_404_for_a_session_unknown_to_this_worker() -> None:
+ from starlette.types import Scope
+
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+
+ scope: Final[Scope] = {
+ "type": "http",
+ "method": "POST",
+ "path": "/mcp",
+ "headers": [(b"mcp-session-id", b"stale-session-from-another-worker")],
+ }
+ receive: Final = AsyncMock(side_effect=[{"type": "http.request", "body": _TOOLS_LIST, "more_body": False}])
+ send: Final = AsyncMock()
+ stateful_handle: Final = AsyncMock()
+ stateless_handle: Final = AsyncMock()
+
+ with (
+ _client_allowlist_patches(["antigravity-cli"]),
+ patch( # test-quality-ok: session managers are module singletons; the downstream call is the observable
+ "litellm.proxy._experimental.mcp_server.server.session_manager_stateful",
+ SimpleNamespace(handle_request=stateful_handle, _server_instances={}),
+ ),
+ patch( # test-quality-ok: session managers are module singletons; the downstream call is the observable
+ "litellm.proxy._experimental.mcp_server.server.session_manager_stateless",
+ SimpleNamespace(handle_request=stateless_handle),
+ ),
+ ):
+ await mcp_module.handle_streamable_http_mcp(scope, receive, send)
+
+ status, body = _forbidden_client_response(send)
+ assert status == 404
+ assert body["error"] == "Not Found"
+ assert "stale-session-from-another-worker" in body["details"]
+ stateful_handle.assert_not_awaited()
+ stateless_handle.assert_not_awaited()
+
+
+async def test_streamable_http_without_allowlist_still_serves_sessionless_posts_statelessly() -> None:
from starlette.types import Receive, Scope, Send
from litellm.proxy._experimental.mcp_server import server as mcp_module
@@ -2234,7 +2305,7 @@ async def test_streamable_http_allowlist_only_inspects_initialize_requests() ->
downstream_bodies.append(await _drain_body(downstream_receive))
with (
- _client_allowlist_patches(["antigravity-cli"]),
+ _client_allowlist_patches(None),
patch( # test-quality-ok: session managers are module singletons; the downstream call is the observable
"litellm.proxy._experimental.mcp_server.server.session_manager_stateless",
SimpleNamespace(handle_request=AsyncMock(side_effect=handle_request)),
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index 25a1f83c61f..6d92d20cc61 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -13823,7 +13823,9 @@ async def test_update_general_settings_keeps_yaml_openai_websocket_passthrough()
({}, None),
],
)
-async def test_update_general_settings_propagates_mcp_allowed_clients(db_general_settings, expected):
+async def test_update_general_settings_propagates_mcp_allowed_clients(
+ db_general_settings: dict[str, list[str]], expected: list[str] | None
+) -> None:
from litellm.proxy.proxy_server import ProxyConfig
proxy_config = ProxyConfig()
@@ -13839,7 +13841,7 @@ async def test_update_general_settings_propagates_mcp_allowed_clients(db_general
@pytest.mark.asyncio
-async def test_update_general_settings_keeps_yaml_mcp_allowed_clients():
+async def test_update_general_settings_keeps_yaml_mcp_allowed_clients() -> None:
from litellm.proxy.proxy_server import ProxyConfig
proxy_config = ProxyConfig()