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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(mcp): preserve caller bearer for guardrail evaluation (#45746)
joshua-berrif57906c124f0
diff --git a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.pyindex 87dab4a8d67..1d86a20d80b 100644--- a/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py+++ b/litellm/proxy/_experimental/mcp_server/auth/user_api_key_auth_mcp.py@@ -8,7 +8,7 @@ from types import MappingProxyTypefrom typing import TYPE_CHECKING, Final, Literal, castfrom fastapi import HTTPException-from pydantic import TypeAdapter+from pydantic import SecretStr, TypeAdapterfrom starlette.datastructures import Headersfrom starlette.requests import Requestfrom starlette.types import Scope@@ -1532,6 +1532,11 @@ class MCPRequestHandler:_get_mcp_server_auth_headers_from_headers = get_mcp_server_auth_headers_from_headers+ @staticmethod+ def get_incoming_bearer_token(headers: Mapping[str, str]) -> SecretStr | None:+ authorization: Final = next((value for key, value in headers.items() if key.lower() == "authorization"), "")+ return SecretStr(authorization[len("bearer ") :]) if authorization.lower().startswith("bearer ") else None+@staticmethoddef get_oauth2_headers_from_headers(headers: Headers) -> dict[str, str]:"""diff --git a/litellm/proxy/_experimental/mcp_server/contracts.py b/litellm/proxy/_experimental/mcp_server/contracts.pyindex bf0fae1a210..c337c17c9ff 100644--- a/litellm/proxy/_experimental/mcp_server/contracts.py+++ b/litellm/proxy/_experimental/mcp_server/contracts.py@@ -4,10 +4,11 @@ from collections.abc import Mappingfrom copy import deepcopyfrom dataclasses import dataclass, fieldfrom datetime import datetime-from types import MappingProxyType+from types import EllipsisType, MappingProxyTypefrom typing import TYPE_CHECKING, Final, Literal, Protocol, TypeAliasfrom mcp.types import ErrorData, InputRequest, InputResponse, InputResponses+from pydantic import SecretStrfrom litellm.proxy._experimental.mcp_server.tool_outcome import WireCompatfrom litellm.proxy._types import UserAPIKeyAuth@@ -69,6 +70,7 @@ class OperationContext:mcp_proxy_mode: bool = Falsewire_compat: WireCompat = WireCompat.LEGACYprotocol_version: str | None = None+ incoming_bearer_token: SecretStr | None | EllipsisType = field(default=..., repr=False)def __post_init__(self) -> None:object.__setattr__(self, "_caller", copy_caller(self._caller))diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex 7c375969a44..e492af133ff 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -57,7 +57,7 @@ from mcp.types import (ResourceTemplate,)from mcp.types import Tool as MCPTool-from pydantic import AnyUrl, Field, TypeAdapter+from pydantic import AnyUrl, Field, SecretStr, TypeAdapterfrom typing_extensions import ReadOnly, assert_neverimport litellm@@ -5921,6 +5921,7 @@ class MCPServerManager:litellm_logging_obj: "LiteLLMLoggingObj | None" = None,guardrail_context: Mapping[str, object] | None = None,tool: MCPTool | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> dict[str, Any]:"""Run pre-call checks and guardrail hooks for an MCP tool call.@@ -5977,13 +5978,11 @@ class MCPServerManager:if proxy_logging_obj is None:return hook_result- # Extract incoming Bearer token from raw request headers so- # guardrails like MCPJWTSigner can verify + re-sign it (FR-5).- normalized_raw: Final = {k.lower(): v for k, v in (raw_headers or {}).items()}- incoming_bearer_token: str | None = None- auth_hdr: Final = normalized_raw.get("authorization", "")- if auth_hdr.lower().startswith("bearer "):- incoming_bearer_token = auth_hdr[len("bearer ") :]+ caller_bearer: Final = (+ MCPRequestHandler.get_incoming_bearer_token(raw_headers or {})+ if incoming_bearer_token is ...+ else incoming_bearer_token+ )pre_hook_kwargs: Final = {"guardrail_context": guardrail_context,@@ -5998,7 +5997,7 @@ class MCPServerManager:getattr(user_api_key_auth, "end_user_id", None) if user_api_key_auth else None),"user_api_key_hash": (getattr(user_api_key_auth, "api_key_hash", None) if user_api_key_auth else None),- "incoming_bearer_token": incoming_bearer_token,+ "incoming_bearer_token": caller_bearer.get_secret_value() if caller_bearer is not None else None,"headers": logging_safe_mcp_headers(raw_headers),"tool_description": tool.description if tool is not None else None,"tool_input_schema": tool.input_schema if tool is not None else None,@@ -6664,6 +6663,7 @@ class MCPServerManager:*,catalog_auth_header: str | None | EllipsisType = ...,listed_tool: MCPTool | None | EllipsisType = ...,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> CallToolResult | InputRequiredResult:"""Call a tool with the given name and arguments@@ -6718,6 +6718,7 @@ class MCPServerManager:litellm_logging_obj=litellm_logging_obj,guardrail_context=guardrail_context,tool=self.get_listed_tool(mcp_server, name, listed_caller) if listed_tool is ... else listed_tool,+ incoming_bearer_token=incoming_bearer_token,)if "arguments" in hook_result:arguments = hook_result["arguments"]diff --git a/litellm/proxy/_experimental/mcp_server/operations.py b/litellm/proxy/_experimental/mcp_server/operations.pyindex d98748612bc..2f0b8e64c9e 100644--- a/litellm/proxy/_experimental/mcp_server/operations.py+++ b/litellm/proxy/_experimental/mcp_server/operations.py@@ -10,6 +10,7 @@ from contextvars import ContextVarfrom dataclasses import dataclass, replacefrom datetime import datetimefrom functools import partial+from types import EllipsisTypefrom typing import Any, Final, NoReturn, TypeAlias, overloadfrom fastapi import HTTPException@@ -45,7 +46,7 @@ from mcp.types import (ToolsCapability,)from mcp.types import Tool as MCPTool-from pydantic import AnyUrl, ConfigDict, Field, TypeAdapter+from pydantic import AnyUrl, ConfigDict, Field, SecretStr, TypeAdapterfrom typing_extensions import ReadOnly, TypedDict, assert_neverfrom litellm._logging import verbose_logger@@ -352,6 +353,7 @@ async def _dispatch_virtual_mcp_tool(oauth2_headers: dict[str, str] | None = None,raw_headers: dict[str, str] | None = None,mcp_proxy_mode: bool = False,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> CallToolResult | None:"""Handle the mcp_tool_search / mcp_tool_call virtual tools.@@ -407,6 +409,7 @@ async def _dispatch_virtual_mcp_tool(oauth2_headers=oauth2_headers,raw_headers=raw_headers,litellm_logging_obj=proxy_logging_obj,+ incoming_bearer_token=incoming_bearer_token,)except Exception as exc:if proxy_logging_obj is not None:@@ -509,6 +512,7 @@ async def _dispatch_virtual_mcp_tool(oauth2_headers=oauth2_headers,raw_headers=raw_headers,litellm_logging_obj=virtual_logging_obj,+ incoming_bearer_token=incoming_bearer_token,)@@ -1874,6 +1878,7 @@ async def execute_mcp_tool(wire_compat: WireCompat = WireCompat.LEGACY,input_responses: InputResponses | None = None,request_state: str | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,**kwargs: object, # kwargs-ok: preserves the existing REST and decorated logging call contract) -> CallToolResult | InputRequiredResult:context: Final = prepare_context(@@ -1884,6 +1889,7 @@ async def execute_mcp_tool(raw_headers=raw_headers,client_ip=client_ip,wire_compat=wire_compat,+ incoming_bearer_token=incoming_bearer_token,)operation: Final = AuthorizedToolCall(name=name,@@ -1915,6 +1921,7 @@ async def _execute_mcp_tool(wire_compat: WireCompat = WireCompat.LEGACY,input_responses: InputResponses | None = None,request_state: str | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,**kwargs: Any,) -> CallToolResult | InputRequiredResult:"""@@ -2152,6 +2159,7 @@ async def _execute_mcp_tool(oauth2_headers,),),+ incoming_bearer_token=incoming_bearer_token,)# `pre_call_tool_check` may return guardrail-modified# arguments; honor them on the local path too.@@ -2212,6 +2220,7 @@ async def _execute_mcp_tool(wire_compat=wire_compat,input_responses=input_responses,request_state=request_state,+ incoming_bearer_token=incoming_bearer_token,)# Fall back to local tool registry with original name (legacy support)@@ -2284,6 +2293,7 @@ async def _execute_mcp_tool(oauth2_headers,),),+ incoming_bearer_token=incoming_bearer_token,)if "arguments" in hook_result:arguments = hook_result["arguments"] # pyright: ignore[reportAny] # hook returns untyped args@@ -2455,6 +2465,7 @@ async def call_mcp_tool(wire_compat: WireCompat = WireCompat.LEGACY,input_responses: InputResponses | None = None,request_state: str | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,**kwargs: Any,) -> CallToolResult | InputRequiredResult:"""@@ -2515,6 +2526,7 @@ async def call_mcp_tool(wire_compat=wire_compat,input_responses=input_responses,request_state=request_state,+ incoming_bearer_token=incoming_bearer_token,**kwargs,)except Exception as e:@@ -2709,6 +2721,7 @@ async def _handle_managed_mcp_tool(request_state: str | None = None,*,catalog_auth_header: str | None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> CallToolResult | InputRequiredResult:"""Handle tool execution for managed server tools. ``catalog_auth_header`` is the header the clientsupplied, which keys the caller's catalog slot; ``mcp_auth_header`` may already be the resolved@@ -2734,6 +2747,7 @@ async def _handle_managed_mcp_tool(wire_compat=wire_compat,input_responses=input_responses,request_state=request_state,+ incoming_bearer_token=incoming_bearer_token,)verbose_logger.debug("CALL TOOL RESULT: %s", call_tool_result)return call_tool_result@@ -2908,6 +2922,7 @@ async def _execute_mcp_server_tool_call(oauth2_headers=oauth2_headers,raw_headers=raw_headers,mcp_proxy_mode=context.mcp_proxy_mode,+ incoming_bearer_token=context.incoming_bearer_token,)if virtual_tool_result is not None:return virtual_tool_result@@ -2957,6 +2972,7 @@ async def _execute_mcp_server_tool_call(wire_compat=context.wire_compat,input_responses=params.input_responses,request_state=params.request_state,+ incoming_bearer_token=context.incoming_bearer_token,**data, # for logging)except MCPMissingUserEnvVarsError as e:@@ -3184,6 +3200,7 @@ def prepare_context(mcp_proxy_mode: bool = False,wire_compat: WireCompat = WireCompat.LEGACY,protocol_version: str | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> OperationContext:return OperationContext(_caller=user_api_key_auth,@@ -3196,6 +3213,7 @@ def prepare_context(mcp_proxy_mode=mcp_proxy_mode,wire_compat=wire_compat,protocol_version=protocol_version,+ incoming_bearer_token=incoming_bearer_token,)@@ -3376,6 +3394,7 @@ class GatewayOperations:wire_compat=context.wire_compat,input_responses=operation.input_responses,request_state=operation.request_state,+ incoming_bearer_token=context.incoming_bearer_token,**operation.logging_data,)case ListToolsRequest(params=params):diff --git a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py b/litellm/proxy/_experimental/mcp_server/rest_endpoints.pyindex 496c92f88ee..38f526bcd13 100644--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py@@ -229,6 +229,7 @@ if MCP_AVAILABLE:from litellm.llms.litellm_proxy.skills.skill_search import (DEFAULT_SKILL_SEARCH_TOP_K,)+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandlerfrom litellm.proxy._experimental.mcp_server.mcp_server_manager import ( # noqa: F401 # legacy module exports_UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES, # pyright: ignore[reportPrivateUsage,reportUnusedImport] # backwards-compatible package exportUPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES,@@ -411,6 +412,7 @@ if MCP_AVAILABLE:raw_headers=virtual_raw_headers,litellm_logging_obj=virtual_logging_obj,guardrail_context=MCPRequestContext.resolve_guardrail_context(virtual_data),+ incoming_bearer_token=MCPRequestHandler.get_incoming_bearer_token(request.headers),)except Exception as e:virtual_request_data: Final = virtual_processor.data@@ -1344,6 +1346,7 @@ if MCP_AVAILABLE:litellm_logging_obj=data.get("litellm_logging_obj"),guardrail_context=MCPRequestContext.resolve_guardrail_context(data),requested_server_id=canonical_server_id,+ incoming_bearer_token=MCPRequestHandler.get_incoming_bearer_token(request.headers),)result: Final = complete_call_tool_result(executed, WireCompat.LEGACY)except Exception as e:diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex bf813eaff2b..17d3c343756 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -838,6 +838,7 @@ if MCP_AVAILABLE:headers,client_ip,) = await get_or_extract_auth_context()+ request: Final[object] = getattr(ctx, "request", None)yield operations.prepare_context(auth,token,@@ -849,6 +850,11 @@ if MCP_AVAILABLE:_mcp_proxy_mode.get(),wire_compat_for(ctx.protocol_version),ctx.protocol_version,+ incoming_bearer_token=(+ MCPRequestHandler.get_incoming_bearer_token(request.headers)+ if isinstance(request, StarletteRequest)+ else None+ ),)async def handle_list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams) -> ListToolsResult:diff --git a/litellm/proxy/_experimental/mcp_server/tool_search.py b/litellm/proxy/_experimental/mcp_server/tool_search.pyindex 217ffcd6b5f..a8aff2b2e4b 100644--- a/litellm/proxy/_experimental/mcp_server/tool_search.py+++ b/litellm/proxy/_experimental/mcp_server/tool_search.py@@ -8,13 +8,13 @@ from collections.abc import Iterator, Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetimefrom itertools import chain, islice-from types import MappingProxyType+from types import EllipsisType, MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, TypedDictimport anyiofrom anyio import to_processfrom anyio.lowlevel import RunVar-from pydantic import JsonValue, ValidationError+from pydantic import JsonValue, SecretStr, ValidationErrorfrom typing_extensions import ReadOnly, Required, assert_neverimport litellm@@ -588,6 +588,7 @@ async def handle_mcp_proxy_tool(oauth2_headers: dict[str, str] | None = None, # mutable-ok: preserve forwarded headersraw_headers: dict[str, str] | None = None, # mutable-ok: preserve request headerslitellm_logging_obj: LiteLLMLoggingObj | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> CallToolResult:from fastapi import HTTPException@@ -662,6 +663,7 @@ async def handle_mcp_proxy_tool(oauth2_headers=oauth2_headers,raw_headers=raw_headers,litellm_logging_obj=litellm_logging_obj,+ incoming_bearer_token=incoming_bearer_token,)@@ -678,6 +680,7 @@ async def handle_mcp_tool_call(litellm_logging_obj: LiteLLMLoggingObj | None = None,requested_server_id: str | None = None,guardrail_context: Mapping[str, object] | None = None,+ incoming_bearer_token: SecretStr | None | EllipsisType = ...,) -> CallToolResult:from litellm.proxy._experimental.mcp_server.operations import (_get_allowed_mcp_servers,@@ -719,5 +722,6 @@ async def handle_mcp_tool_call(litellm_logging_obj=litellm_logging_obj,requested_server_id=requested_server_id,guardrail_context=guardrail_context,+ incoming_bearer_token=incoming_bearer_token,)return complete_call_tool_result(result, WireCompat.LEGACY)diff --git a/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py b/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.pyindex ad94defebd7..adae7872430 100644--- a/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py+++ b/tests/unit/proxy/_experimental/mcp_server/auth/test_user_api_key_auth_mcp.py@@ -26,6 +26,24 @@ from litellm.proxy._types import (from litellm.types.agents import AgentCaller[email protected]("headers,expected", [+ ({"Authorization": "Bearer caller.jwt.signature"}, "caller.jwt.signature"),+ ({"AUTHORIZATION": "bEaReR caller.jwt.signature"}, "caller.jwt.signature"),+ ({"authorization": "Bearer "}, ""),+ ({"authorization": "Basic credentials"}, None),+ ({"authorization-extra": "Bearer wrong.jwt.signature"}, None),+ ({"x-litellm-api-key": "sk-key"}, None),+ ({}, None),+])+def test_incoming_guardrail_bearer_requires_exact_authorization_header(+ headers: dict[str, str], expected: str | None,+) -> None:+ token: Final = MCPRequestHandler.get_incoming_bearer_token(headers)+ assert (token.get_secret_value() if token is not None else None) == expected+ if expected:+ assert expected not in repr(token)++@pytest.mark.asyncioclass TestMCPRequestHandler:@pytest.mark.parametrize(diff --git a/tests/unit/proxy/_experimental/mcp_server/test_contracts.py b/tests/unit/proxy/_experimental/mcp_server/test_contracts.pyindex e13ecdfcce9..db877bd4395 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_contracts.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_contracts.py@@ -1,11 +1,24 @@from dataclasses import FrozenInstanceError+from typing import Finalimport pytest+from pydantic import SecretStrfrom litellm.proxy._experimental.mcp_server.operations import prepare_contextfrom litellm.proxy._types import UserAPIKeyAuth+def test_guardrail_bearer_stays_out_of_egress_and_context_representations() -> None:+ token: Final = SecretStr("caller.jwt.signature")+ context: Final = prepare_context(incoming_bearer_token=token)+ assert context.incoming_bearer_token is token+ assert token.get_secret_value() not in repr(context)+ assert token not in context.legacy_auth()+ assert context.raw_headers is None+ assert context.oauth2_headers is None+ assert context.mcp_server_auth_headers is None++def test_operation_context_isolates_nested_headers_and_caller_permissions():caller = UserAPIKeyAuth(user_id="alpha", models=["allowed"])caller.mcp_admitted_user_subject = Truediff --git a/tests/unit/proxy/_experimental/mcp_server/test_operations.py b/tests/unit/proxy/_experimental/mcp_server/test_operations.pyindex 25c80398e46..32a7c3fbe58 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_operations.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_operations.py@@ -1,9 +1,10 @@import asyncio-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom typing import Finalfrom unittest.mock import AsyncMock, patchimport pytest+from mcp.server.context import ServerRequestContextfrom mcp.types import GetPromptRequest, GetPromptRequestParams, GetPromptResultfrom mcp.types import Tool as MCPTool@@ -43,6 +44,116 @@ async def _served_catalog_tool() -> str:return "ok"[email protected]("mode", ["direct", "virtual", "proxy"])[email protected]("verdict", ["allow", "block", "obo_error", "evaluate_error", "missing"])+async def test_mapped_caller_bearer_reaches_agent_evaluation(+ monkeypatch: pytest.MonkeyPatch, _mcp_request_ctx: Callable[..., ServerRequestContext],+ mode: str, verdict: str, caplog: pytest.LogCaptureFixture,+) -> None:+ from urllib.parse import parse_qs++ import httpx+ from mcp.server.auth.middleware.auth_context import auth_context_var+ from mcp.types import CallToolRequest, CallToolRequestParams, CallToolResult, TextContent+ from starlette.requests import Request++ from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler+ from litellm.proxy._experimental.mcp_server import server as gateway+ from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import MCPRequestHandler+ from litellm.proxy._experimental.mcp_server.mcp_context import _mcp_proxy_mode+ from litellm.proxy._experimental.mcp_server.tool_search import mcp_proxy_tool_id, with_mcp_proxy_identity+ from litellm.proxy.guardrails.guardrail_hooks.agent_365.agent_365 import Agent365Guardrail++ bearer: Final = "signed.caller.assertion"+ request: Final = Request({+ "type": "http", "method": "POST", "path": "/mcp",+ "headers": [] if verdict == "missing" else [(b"authorization", f"Bearer {bearer}".encode())],+ })+ auth: Final = UserAPIKeyAuth(+ api_key="stored-key-hash", user_id="mapped-caller",+ object_permission={"object_permission_id": "mapped", "mcp_servers": ["guarded"], "mcp_tool_search_enabled": mode == "virtual"},+ )+ oauth, raw, _, _ = MCPRequestHandler.scrub_gateway_admission_credentials(+ admitted=False, admitted_credential=bearer,+ oauth2_headers={"Authorization": f"Bearer {bearer}"},+ raw_headers=dict(request.headers), mcp_auth_header=None, mcp_server_auth_headers=None,+ )+ assert "authorization" not in raw+ provider_requests: Final[asyncio.Queue[str]] = asyncio.Queue()++ def provider(exchange: httpx.Request) -> httpx.Response:+ provider_requests.put_nowait(exchange.url.path)+ if exchange.url.path.endswith("/token"):+ assert parse_qs(exchange.content.decode())["assertion"] == [bearer]+ if verdict == "obo_error":+ return httpx.Response(400, json={"error": "invalid_grant"})+ return httpx.Response(200, json={"access_token": "delegated-token", "expires_in": 3600})+ assert exchange.headers["authorization"] == "Bearer delegated-token"+ if verdict == "evaluate_error":+ return httpx.Response(503, json={"error": "unavailable"})+ return httpx.Response(200, json={+ "allowed": verdict == "allow", "defender": {"status": "Evaluated", "verdict": "Allow" if verdict == "allow" else "Block"},+ })++ executions: Final[asyncio.Queue[str]] = asyncio.Queue()++ async def tool() -> str:+ from litellm.proxy._experimental.mcp_server.openapi_to_mcp_generator import request_extra_headers++ assert bearer not in str(request_extra_headers.get())+ executions.put_nowait("executed")+ return "ok"++ handler: Final = AsyncHTTPHandler(transport=httpx.MockTransport(provider))+ guardrail: Final = Agent365Guardrail(+ guardrail_name="agent-evaluation", tenant_id="tenant", client_id="gateway", client_secret="secret",+ async_handler=handler, event_hook="pre_mcp_call", default_on=True,+ )+ monkeypatch.setattr(litellm, "callbacks", [guardrail])+ managed: Final = MCPServer(+ server_id="guarded", name="guarded", transport=MCPTransport.http,+ spec_path="/catalog.yaml", allow_all_keys=True,+ )+ monkeypatch.setitem(operations.global_mcp_server_manager.registry, managed.server_id, managed)+ global_mcp_tool_registry.register_tool(+ name="guarded-echo", description="Echo", input_schema={"type": "object"}, handler=tool,+ )+ previous: Final = auth_context_var.set(None)+ proxy_mode: Final = _mcp_proxy_mode.set(mode == "proxy")+ tool_id: Final = mcp_proxy_tool_id(with_mcp_proxy_identity(+ MCPTool(name="guarded-echo", input_schema={"type": "object"}), managed.server_id,+ ))+ params: Final = {+ "direct": CallToolRequestParams(name="guarded-echo", arguments={}),+ "virtual": CallToolRequestParams(name="mcp_tool_call", arguments={"tool_name": "guarded-echo", "arguments": {}}),+ "proxy": CallToolRequestParams(name="call_tool", arguments={"tool_id": tool_id, "arguments": {}}),+ }[mode]+ try:+ gateway.set_auth_context(+ auth, mcp_servers=[managed.server_id], oauth2_headers=oauth,+ raw_headers={"authorization": "Bearer previous.caller.assertion"} if verdict == "missing" else raw,+ )+ async with gateway._legacy_operation_context(_mcp_request_ctx(request=request), trace=False) as context:+ result: Final = await GatewayOperations().execute(+ CallToolRequest(params=params), context,+ )+ assert isinstance(result, CallToolResult)+ assert result.is_error is (verdict != "allow")+ assert executions.qsize() == (1 if verdict == "allow" else 0)+ assert provider_requests.qsize() == (0 if verdict == "missing" else 1 if verdict == "obo_error" else 2)+ assert bearer not in caplog.text+ assert bearer not in repr(context)+ if verdict == "allow":+ assert isinstance(result.content[0], TextContent)+ assert result.content[0].text == "ok"+ finally:+ auth_context_var.reset(previous)+ _mcp_proxy_mode.reset(proxy_mode)+ global_mcp_tool_registry.unregister_tools_with_prefix("guarded-")+ await handler.close()++@pytest.mark.asyncio@pytest.mark.parametrize("surface", ["mcp", "rest"])@pytest.mark.parametrize("restriction", ["key", "server"])