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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_mcp_test_connection_oauth_bearer
mateo-berrib45670b4b4c6
diff --cc litellm/proxy/_experimental/mcp_server/rest_endpoints.pyindex a1583154916,d1ef73a15cd..e7ba7168ba0--- a/litellm/proxy/_experimental/mcp_server/rest_endpoints.py+++ b/litellm/proxy/_experimental/mcp_server/rest_endpoints.py@@@ -1,15 -1,16 +1,18 @@@import asyncioimport importlib- from collections.abc import Awaitable, Callable, Mapping+ from collections.abc import Awaitable, Callable, Mapping, Sequence+from dataclasses import dataclassfrom datetime import datetime+ from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, Literal+ import anyioimport httpxfrom fastapi import APIRouter, Depends, HTTPException, Query, Request, status+from starlette.datastructures import Headersfrom litellm._logging import verbose_logger+ from litellm.constants import MCP_CLIENT_TIMEOUT, MCP_TOOL_LISTING_TIMEOUTfrom litellm.exceptions import (BlockedPiiEntityError,GuardrailRaisedException,@@@ -1414,18 -1381,61 +1426,35 @@@ if MCP_AVAILABLE},)- new_mcp_server_request = _inherit_credentials_from_existing_server(new_mcp_server_request)+ staged: Final = _stage_server_test(new_mcp_server_request, request.headers)# For OpenAPI spec servers, generate tools from the spec directly- if new_mcp_server_request.spec_path:- return await _preview_openapi_tools(new_mcp_server_request.spec_path)-- from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (- MCPRequestHandler,- )-- headers: Final = request.headers-- mcp_auth_header: str | None = None- if new_mcp_server_request.auth_type in {- MCPAuth.api_key,- MCPAuth.bearer_token,- MCPAuth.basic,- MCPAuth.authorization,- }:- credentials: Final = getattr(new_mcp_server_request, "credentials", None)- if isinstance(credentials, dict):- mcp_auth_header = credentials.get("auth_value")-- # Authorization doubles as the admission fallback (LITELLM_API_KEY_HEADER_NAME_SECONDARY):- # when the primary x-litellm-api-key header is absent, the Authorization value is the- # caller's LiteLLM key, not an upstream token, and must never be forwarded upstream.- oauth2_headers: dict[str, str] | None = None- if new_mcp_server_request.auth_type in _UPSTREAM_OAUTH_DISCOVERY_AUTH_TYPES and headers.get(- MCPRequestHandler.LITELLM_API_KEY_HEADER_NAME_PRIMARY- ):- oauth2_headers = MCPRequestHandler._get_oauth2_headers_from_headers(headers)+ if staged.request.spec_path:+ return await _preview_openapi_tools(staged.request.spec_path)async def _list_tools_operation(client):- async def _list_tools_session_operation(session):- return await session.list_tools()-- list_tools_response: Final = await client.run_with_session(_list_tools_session_operation)- list_tools_result: Final[list[MCPTool]] = list_tools_response.tools+ # Bound the whole pagination walk: without this the preview is limited only by the+ # per-request timeout times the page cap. max() keeps the pre-pagination guarantee+ # that a single slow page within the client timeout still succeeds, and a+ # per-server timeout above the global default extends the deadline with it.+ listing_deadline: Final = max(+ getattr(client, "timeout", MCP_CLIENT_TIMEOUT) or MCP_CLIENT_TIMEOUT,+ MCP_TOOL_LISTING_TIMEOUT,+ )+ list_tools_result = None # rebind-ok: set inside the timeout scope below+ with anyio.move_on_after(listing_deadline):+ list_tools_result = await client.list_tools(raise_on_error=True) # rebind-ok: fills the init above+ if list_tools_result is None:+ verbose_logger.warning(+ "MCP tools/list preview timed out after %s seconds while paginating upstream tools",+ listing_deadline,+ )+ return { # mutable-ok: error response payload+ "status": "error",+ "error": True,+ "message": f"Timed out listing tools after {listing_deadline} seconds. "+ "The MCP server may be responding slowly or paginating excessively.",+ }model_dumped_tools: Final[list[dict]] = [tool.model_dump() for tool in list_tools_result]return {"tools": model_dumped_tools,