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): preserve proxy logging and authorization coverage (#40337)

tin-berri1a9c6ce390ae
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 44c00df996c..30793ef246d 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -767,12 +767,12 @@ if MCP_AVAILABLE:
_stateful_auth_context_cleanup_task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await _stateful_auth_context_cleanup_task
- if _session_manager_cm:
- await _session_manager_cm.__aexit__(None, None, None)
- if _session_manager_stateful_cm:
- await _session_manager_stateful_cm.__aexit__(None, None, None)
if _sse_session_manager_cm:
await _sse_session_manager_cm.__aexit__(None, None, None)
+ if _session_manager_stateful_cm:
+ await _session_manager_stateful_cm.__aexit__(None, None, None)
+ if _session_manager_cm:
+ await _session_manager_cm.__aexit__(None, None, None)
except Exception as e:
verbose_logger.exception("Error during session manager shutdown: %s", e)
@@ -1005,6 +1005,7 @@ if MCP_AVAILABLE:
if _mcp_proxy_mode.get() and name in MCP_PROXY_TOOL_NAMES:
assert user_api_key_auth is not None
+ proxy_call_start: Final = datetime.now() # noqa: DTZ005 # logging pipeline uses naive datetimes
proxy_logging_obj: Final = (
await _build_virtual_call_logging_obj(
name=name,
@@ -1016,7 +1017,7 @@ if MCP_AVAILABLE:
if name == MCP_PROXY_CALL_TOOL_NAME
else None
)
- return await handle_mcp_proxy_tool(
+ proxy_result: Final = await handle_mcp_proxy_tool(
name=name,
arguments=arguments or {}, # mutable-ok: proxy handler payload
user_api_key_dict=user_api_key_auth,
@@ -1028,6 +1029,16 @@ if MCP_AVAILABLE:
raw_headers=raw_headers,
litellm_logging_obj=proxy_logging_obj,
)
+ if proxy_logging_obj is not None:
+ return await _fire_mcp_tool_call_logging(
+ logging_obj=proxy_logging_obj,
+ result=proxy_result,
+ start_time=proxy_call_start,
+ end_time=datetime.now(), # noqa: DTZ005 # matches the logging pipeline start time
+ user_api_key_auth=user_api_key_auth,
+ request_data=types.MappingProxyType({"name": name, "arguments": arguments}),
+ )
+ return proxy_result
if name not in VIRTUAL_TOOL_NAMES:
return None
@@ -3493,7 +3504,9 @@ if MCP_AVAILABLE:
server_name: str | None,
session_id: str | None = None,
) -> StandardLoggingMCPToolCall:
- mcp_server: Final = global_mcp_server_manager._get_mcp_server_from_tool_name(name)
+ mcp_server: Final = global_mcp_server_manager._get_mcp_server_from_tool_name(
+ add_server_prefix_to_name(name, server_name) if server_name else name
+ )
namespaced_tool_name: Final = f"{server_name}/{name}" if server_name else name
if mcp_server:
mcp_info: Final = mcp_server.mcp_info or {}
diff --git a/tests/mcp_tests/mcp_server.py b/tests/mcp_tests/mcp_server.py
index bc6accbb721..eba7cae1bca 100644
--- a/tests/mcp_tests/mcp_server.py
+++ b/tests/mcp_tests/mcp_server.py
@@ -1,10 +1,12 @@
# math_server.py
import argparse
import os
+from typing import Final
-from mcp.server.fastmcp import FastMCP
+from mcp.server.fastmcp import Context, FastMCP
mcp = FastMCP("Math")
+ADD_OFFSET: Final = int(os.getenv("MCP_ADD_OFFSET", "0"))
def _parse_args() -> argparse.Namespace:
@@ -31,7 +33,7 @@ def _parse_args() -> argparse.Namespace:
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
- return a + b
+ return a + b + ADD_OFFSET
@mcp.tool()
@@ -40,6 +42,15 @@ def multiply(a: int, b: int) -> int:
return a * b
+def request_headers(ctx: Context) -> dict[str, str]:
+ request: Final = ctx.request_context.request
+ return {
+ "authorization": request.headers.get("authorization", "") if request is not None else "",
+ "x-request-tag": request.headers.get("x-request-tag", "") if request is not None else "",
+ }
+
+
def main() -> None:
args = _parse_args()
transport = (args.transport or "stdio").lower()
diff --git a/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml b/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
index ad68a03781d..19fad3d1393 100644
--- a/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
+++ b/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
@@ -23,3 +23,6 @@ mcp_servers:
transport: http
url: http://127.0.0.1:0/mcp
allow_all_keys: true
+ math_restricted:
+ transport: http
+ url: http://127.0.0.1:0/mcp
diff --git a/tests/mcp_tests/test_proxy_mcp_e2e.py b/tests/mcp_tests/test_proxy_mcp_e2e.py
index a97eed82e18..5e5b9db2dc6 100644
--- a/tests/mcp_tests/test_proxy_mcp_e2e.py
+++ b/tests/mcp_tests/test_proxy_mcp_e2e.py
@@ -1,27 +1,39 @@
import asyncio
import json
import os
+import queue
import socket
import subprocess
import sys
+import tempfile
import threading
import time
import typing
+from contextlib import asynccontextmanager, contextmanager
+from dataclasses import dataclass
+from datetime import datetime
from pathlib import Path
+import httpx
import pytest
import uvicorn
import yaml
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
+from mcp.types import CallToolResult
+from starlette.requests import Request
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.proxy._experimental.mcp_server.tool_search import handle_mcp_proxy_tool
+from litellm.proxy._types import LiteLLM_ObjectPermissionTable, ProxyException, UserAPIKeyAuth
from litellm.proxy.proxy_server import (
app as proxy_app,
+)
+from litellm.proxy.proxy_server import (
cleanup_router_config_variables,
initialize,
)
-
CONFIG_TEMPLATE_PATH = Path("tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml")
MCP_SERVER_SCRIPT = Path("tests/mcp_tests/mcp_server.py")
PROJECT_ROOT = Path(__file__).resolve().parents[2]
@@ -46,28 +58,49 @@ def _clear_proxy_database_env() -> typing.Iterator[None]:
mp.undo()
-def _initialize_proxy(config_path: str) -> None:
+async def _initialize_proxy(config_path: str) -> None:
+ from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager
+
cleanup_router_config_variables()
- asyncio.run(initialize(config=config_path, debug=True))
+ await initialize(config=config_path, debug=True)
+ for server_id, upstream in tuple(global_mcp_server_manager.registry.items()):
+ if upstream.server_name != "math_restricted":
+ continue
+ global_mcp_server_manager.registry[server_id] = upstream.model_copy(
+ update={"tool_name_to_display_name": {"add": "Add Numbers"}}
+ )
+
+
+@dataclass(frozen=True)
+class ProxyRig:
+ url: str
+ config_path: str
+ loop: asyncio.AbstractEventLoop
def _start_proxy_server(
config_path: str,
-) -> tuple[str, uvicorn.Server, threading.Thread, socket.socket]:
- _initialize_proxy(config_path)
-
+) -> tuple[ProxyRig, uvicorn.Server, threading.Thread, socket.socket]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 0))
host, port = sock.getsockname()
- config = uvicorn.Config(proxy_app, host=host, port=port, log_level="warning")
+ config = uvicorn.Config(proxy_app, host=host, port=port, log_level="warning", lifespan="off")
server = uvicorn.Server(config)
+ loop = asyncio.new_event_loop()
+
+ async def _serve() -> None:
+ from litellm.proxy._experimental.mcp_server import server as mcp_server
+
+ await _initialize_proxy(config_path)
+ async with proxy_app.router.lifespan_context(proxy_app), mcp_server.lifespan(proxy_app):
+ await server.serve(sockets=[sock])
+
def _run() -> None:
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
- loop.run_until_complete(server.serve(sockets=[sock]))
+ with asyncio.Runner(loop_factory=lambda: loop) as runner:
+ runner.run(_serve())
thread = threading.Thread(target=_run, daemon=True)
thread.start()
@@ -80,75 +113,93 @@ def _start_proxy_server(
raise TimeoutError("Proxy server did not start in time")
time.sleep(0.05)
- return f"http://{host}:{port}", server, thread, sock
+ return ProxyRig(f"http://{host}:{port}", config_path, loop), server, thread, sock
[email protected](scope="session")
-def math_streamable_http_server() -> str:
+@contextmanager
+def _math_http_server(offset: int) -> typing.Iterator[str]:
host = "127.0.0.1"
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((host, 0))
_, port = sock.getsockname()
- cmd = [
- sys.executable,
- str(MCP_SERVER_SCRIPT),
- "--transport",
- "http",
- "--host",
- host,
- "--port",
- str(port),
- ]
-
- env = os.environ.copy()
- server_process = subprocess.Popen(
- cmd,
- cwd=str(PROJECT_ROOT),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- )
-
- start_time = time.time()
- while True:
- if server_process.poll() is not None:
- stdout, stderr = server_process.communicate()
- raise RuntimeError(
- f"Streamable HTTP MCP server exited early.\nSTDOUT: {stdout.decode()}\nSTDERR: {stderr.decode()}"
- )
+ with tempfile.TemporaryFile() as server_log:
+ process = subprocess.Popen(
+ [sys.executable, str(MCP_SERVER_SCRIPT), "--transport", "http", "--host", host, "--port", str(port)],
+ cwd=str(PROJECT_ROOT),
+ stdout=server_log,
+ stderr=subprocess.STDOUT,
+ env={**os.environ, "MCP_ADD_OFFSET": str(offset)},
+ )
try:
- with socket.create_connection((host, port), timeout=0.1):
- break
- except OSError:
- if time.time() - start_time > PROXY_START_TIMEOUT:
- server_process.terminate()
- raise TimeoutError("Streamable HTTP MCP server did not start in time")
- time.sleep(0.05)
+ start_time = time.monotonic()
+ while True:
+ if process.poll() is not None:
+ server_log.seek(0)
+ raise RuntimeError(f"MCP upstream exited early: {server_log.read().decode()}")
+ try:
+ with socket.create_connection((host, port), timeout=0.1):
+ break
+ except OSError:
+ if time.monotonic() - start_time > PROXY_START_TIMEOUT:
+ raise TimeoutError("Streamable HTTP MCP server did not start in time")
+ time.sleep(0.05)
+ yield f"http://{host}:{port}"
+ finally:
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
- yield f"http://{host}:{port}"
- server_process.terminate()
- try:
- server_process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- server_process.kill()
[email protected](scope="session")
+def math_streamable_http_server() -> typing.Iterator[str]:
+ with _math_http_server(100) as url:
+ yield url
@pytest.fixture(scope="session")
-def proxy_server_url(tmp_path_factory: pytest.TempPathFactory, math_streamable_http_server: str):
+def math_restricted_server() -> typing.Iterator[str]:
+ with _math_http_server(200) as url:
+ yield url
+
+
[email protected](scope="session")
+def _proxy_server(
+ tmp_path_factory: pytest.TempPathFactory,
+ math_streamable_http_server: str,
+ math_restricted_server: str,
+):
config_dir = tmp_path_factory.mktemp("mcp_e2e")
config_path = config_dir / "config.yaml"
config = yaml.safe_load(CONFIG_TEMPLATE_PATH.read_text())
+ config["mcp_servers"]["math_stdio"]["command"] = sys.executable
config["mcp_servers"]["math_streamable_http"]["url"] = f"{math_streamable_http_server}/mcp"
+ config["mcp_servers"]["math_restricted"]["url"] = f"{math_restricted_server}/mcp"
+ config["general_settings"]["custom_auth"] = f"{__name__}.authorize_proxy_key"
+ config["litellm_settings"]["callbacks"] = [f"{__name__}.proxy_call_recorder"]
+ config["mcp_servers"]["math_restricted"]["mcp_info"] = {"mcp_server_cost_info": {"default_cost_per_query": 0.25}}
config_path.write_text(yaml.safe_dump(config))
- server_url, server, thread, sock = _start_proxy_server(str(config_path))
+ rig, server, thread, sock = _start_proxy_server(str(config_path))
- yield server_url
+ try:
+ yield rig
+ finally:
+ server.should_exit = True
+ thread.join(timeout=10)
+ sock.close()
+ assert not thread.is_alive(), "Proxy did not shut down"
- server.should_exit = True
- thread.join(timeout=10)
- sock.close()
+
+def proxy_server_url(_proxy_server: ProxyRig, setup_and_teardown: None) -> str:
+ asyncio.run_coroutine_threadsafe(_initialize_proxy(_proxy_server.config_path), _proxy_server.loop).result(
+ timeout=30
+ )
+ return _proxy_server.url
class TestProxyMcpSimpleConnections:
@@ -192,7 +243,7 @@ class TestProxyMcpSimpleConnections:
assert result.content
first_content = result.content[0]
text = getattr(first_content, "text", None)
- assert text == "11"
+ assert text == "111"
@pytest.mark.asyncio
async def test_proxy_mcp_lists_all_servers_without_header(self, proxy_server_url: str) -> None:
@@ -222,7 +273,7 @@ class TestProxyMcpSimpleConnections:
stdio_result = await _call_and_get_text("math_stdio-add", a=2, b=3)
streamable_result = await _call_and_get_text("math_streamable_http-add", a=4, b=5)
assert stdio_result == "5"
- assert streamable_result == "9"
+ assert streamable_result == "109"
class TestProxyMcpStatelessBehavior:
@@ -349,7 +400,7 @@ class TestProxyMcpSchemaDiscoveryMode:
},
)
assert stdio.isError is False and stdio.content[0].text == "7"
- assert http.isError is False and http.content[0].text == "11"
+ assert http.isError is False and http.content[0].text == "111"
@pytest.mark.asyncio
async def test_server_scope_header_narrows_discovery(self, proxy_server_url: str) -> None:
@@ -384,6 +435,12 @@ class TestProxyMcpSchemaDiscoveryMode:
stale = await session.call_tool("get_tool_schema", arguments={"tool_id": "0" * 32})
assert stale.isError is True and "unauthorized tool_id" in stale.content[0].text
+ for not_an_object in ("wrong", False):
+ refused_args = await session.call_tool(
+ "call_tool", arguments={"tool_id": tool_id, "arguments": not_an_object}
+ )
+ assert refused_args.isError is True and "object" in refused_args.content[0].text
+
direct = await session.call_tool("math_stdio-add", arguments={"a": 1, "b": 2})
assert direct.isError is True and "unavailable on /mcp/proxy" in direct.content[0].text
@@ -391,3 +448,208 @@ class TestProxyMcpSchemaDiscoveryMode:
with pytest.raises(McpError) as refused:
await operation()
assert refused.value.error.code == METHOD_NOT_FOUND
+
+
+async def authorize_proxy_key(request: Request, api_key: str) -> UserAPIKeyAuth:
+ permissions = {
+ "sk-1234": LiteLLM_ObjectPermissionTable(object_permission_id="open", mcp_servers=["math_stdio"]),
+ "sk-restricted": LiteLLM_ObjectPermissionTable(
+ object_permission_id="restricted", mcp_servers=["math_restricted"]
+ ),
+ "sk-none": LiteLLM_ObjectPermissionTable(object_permission_id="none", mcp_servers=["no-mcp-servers"]),
+ "sk-add-only": LiteLLM_ObjectPermissionTable(
+ object_permission_id="add-only", mcp_servers=["math_stdio"], mcp_tool_permissions={"math_stdio": ["add"]}
+ ),
+ }
+ permission = permissions.get(api_key)
+ if permission is None:
+ raise ProxyException(message="Unknown test key", type="authentication_error", param=None, code=401)
+ return UserAPIKeyAuth(api_key=api_key, user_id=api_key, object_permission=permission)
+
+
+class ProxyCallRecorder(CustomLogger):
+ def __init__(self) -> None:
+ super().__init__()
+ self.events: queue.Queue[str] = queue.Queue()
+
+ async def async_log_success_event(
+ self, kwargs: dict[str, object], response_obj: object, start_time: datetime, end_time: datetime
+ ) -> None:
+ payload = kwargs.get("standard_logging_object")
+ if isinstance(payload, dict) and payload.get("call_type") == "call_mcp_tool":
+ self.events.put(json.dumps(payload, default=str))
+
+
+proxy_call_recorder = ProxyCallRecorder()
+
+
+@asynccontextmanager
+async def _scoped_session(url: str, key: str = "sk-1234", **headers: str) -> typing.AsyncIterator[ClientSession]:
+ async with asyncio.timeout(30):
+ async with _proxy_session(url, Authorization=f"Bearer {key}", **headers) as (read, write, _sid):
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ yield session
+
+
+async def _search(session: ClientSession, query: str) -> dict[str, str]:
+ result = await session.call_tool("search_tools", arguments={"query": query})
+ assert result.isError is False, result
+ return {hit["name"]: hit["tool_id"] for hit in _payload(result)}
+
+
+async def _call(session: ClientSession, tool_id: str, a: int = 3, b: int = 4) -> CallToolResult:
+ return await session.call_tool("call_tool", arguments={"tool_id": tool_id, "arguments": {"a": a, "b": b}})
+
+
+def _assert_unauthorized(result: CallToolResult) -> None:
+ assert result.isError is True
+ assert result.content[0].text == "Unknown or unauthorized tool_id"
+
+
+class TestProxyMcpAuthorizationScope:
+ @pytest.mark.asyncio
+ async def test_server_grant_bounds_search_and_blocks_foreign_ids(self, proxy_server_url: str) -> None:
+ async with _scoped_session(proxy_server_url, "sk-restricted") as granted:
+ restricted_id = (await _search(granted, "add"))["math_restricted-add"]
+ assert (await _call(granted, restricted_id)).content[0].text == "207"
+ async with _scoped_session(proxy_server_url) as ungranted:
+ assert set(await _search(ungranted, "add")) == {"math_stdio-add", "math_streamable_http-add"}
+ _assert_unauthorized(await ungranted.call_tool("get_tool_schema", {"tool_id": restricted_id}))
+ _assert_unauthorized(await _call(ungranted, restricted_id))
+
+ @pytest.mark.asyncio
+ async def test_no_mcp_servers_sentinel_hides_every_tool(self, proxy_server_url: str) -> None:
+ async with _scoped_session(proxy_server_url) as granted:
+ tool_id = (await _search(granted, "add"))["math_stdio-add"]
+ async with _scoped_session(proxy_server_url, "sk-none") as session:
+ assert await _search(session, "add") == {}
+ _assert_unauthorized(await session.call_tool("get_tool_schema", {"tool_id": tool_id}))
+ _assert_unauthorized(await _call(session, tool_id))
+
+ @pytest.mark.asyncio
+ async def test_tool_grant_hides_ungranted_tools_and_blocks_their_ids(self, proxy_server_url: str) -> None:
+ async with _scoped_session(proxy_server_url) as granted:
+ multiply_id = (await _search(granted, "multiply"))["math_stdio-multiply"]
+ async with _scoped_session(proxy_server_url, "sk-add-only", **{"x-mcp-servers": "math_stdio"}) as session:
+ ids = await _search(session, "add multiply request_headers")
+ assert set(ids) == {"math_stdio-add"}
+ assert (await _call(session, ids["math_stdio-add"])).content[0].text == "7"
+ _assert_unauthorized(await session.call_tool("get_tool_schema", {"tool_id": multiply_id}))
+ _assert_unauthorized(await _call(session, multiply_id))
+
+ @pytest.mark.asyncio
+ async def test_same_named_tools_keep_distinct_ids_and_reach_their_own_upstream(self, proxy_server_url: str) -> None:
+ async with _scoped_session(proxy_server_url, "sk-restricted") as session:
+ ids = await _search(session, "add")
+ assert set(ids) == {"math_stdio-add", "math_streamable_http-add", "math_restricted-add"}
+ assert len(set(ids.values())) == 3
+ assert all(len(tool_id) == 32 for tool_id in ids.values())
+ for name, expected in (
+ ("math_stdio-add", "7"),
+ ("math_streamable_http-add", "107"),
+ ("math_restricted-add", "207"),
+ ):
+ schema = _payload(await session.call_tool("get_tool_schema", {"tool_id": ids[name]}))
+ assert schema["name"] == name
+ assert schema["tool_id"] == ids[name]
+ result = await _call(session, ids[name])
+ assert result.isError is False
+ assert result.content[0].text == expected
+
+ @pytest.mark.asyncio
+ async def test_server_scope_header_narrows_grants_and_blocks_out_of_scope_ids(self, proxy_server_url: str) -> None:
+ async with _scoped_session(proxy_server_url, "sk-restricted") as unscoped:
+ other_id = (await _search(unscoped, "add"))["math_stdio-add"]
+ async with _scoped_session(
+ proxy_server_url, "sk-restricted", **{"x-mcp-servers": "math_restricted"}
+ ) as session:
+ ids = await _search(session, "add")
+ assert set(ids) == {"math_restricted-add"}
+ _assert_unauthorized(await session.call_tool("get_tool_schema", {"tool_id": other_id}))
+ _assert_unauthorized(await _call(session, other_id))
+ assert (await _call(session, ids["math_restricted-add"])).content[0].text == "207"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("key", [None, "sk-invalid"])
+ async def test_missing_or_invalid_key_cannot_initialize(self, proxy_server_url: str, key: str | None) -> None:
+ async with httpx.AsyncClient() as client:
+ response = await client.post(
+ f"{proxy_server_url}/mcp/proxy",
+ headers={
+ "Accept": "application/json, text/event-stream",
+ **({"Authorization": f"Bearer {key}"} if key else {}),
+ },
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-03-26",
+ "capabilities": {},
+ "clientInfo": {"name": "auth-test", "version": "1"},
+ },
+ },
+ )
+ assert response.status_code == 401, response.text
+
+ @pytest.mark.asyncio
+ async def test_server_headers_are_forwarded_only_to_the_named_upstream(self, proxy_server_url: str) -> None:
+ for tag in ("first-request", "second-request"):
+ async with _scoped_session(
+ proxy_server_url,
+ "sk-restricted",
+ **{
+ "x-mcp-math_restricted-authorization": f"Bearer {tag}",
+ "x-mcp-math_restricted-x-request-tag": tag,
+ },
+ ) as session:
+ ids = await _search(session, "request_headers")
+ for name, expected in (
+ ("math_restricted", {"authorization": f"Bearer {tag}", "x-request-tag": tag}),
+ ("math_streamable_http", {"authorization": "", "x-request-tag": ""}),
+ ):
+ result = await session.call_tool(
+ "call_tool", {"tool_id": ids[f"{name}-request_headers"], "arguments": {}}
+ )
+ assert result.isError is False
+ assert _payload(result) == expected
+
+ @pytest.mark.asyncio
+ async def test_proxy_call_emits_spend_log(self, proxy_server_url: str) -> None:
+ async with _scoped_session(proxy_server_url, "sk-restricted") as session:
+ tool_id = (await _search(session, "add"))["math_restricted-add"]
+ result = await _call(session, tool_id, 123, 456)
+ assert result.isError is False and result.content[0].text == "779"
+ async with asyncio.timeout(10):
+ while True:
+ payload = json.loads(await asyncio.to_thread(proxy_call_recorder.events.get, True, 5))
+ if payload.get("metadata", {}).get("mcp_tool_call_metadata", {}).get("arguments") == {
+ "a": 123,
+ "b": 456,
+ }:
+ break
+ assert payload["call_type"] == "call_mcp_tool"
+ assert payload["response_cost"] == 0.25
+ assert payload["status"] == "success"
+ assert payload["metadata"]["mcp_tool_call_metadata"]["mcp_server_name"] == "math_restricted"
+ assert payload["metadata"]["mcp_tool_call_metadata"]["name"] == "add"
+ assert payload["metadata"]["mcp_tool_call_metadata"]["namespaced_tool_name"] == "math_restricted/add"
+
+ @pytest.mark.parametrize("arguments", ["wrong", False, None, [], 0])
+ def test_handler_rejects_non_object_arguments(
+ self, proxy_server_url: str, _proxy_server: ProxyRig, arguments: object
+ ) -> None:
+ async def check() -> None:
+ auth = UserAPIKeyAuth(
+ object_permission=LiteLLM_ObjectPermissionTable(
+ object_permission_id="validation", mcp_servers=["math_stdio"]
+ )
+ )
+ hits = _payload(await handle_mcp_proxy_tool("search_tools", {"query": "add"}, auth))
+ tool_id = next(hit["tool_id"] for hit in hits if hit["name"] == "math_stdio-add")
+ result = await handle_mcp_proxy_tool("call_tool", {"tool_id": tool_id, "arguments": arguments}, auth)
+ assert result.isError is True
+ assert result.content[0].text == "arguments must be an object"
+
+ asyncio.run_coroutine_threadsafe(check(), _proxy_server.loop).result(timeout=30)
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_proxy_mode.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_proxy_mode.py
index 413785529d5..29711f80deb 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_proxy_mode.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_proxy_mode.py
@@ -1,355 +1,50 @@
-import json
-from collections.abc import Iterator
-from unittest.mock import AsyncMock, patch
-
import pytest
-from mcp.types import CallToolResult, TextContent, Tool
+from mcp.shared.exceptions import McpError
+from pydantic import AnyUrl
from litellm.proxy._experimental.mcp_server import server
-from litellm.proxy._experimental.mcp_server.faults.list_outcomes import AggregateToolListing
-from litellm.proxy._experimental.mcp_server.tool_search import (
- MCP_PROXY_CALL_TOOL_NAME,
- MCP_PROXY_SCHEMA_TOOL_NAME,
- MCP_PROXY_SEARCH_TOOL_NAME,
- handle_mcp_proxy_tool,
- mcp_proxy_tool_id,
- with_mcp_proxy_identity,
-)
-from litellm.proxy._types import LiteLLM_ObjectPermissionTable, UserAPIKeyAuth
-from litellm.types.mcp import MCPTransport
-from litellm.types.mcp_server.mcp_server_manager import MCPServer
+from litellm.proxy._experimental.mcp_server.mcp_context import _mcp_proxy_mode
+from litellm.proxy._types import UserAPIKeyAuth
-TOOL = Tool.model_validate(
- {
- "name": "math_stdio-add",
- "description": "Add two numbers",
- "inputSchema": {
- "type": "object",
- "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
- "required": ["a", "b"],
- },
- "outputSchema": {"type": "object"},
- "_meta": {"litellm.ai/proxy_tool_identity": {"server_id": "server-1", "tool_name": "math_stdio-add"}},
- }
-)
AUTH = UserAPIKeyAuth(api_key="key")
-def _text(result: CallToolResult) -> object:
- return json.loads(result.content[0].text)
-
-
-async def test_proxy_search_returns_opaque_id_and_schema() -> None:
- with (
- patch( # test-quality-ok: isolate authorized catalog owner
- "litellm.proxy._experimental.mcp_server.server._list_mcp_tools",
- new_callable=AsyncMock,
- return_value=AggregateToolListing(tools=[TOOL], outcomes={}),
- ),
- ):
- result = await handle_mcp_proxy_tool(MCP_PROXY_SEARCH_TOOL_NAME, {"query": "add"}, AUTH)
-
- item = _text(result)[0]
- assert item["tool_id"] == mcp_proxy_tool_id(TOOL)
- assert item["name"] == TOOL.name
- assert "inputSchema" not in item
- assert "outputSchema" not in item
- assert len(item["tool_id"]) == 32
-
-
-async def test_proxy_schema_and_call_resolve_current_authorized_catalog() -> None:
- executed = CallToolResult(content=[TextContent(type="text", text="3")], isError=False)
- with (
- patch( # test-quality-ok: isolate authorized catalog owner
- "litellm.proxy._experimental.mcp_server.server._list_mcp_tools",
- new_callable=AsyncMock,
- return_value=AggregateToolListing(tools=[TOOL], outcomes={}),
- ),
- patch( # test-quality-ok: isolate execution delegate seam
- "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_tool_call",
- new_callable=AsyncMock,
- return_value=executed,
- ) as call,
- ):
- schema = await handle_mcp_proxy_tool(
- MCP_PROXY_SCHEMA_TOOL_NAME,
- {"tool_id": mcp_proxy_tool_id(TOOL)},
- AUTH,
- )
- result = await handle_mcp_proxy_tool(
- MCP_PROXY_CALL_TOOL_NAME,
- {"tool_id": mcp_proxy_tool_id(TOOL), "arguments": {"a": 1, "b": 2}},
- AUTH,
- )
-
- assert _text(schema)["inputSchema"] == TOOL.inputSchema
- assert result is executed
- assert call.await_args.kwargs["tool_name"] == TOOL.name
- assert call.await_args.kwargs["arguments"] == {"a": 1, "b": 2}
- assert call.await_args.kwargs["requested_server_id"] == "server-1"
-
-
-async def test_proxy_rejects_stale_id_and_invalid_arguments_before_dispatch() -> None:
- with (
- patch( # test-quality-ok: isolate authorized catalog owner
- "litellm.proxy._experimental.mcp_server.server._list_mcp_tools",
- new_callable=AsyncMock,
- return_value=AggregateToolListing(tools=[TOOL], outcomes={}),
- ),
- patch( # test-quality-ok: isolate execution delegate seam
- "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_tool_call", new_callable=AsyncMock
- ) as call,
- ):
- stale = await handle_mcp_proxy_tool(MCP_PROXY_SCHEMA_TOOL_NAME, {"tool_id": "stale"}, AUTH)
- invalid = await handle_mcp_proxy_tool(
- MCP_PROXY_CALL_TOOL_NAME,
- {"tool_id": mcp_proxy_tool_id(TOOL), "arguments": "wrong"},
- AUTH,
- )
- falsy = await handle_mcp_proxy_tool(
- MCP_PROXY_CALL_TOOL_NAME,
- {"tool_id": mcp_proxy_tool_id(TOOL), "arguments": False},
- AUTH,
- )
- invalid_schema = await handle_mcp_proxy_tool(
- MCP_PROXY_CALL_TOOL_NAME,
- {"tool_id": mcp_proxy_tool_id(TOOL), "arguments": {"a": "wrong"}},
- AUTH,
- )
-
- assert stale.isError is True
- assert invalid.isError is True
- assert falsy.isError is True
- assert invalid_schema.isError is True
- call.assert_not_awaited()
-
-
-async def test_proxy_call_builds_logging_object() -> None:
- from litellm.proxy._experimental.mcp_server.mcp_context import _mcp_proxy_mode
-
- sentinel = object()
- result = CallToolResult(content=[TextContent(type="text", text="ok")], isError=False)
+def proxy_mode():
token = _mcp_proxy_mode.set(True)
try:
- with (
- patch.object( # test-quality-ok: isolate logging pipeline seam
- server, "_build_virtual_call_logging_obj", new_callable=AsyncMock, return_value=sentinel
- ) as build,
- patch( # test-quality-ok: isolate proxy dispatch seam
- "litellm.proxy._experimental.mcp_server.tool_search.handle_mcp_proxy_tool",
- new_callable=AsyncMock,
- return_value=result,
- ) as handle,
- ):
- actual = await server._dispatch_virtual_mcp_tool(
- name=MCP_PROXY_CALL_TOOL_NAME,
- arguments={"tool_id": "id", "arguments": {}},
- user_api_key_auth=AUTH,
- client_ip=None,
- )
+ yield
finally:
_mcp_proxy_mode.reset(token)
- assert actual is result
- build.assert_awaited_once()
- assert handle.await_args.kwargs["litellm_logging_obj"] is sentinel
-
@pytest.mark.asyncio
[email protected]("proxy_mode")
async def test_proxy_call_rejects_non_proxy_tool_names() -> None:
- from litellm.proxy._experimental.mcp_server.mcp_context import _mcp_proxy_mode
-
- token = _mcp_proxy_mode.set(True)
- try:
- result = await server._dispatch_virtual_mcp_tool(
- name="math_stdio-add",
- arguments={"a": 1, "b": 2},
- user_api_key_auth=AUTH,
- client_ip=None,
- )
- finally:
- _mcp_proxy_mode.reset(token)
+ result = await server._dispatch_virtual_mcp_tool(
+ name="math_stdio-add", arguments={"a": 1, "b": 2}, user_api_key_auth=AUTH, client_ip=None
+ )
assert result is not None
assert result.isError is True
- assert "unavailable" in result.content[0].text
+ assert "unavailable on /mcp/proxy" in result.content[0].text
@pytest.mark.asyncio
[email protected]("proxy_mode")
async def test_proxy_rejects_non_tool_protocol_operations() -> None:
- from mcp.shared.exceptions import McpError
- from pydantic import AnyUrl
-
- from litellm.proxy._experimental.mcp_server.mcp_context import _mcp_proxy_mode
-
- token = _mcp_proxy_mode.set(True)
- try:
- with pytest.raises(McpError):
- await server.list_prompts()
- with pytest.raises(McpError):
- await server.get_prompt("prompt", {})
- with pytest.raises(McpError):
- await server.list_resources()
- with pytest.raises(McpError):
- await server.list_resource_templates()
- with pytest.raises(McpError):
- await server.read_resource(AnyUrl("https://example.com/resource"))
- finally:
- _mcp_proxy_mode.reset(token)
-
-
-async def test_proxy_list_mode_has_fixed_definitions_without_search_flag() -> None:
- from litellm.proxy._experimental.mcp_server.mcp_context import _mcp_proxy_mode
-
- token = _mcp_proxy_mode.set(True)
- try:
- with patch( # test-quality-ok: isolate authenticated MCP context seam
- "litellm.proxy._experimental.mcp_server.server.get_or_extract_auth_context",
- new_callable=AsyncMock,
- return_value=(AUTH, None, None, None, None, None, None),
- ):
- tools = await server.handle_list_tools()
- options = server.server.create_initialization_options()
- finally:
- _mcp_proxy_mode.reset(token)
-
- assert {tool.name for tool in tools} == {
- MCP_PROXY_SEARCH_TOOL_NAME,
- MCP_PROXY_SCHEMA_TOOL_NAME,
- MCP_PROXY_CALL_TOOL_NAME,
- }
+ options = server.server.create_initialization_options()
assert options.capabilities.prompts is None
assert options.capabilities.resources is None
assert options.capabilities.tools is not None
-
-def _server(server_id: str, name: str, **overrides: object) -> MCPServer:
- return MCPServer(
- server_id=server_id,
- name=name,
- server_name=name,
- url=f"http://{name}.test",
- transport=MCPTransport.http,
- **overrides,
- )
-
-
-def _upstream_tool(prefix: str, name: str) -> Tool:
- return Tool(
- name=f"{prefix}-{name}",
- description=f"{name} numbers",
- inputSchema={"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"]},
- )
-
-
-def _auth(**object_permission: object) -> UserAPIKeyAuth:
- return UserAPIKeyAuth(
- api_key="sk-scope",
- object_permission=LiteLLM_ObjectPermissionTable(object_permission_id="scope", **object_permission),
- )
-
-
-def _ids(result: CallToolResult) -> dict[str, str]:
- return {item["name"]: item["tool_id"] for item in _text(result)}
-
-
-class TestMcpProxyAuthorizationScope:
- """The real catalog resolver runs (server grants, tool grants, scope header, sentinel); only the
- upstream tools/list fetch and the final upstream dispatch are faked."""
-
- ALPHA = _server("srv-alpha", "alpha", tool_name_to_display_name={"add": "Add Numbers"})
- BETA = _server("srv-beta", "beta")
- ALPHA_ADD = with_mcp_proxy_identity(_upstream_tool("alpha", "add"), "srv-alpha")
- ALPHA_MULTIPLY = with_mcp_proxy_identity(_upstream_tool("alpha", "multiply"), "srv-alpha")
- BETA_ADD = with_mcp_proxy_identity(_upstream_tool("beta", "add"), "srv-beta")
-
- @pytest.fixture
- def rig(self) -> Iterator[AsyncMock]:
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import global_mcp_server_manager
-
- upstream = {
- "srv-alpha": [_upstream_tool("alpha", "add"), _upstream_tool("alpha", "multiply")],
- "srv-beta": [_upstream_tool("beta", "add")],
- }
-
- async def fetch(server: MCPServer, **_: object) -> list[Tool]:
- return list(upstream[server.server_id])
-
- dispatched = AsyncMock(
- return_value=CallToolResult(content=[TextContent(type="text", text="ok")], isError=False)
- )
- global_mcp_server_manager.registry.update({"srv-alpha": self.ALPHA, "srv-beta": self.BETA})
- with (
- patch.object( # test-quality-ok: the upstream MCP server is the only faked collaborator
- global_mcp_server_manager, "_get_tools_from_server", new=AsyncMock(side_effect=fetch)
- ),
- patch.object(global_mcp_server_manager, "call_tool", new=dispatched), # test-quality-ok: dispatch seam
- ):
- yield dispatched
-
- async def _proxy(
- self, name: str, arguments: dict[str, object], auth: UserAPIKeyAuth, **kwargs: object
- ) -> CallToolResult:
- return await handle_mcp_proxy_tool(name, arguments, auth, **kwargs)
-
- @pytest.mark.asyncio
- async def test_search_and_schema_are_bounded_by_the_key_server_grant(self, rig: AsyncMock) -> None:
- granted = _auth(mcp_servers=["srv-alpha"])
-
- assert _ids(await self._proxy(MCP_PROXY_SEARCH_TOOL_NAME, {"query": "numbers"}, granted)) == {
- "alpha-add": mcp_proxy_tool_id(self.ALPHA_ADD),
- "alpha-multiply": mcp_proxy_tool_id(self.ALPHA_MULTIPLY),
- }
- denied_schema = await self._proxy(
- MCP_PROXY_SCHEMA_TOOL_NAME, {"tool_id": mcp_proxy_tool_id(self.BETA_ADD)}, granted
- )
- denied_call = await self._proxy(
- MCP_PROXY_CALL_TOOL_NAME, {"tool_id": mcp_proxy_tool_id(self.BETA_ADD), "arguments": {"a": 1}}, granted
- )
- assert denied_schema.isError is True and denied_call.isError is True
- rig.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_no_mcp_servers_sentinel_hides_every_tool(self, rig: AsyncMock) -> None:
- result = await self._proxy(
- MCP_PROXY_SEARCH_TOOL_NAME, {"query": "numbers"}, _auth(mcp_servers=["no-mcp-servers"])
- )
- assert _text(result) == []
- rig.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_tool_grant_hides_ungranted_tools_and_blocks_their_ids(self, rig: AsyncMock) -> None:
- scoped = _auth(mcp_servers=["srv-alpha"], mcp_tool_permissions={"srv-alpha": ["add"]})
-
- assert set(_ids(await self._proxy(MCP_PROXY_SEARCH_TOOL_NAME, {"query": "numbers"}, scoped))) == {"alpha-add"}
- blocked = await self._proxy(
- MCP_PROXY_CALL_TOOL_NAME, {"tool_id": mcp_proxy_tool_id(self.ALPHA_MULTIPLY), "arguments": {"a": 1}}, scoped
- )
- assert blocked.isError is True
- rig.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_same_named_tools_keep_distinct_ids_and_dispatch_to_their_own_server(self, rig: AsyncMock) -> None:
- both = _auth(mcp_servers=["srv-alpha", "srv-beta"])
-
- ids = _ids(await self._proxy(MCP_PROXY_SEARCH_TOOL_NAME, {"query": "add"}, both))
- assert set(ids) == {"alpha-add", "beta-add"}, "display-name overrides must not rename proxy identities"
- assert ids["alpha-add"] != ids["beta-add"]
-
- result = await self._proxy(MCP_PROXY_CALL_TOOL_NAME, {"tool_id": ids["beta-add"], "arguments": {"a": 1}}, both)
- assert result.isError is False
- rig.assert_awaited_once()
- assert rig.await_args.kwargs["server_name"] == "beta"
- assert rig.await_args.kwargs["name"] == "add"
-
- @pytest.mark.asyncio
- async def test_server_scope_header_narrows_search_within_the_grant(self, rig: AsyncMock) -> None:
- both = _auth(mcp_servers=["srv-alpha", "srv-beta"])
- scoped = await self._proxy(MCP_PROXY_SEARCH_TOOL_NAME, {"query": "add"}, both, mcp_servers=["beta"])
- assert set(_ids(scoped)) == {"beta-add"}
- rig.assert_not_awaited()
+ with pytest.raises(McpError):
+ await server.list_prompts()
+ with pytest.raises(McpError):
+ await server.get_prompt("prompt", {})
+ with pytest.raises(McpError):
+ await server.list_resources()
+ with pytest.raises(McpError):
+ await server.list_resource_templates()
+ with pytest.raises(McpError):
+ await server.read_resource(AnyUrl("https://example.com/resource"))