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): cap the body the client allowlist inspects at 64 KiB

yassinc0f335d8cae7
diff --git a/litellm/constants.py b/litellm/constants.py
index 8409a161800..6babf6afae3 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -183,6 +183,7 @@ MCP_TOOL_LISTING_TIMEOUT: Final = float(os.getenv("LITELLM_MCP_TOOL_LISTING_TIME
MCP_METADATA_TIMEOUT: Final = float(os.getenv("LITELLM_MCP_METADATA_TIMEOUT", "10.0"))
MCP_HEALTH_CHECK_TIMEOUT: Final = float(os.getenv("LITELLM_MCP_HEALTH_CHECK_TIMEOUT", "10.0"))
MCP_TOOL_LISTING_MAX_PAGES: Final = 1000
+MCP_ALLOWLIST_PEEK_MAX_BYTES: Final = 64 * 1024
# Allowlist of commands permitted for MCP stdio transport.
# Prevents arbitrary command execution via /mcp-rest/test/* endpoints or server creation.
diff --git a/litellm/proxy/_experimental/mcp_server/client_allowlist.py b/litellm/proxy/_experimental/mcp_server/client_allowlist.py
index 607c502a460..b1afec397c2 100644
--- a/litellm/proxy/_experimental/mcp_server/client_allowlist.py
+++ b/litellm/proxy/_experimental/mcp_server/client_allowlist.py
@@ -12,6 +12,7 @@ from pydantic import BaseModel, TypeAdapter, ValidationError
from typing_extensions import ReadOnly, TypedDict
from litellm._logging import verbose_logger
+from litellm.constants import MCP_ALLOWLIST_PEEK_MAX_BYTES
MCP_ALLOWED_CLIENTS_SETTING: Final = "mcp_allowed_clients"
@@ -55,6 +56,18 @@ class MCPClientRejection:
return body
+def oversized_unidentified_request_body() -> MCPClientForbiddenBody:
+ body: Final[MCPClientForbiddenBody] = {
+ "error": "Forbidden",
+ "details": (
+ f"While {MCP_ALLOWED_CLIENTS_SETTING} is set, this gateway reads at most "
+ f"{MCP_ALLOWLIST_PEEK_MAX_BYTES} bytes of an MCP POST to find clientInfo.name before routing it; "
+ "this request was larger than that and could not be identified."
+ ),
+ }
+ 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 1c914ae7fbe..aa4a66bc848 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -26,7 +26,7 @@ from starlette.types import Message, Receive, Scope, Send
from typing_extensions import ReadOnly, TypedDict
from litellm._logging import verbose_logger
-from litellm.constants import MAXIMUM_TRACEBACK_LINES_TO_LOG
+from litellm.constants import MAXIMUM_TRACEBACK_LINES_TO_LOG, MCP_ALLOWLIST_PEEK_MAX_BYTES
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.custom_httpx.http_handler import (
get_async_httpx_client,
@@ -467,6 +467,7 @@ if MCP_AVAILABLE:
MCP_ALLOWED_CLIENTS_SETTING,
allowed_mcp_clients_from_general_settings,
check_mcp_client_allowed,
+ oversized_unidentified_request_body,
)
from litellm.proxy._experimental.mcp_server.faults.list_outcomes import (
SERVER_OUTCOMES_META_KEY,
@@ -3826,8 +3827,23 @@ if MCP_AVAILABLE:
return allowed_mcp_clients_from_general_settings(general_settings)
- def _routing_peek_limit(allowed_clients: frozenset[str] | None) -> int | None:
- return _MCP_ROUTING_PEEK_MAX_BYTES if allowed_clients is None else None
+ def _routing_peek_limit(allowed_clients: frozenset[str] | None) -> int:
+ return _MCP_ROUTING_PEEK_MAX_BYTES if allowed_clients is None else MCP_ALLOWLIST_PEEK_MAX_BYTES
+
+ async def _reject_oversized_unidentified_request(
+ scope: Scope,
+ receive: Receive,
+ send: Send,
+ client_ip: str | None,
+ ) -> None:
+ verbose_logger.warning(
+ "Rejecting MCP POST (ip=%s): body exceeds %d bytes so %s cannot be checked",
+ client_ip,
+ MCP_ALLOWLIST_PEEK_MAX_BYTES,
+ MCP_ALLOWED_CLIENTS_SETTING,
+ )
+ forbidden: Final = JSONResponse(status_code=403, content=oversized_unidentified_request_body())
+ await forbidden(scope, receive, send)
async def _reject_initialize_from_disallowed_client(
scope: Scope,
@@ -3864,13 +3880,14 @@ if MCP_AVAILABLE:
async def _read_request_body_for_routing(
receive: Receive,
- peek_max_bytes: int | None = _MCP_ROUTING_PEEK_MAX_BYTES,
- ) -> tuple[list[Message], bytes]:
+ peek_max_bytes: int = _MCP_ROUTING_PEEK_MAX_BYTES,
+ ) -> tuple[list[Message], bytes, bool]:
"""
Read just enough of the request body to decide whether this is a
JSON-RPC ``initialize`` call. Returns the consumed ASGI messages so
the caller can replay them faithfully to the downstream handler, and
- the peeked body bytes (capped at ``peek_max_bytes``).
+ the peeked body bytes (capped at ``peek_max_bytes``), plus whether
+ the body was cut off at that cap.
Stops reading from the wire as soon as either (a) we have peeked
``peek_max_bytes`` of body, or (b) the body is complete.
@@ -3878,14 +3895,11 @@ if MCP_AVAILABLE:
``wrapped_receive`` in the caller — so an authenticated client cannot
force the proxy to buffer an arbitrarily large payload just to make a
routing decision.
-
- ``peek_max_bytes=None`` reads the whole body. The client allowlist
- needs that: a truncated initialize body parses as non-initialize and
- would otherwise skip the allowlist check entirely.
"""
consumed_messages: Final[list[Message]] = []
body_chunks: Final[list[bytes]] = []
peeked_bytes = 0
+ truncated = False
while True:
message = await receive()
@@ -3902,20 +3916,22 @@ if MCP_AVAILABLE:
# handler via ``consumed_messages``, but ``body_chunks`` is
# purely for the JSON-RPC method check — there is no reason
# to copy a large body frame into a second buffer.
- remaining = len(body) if peek_max_bytes is None else peek_max_bytes - peeked_bytes
+ remaining = peek_max_bytes - peeked_bytes
if remaining > 0:
body_chunks.append(body[:remaining])
peeked_bytes += min(len(body), remaining)
+ truncated = truncated or len(body) > remaining
if not message.get("more_body", False):
break
- if peek_max_bytes is not None and peeked_bytes >= peek_max_bytes:
+ if peeked_bytes >= peek_max_bytes:
# Stop draining; downstream replay will pull remaining chunks
# directly from the original `receive` via wrapped_receive.
+ truncated = True
break
- return consumed_messages, b"".join(body_chunks)
+ return consumed_messages, b"".join(body_chunks), truncated
async def _handle_stale_mcp_session(
scope: Scope,
@@ -4566,9 +4582,12 @@ if MCP_AVAILABLE:
body = b""
if scope.get("method") == "POST":
allowed_clients: Final = _load_allowed_mcp_clients()
- consumed_messages, body = await _read_request_body_for_routing(
+ consumed_messages, body, body_truncated = await _read_request_body_for_routing(
receive, _routing_peek_limit(allowed_clients)
)
+ if allowed_clients is not None and body_truncated and not session_id:
+ await _reject_oversized_unidentified_request(scope, receive, send, _client_ip)
+ return
is_initialize = _is_initialize_request(body)
if is_initialize and await _reject_initialize_from_disallowed_client(
scope, receive, send, body, _client_ip, allowed_clients
@@ -4843,11 +4862,14 @@ if MCP_AVAILABLE:
await asyncio.sleep(0.1)
sse_allowed_clients: Final = _load_allowed_mcp_clients()
- sse_consumed_messages, sse_body = (
+ sse_consumed_messages, sse_body, sse_truncated = (
await _read_request_body_for_routing(receive, _routing_peek_limit(sse_allowed_clients))
if scope.get("method") == "POST"
- else ((), b"")
+ else ((), b"", False)
)
+ if sse_allowed_clients is not None and sse_truncated:
+ await _reject_oversized_unidentified_request(scope, receive, send, _sse_client_ip)
+ return
if _is_initialize_request(sse_body) and await _reject_initialize_from_disallowed_client(
scope, receive, send, sse_body, _sse_client_ip, sse_allowed_clients
):
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 6147233c373..e63792101ae 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
@@ -20,6 +20,7 @@ from mcp.types import (
TextResourceContents,
)
+from litellm.constants import MCP_ALLOWLIST_PEEK_MAX_BYTES
from litellm.proxy._types import (
LiteLLM_MCPServerTable,
MCPTransport,
@@ -2311,6 +2312,88 @@ async def test_streamable_http_allowlist_reads_past_the_routing_peek_cap_for_ini
assert body["details"] == "MCP client 'claude-code' is not listed in this gateway's mcp_allowed_clients."
+async def test_streamable_http_allowlist_bounds_the_body_it_buffers_for_unidentified_posts() -> None:
+ from starlette.types import Scope
+
+ from litellm.proxy._experimental.mcp_server import client_allowlist
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+
+ chunk_size: Final = 1024
+ request_body: Final = _oversized_initialize("antigravity-cli", MCP_ALLOWLIST_PEEK_MAX_BYTES)
+ assert len(request_body) > 2 * MCP_ALLOWLIST_PEEK_MAX_BYTES
+ scope: Final[Scope] = {"type": "http", "method": "POST", "path": "/mcp", "headers": []}
+ receive: Final = _chunked_receive(request_body, chunk_size)
+ 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 == client_allowlist.oversized_unidentified_request_body()
+ assert receive.await_count <= MCP_ALLOWLIST_PEEK_MAX_BYTES // chunk_size + 1
+ stateful_handle.assert_not_awaited()
+ stateless_handle.assert_not_awaited()
+
+
+async def test_streamable_http_allowlist_streams_large_posts_on_an_admitted_session() -> None:
+ from starlette.types import Receive, Scope, Send
+
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+
+ request_body: Final = json.dumps(
+ {
+ "jsonrpc": "2.0",
+ "id": 7,
+ "method": "tools/call",
+ "params": {
+ "name": "echo",
+ "arguments": {"text": "x" * (2 * MCP_ALLOWLIST_PEEK_MAX_BYTES)},
+ },
+ }
+ ).encode()
+ scope: Final[Scope] = {
+ "type": "http",
+ "method": "POST",
+ "path": "/mcp",
+ "headers": [(b"mcp-session-id", b"admitted-session")],
+ }
+ receive: Final = _chunked_receive(request_body, 1024)
+ send: Final = AsyncMock()
+ downstream_bodies: Final[list[bytes]] = []
+
+ async def handle_request(_: Scope, downstream_receive: Receive, __: Send) -> None:
+ downstream_bodies.append(await _drain_body(downstream_receive))
+
+ stateful_handle: Final = AsyncMock(side_effect=handle_request)
+
+ 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={"admitted-session": object()}),
+ ),
+ ):
+ await mcp_module.handle_streamable_http_mcp(scope, receive, send)
+
+ assert downstream_bodies == [request_body]
+ send.assert_not_awaited()
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("request_body", "admitted"),
@@ -2361,6 +2444,43 @@ async def test_sse_endpoint_applies_the_same_client_allowlist(request_body: byte
assert "mcp_allowed_clients" in body["details"]
+async def test_sse_endpoint_rejects_posts_larger_than_the_allowlist_peek_cap() -> None:
+ from starlette.types import Scope
+
+ from litellm.proxy._experimental.mcp_server import client_allowlist
+ from litellm.proxy._experimental.mcp_server import server as mcp_module
+
+ chunk_size: Final = 1024
+ request_body: Final = _oversized_initialize("antigravity-cli", MCP_ALLOWLIST_PEEK_MAX_BYTES)
+ scope: Final[Scope] = {"type": "http", "method": "POST", "path": "/mcp/sse", "headers": []}
+ receive: Final = _chunked_receive(request_body, chunk_size)
+ send: Final = AsyncMock()
+ sse_handle: Final = AsyncMock()
+
+ with (
+ _client_allowlist_patches(["antigravity-cli"]),
+ patch( # test-quality-ok: module-level pre-auth probe unrelated to the allowlist under test; no injection seam
+ "litellm.proxy._experimental.mcp_server.server._raise_preemptive_401_for_unauthenticated_servers",
+ new_callable=AsyncMock,
+ ),
+ patch( # test-quality-ok: module-level upstream auth probe unrelated to the allowlist under test; no injection seam
+ "litellm.proxy._experimental.mcp_server.server._check_passthrough_upstream_auth",
+ new_callable=AsyncMock,
+ ),
+ patch.object( # test-quality-ok: SSE manager is a module singleton; the downstream call is the observable
+ mcp_module.sse_session_manager, "handle_request", sse_handle
+ ),
+ ):
+ await mcp_module.handle_sse_mcp(scope, receive, send)
+
+ status, body = _forbidden_client_response(send)
+ assert status == 403
+ assert body == client_allowlist.oversized_unidentified_request_body()
+ assert receive.await_count <= MCP_ALLOWLIST_PEEK_MAX_BYTES // chunk_size + 1
+ sse_handle.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_mcp_routing_chunked_initialize_to_stateful():
"""