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): sanitize Anthropic tool schemas and stop encoding gateway names
Tin Chi Lo56cda9f674d8
diff --git a/litellm/experimental_mcp_client/tools.py b/litellm/experimental_mcp_client/tools.pyindex 1bd65847616..500d226752b 100644--- a/litellm/experimental_mcp_client/tools.py+++ b/litellm/experimental_mcp_client/tools.py@@ -9,7 +9,7 @@ from openai.types.chat import ChatCompletionToolParamfrom openai.types.responses.function_tool_param import FunctionToolParamfrom openai.types.shared_params.function_definition import FunctionDefinition-from litellm.types.llms.anthropic import AnthropicInputSchema, AnthropicMessagesTool+from litellm.types.llms.anthropic import AnthropicMessagesToolfrom litellm.types.utils import ChatCompletionMessageToolCall@@ -78,12 +78,14 @@ def transform_mcp_tool_to_openai_responses_api_tool(def transform_mcp_tool_to_anthropic_tool(mcp_tool: MCPTool) -> AnthropicMessagesTool:"""Convert an MCP tool to an Anthropic Messages API tool."""- normalized_parameters = _normalize_mcp_input_schema(mcp_tool.inputSchema)+ from litellm.litellm_core_utils.prompt_templates.common_utils import (+ sanitize_input_schema_for_anthropic,+ )return AnthropicMessagesTool(name=mcp_tool.name,description=mcp_tool.description or "",- input_schema=AnthropicInputSchema(**normalized_parameters),+ input_schema=sanitize_input_schema_for_anthropic(mcp_tool.inputSchema),type="custom",)diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.pyindex 538d5f650ef..c43089950ee 100644--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py@@ -42,6 +42,7 @@ from litellm.types.utils import ()if TYPE_CHECKING: # newer pattern to avoid importing pydantic objects on __init__.py+ from litellm.types.llms.anthropic import AnthropicInputSchemafrom litellm.types.llms.openai import ChatCompletionImageObjectDEFAULT_USER_CONTINUE_MESSAGE = ChatCompletionUserMessage(content="Please continue.", role="user")@@ -1046,6 +1047,31 @@ def unpack_legacy_defs(return schema+def sanitize_input_schema_for_anthropic(input_schema: dict) -> "AnthropicInputSchema":+ """Coerce an arbitrary tool input_schema into the shape Anthropic accepts.++ Anthropic requires ``type == "object"``, only recognises ``$defs`` (legacy+ ``definitions`` / OpenAPI ``components.schemas`` refs must be inlined first),+ and rejects keys outside ``AnthropicInputSchema``. Both the chat+ (``AnthropicConfig._map_tool_helper``) and Anthropic Messages MCP paths run+ a schema through here so an external MCP schema cannot succeed on one route+ and 400 on the other.+ """+ from litellm.types.llms.anthropic import AnthropicInputSchema++ normalized = dict(input_schema) if input_schema else {}+ if normalized.get("type") != "object":+ normalized["type"] = "object"+ if "properties" not in normalized:+ normalized["properties"] = {}++ normalized = unpack_legacy_defs(normalized, copy=True)++ allowed_keys = set(AnthropicInputSchema.__annotations__.keys())+ filtered = {key: value for key, value in normalized.items() if key in allowed_keys}+ return AnthropicInputSchema(**filtered)++def _get_image_mime_type_from_url(url: str) -> Optional[str]:"""Get mime type for common image URLsdiff --git a/litellm/llms/anthropic/chat/transformation.py b/litellm/llms/anthropic/chat/transformation.pyindex 0ec1f3eae13..5a0f274e3ca 100644--- a/litellm/llms/anthropic/chat/transformation.py+++ b/litellm/llms/anthropic/chat/transformation.py@@ -29,7 +29,9 @@ from litellm.constants import (RESPONSE_FORMAT_TOOL_NAME,)from litellm.litellm_core_utils.core_helpers import map_finish_reason-from litellm.litellm_core_utils.prompt_templates.common_utils import unpack_legacy_defs+from litellm.litellm_core_utils.prompt_templates.common_utils import (+ sanitize_input_schema_for_anthropic,+)from litellm.llms.base_llm.base_utils import type_to_response_format_paramfrom litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMExceptionfrom litellm.types.llms.anthropic import (@@ -634,7 +636,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):mcp_server: Optional[AnthropicMcpServerTool] = Noneif tool["type"] == "function" or tool["type"] == "custom":- _input_schema: dict = tool["function"].get(+ _input_schema = tool["function"].get("parameters",{"type": "object",@@ -642,28 +644,7 @@ class AnthropicConfig(AnthropicModelInfo, BaseConfig):},)- # Anthropic requires input_schema.type to be "object". Normalize- # schemas from external sources (MCP servers, OpenAI callers) that- # may omit the type field or use a non-object type.- if _input_schema.get("type") != "object":- litellm.verbose_logger.debug(- "_map_tool_helper: coercing input_schema type from %r to "- "'object' for Anthropic compatibility (tool: %s)",- _input_schema.get("type"),- tool["function"].get("name"),- )- _input_schema = dict(_input_schema) # avoid mutating caller's dict- _input_schema["type"] = "object"- if "properties" not in _input_schema:- _input_schema["properties"] = {}-- # Inline legacy / OpenAPI $refs before the allow-list filter strips- # their backing def blocks (https://github.com/BerriAI/litellm/issues/26692).- _input_schema = unpack_legacy_defs(_input_schema, copy=True)-- _allowed_properties = set(AnthropicInputSchema.__annotations__.keys())- input_schema_filtered = {k: v for k, v in _input_schema.items() if k in _allowed_properties}- input_anthropic_schema: AnthropicInputSchema = AnthropicInputSchema(**input_schema_filtered)+ input_anthropic_schema = sanitize_input_schema_for_anthropic(_input_schema)_tool = AnthropicMessagesTool(name=tool["function"]["name"],diff --git a/tests/test_litellm/experimental_mcp_client/test_tools.py b/tests/test_litellm/experimental_mcp_client/test_tools.pyindex 625ab56951f..804e99b6f4e 100644--- a/tests/test_litellm/experimental_mcp_client/test_tools.py+++ b/tests/test_litellm/experimental_mcp_client/test_tools.py@@ -299,3 +299,45 @@ def test_transform_mcp_tool_to_anthropic_tool_normalizes_empty_schema():assert anthropic_tool["description"] == ""assert anthropic_tool["input_schema"]["type"] == "object"assert anthropic_tool["input_schema"]["properties"] == {}+++def test_transform_mcp_tool_to_anthropic_tool_strips_keys_anthropic_rejects():+ """+ Regression test (LIT-4517): an MCP schema with keys Anthropic does not accept+ must be sanitized, so the same tool cannot succeed on /chat/completions and 400+ on /v1/messages.++ Given: An MCP tool whose inputSchema carries $schema, legacy definitions and oneOf+ When: It is transformed for the Anthropic Messages API+ Then: Only keys in AnthropicInputSchema survive, matching the chat path++ The chat path runs the schema through the same sanitizer, so before this the two+ routes diverged: a clean-schema server (deepwiki) worked on both, but a server+ with a richer schema would be rejected only on messages.+ """+ from litellm.types.llms.anthropic import AnthropicInputSchema++ tool = MCPTool(+ name="rich",+ description="tool with a dirty schema",+ inputSchema={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ "required": ["q"],+ "$schema": "http://json-schema.org/draft-07/schema#",+ "definitions": {"D": {"type": "string"}},+ "oneOf": [{"required": ["q"]}],+ },+ )++ anthropic_tool = transform_mcp_tool_to_anthropic_tool(tool)+ schema_keys = set(anthropic_tool["input_schema"].keys())++ assert schema_keys <= set(AnthropicInputSchema.__annotations__.keys()), (+ f"schema must only carry keys Anthropic accepts, got {schema_keys}"+ )+ assert "$schema" not in schema_keys+ assert "definitions" not in schema_keys+ assert "oneOf" not in schema_keys+ assert anthropic_tool["input_schema"]["properties"] == {"q": {"type": "string"}}+ assert anthropic_tool["input_schema"]["required"] == ["q"]diff --git a/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.test.ts b/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.test.tsnew file mode 100644index 00000000000..62dd4d2631c--- /dev/null+++ b/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.test.ts@@ -0,0 +1,63 @@+import { describe, it, expect } from "vitest";+import { buildMcpToolBlocks } from "./mcp_tool_blocks";+import { MCPServer, MCPToolset } from "@/components/mcp_tools/types";++const server = (over: Partial<MCPServer>): MCPServer =>+ ({+ server_id: "id-1",+ server_name: "deepwiki",+ alias: "wiki",+ url: "",+ transport: "http",+ auth_type: "none",+ ...over,+ }) as any;++describe("buildMcpToolBlocks", () => {+ it("returns no blocks when nothing is selected", () => {+ expect(buildMcpToolBlocks({ selectedMCPServers: [] })).toEqual([]);+ expect(buildMcpToolBlocks({ selectedMCPServers: undefined })).toEqual([]);+ });++ it("routes by server_name, not alias, so colliding aliases cannot cross-route", () => {+ const [block] = buildMcpToolBlocks({+ selectedMCPServers: ["id-1"],+ mcpServers: [server({})],+ });+ expect(block.server_url).toBe("litellm_proxy/mcp/deepwiki");+ expect(block.server_label).toBe("deepwiki");+ });++ it("does not percent-encode the name; the gateway splits the raw path and never decodes", () => {+ const [block] = buildMcpToolBlocks({+ selectedMCPServers: ["id-1"],+ mcpServers: [server({ server_name: "my server" }) as any],+ });+ expect(block.server_url).toBe("litellm_proxy/mcp/my server");+ expect(block.server_url).not.toContain("%20");+ });++ it("passes per-server tool restrictions through as allowed_tools", () => {+ const [block] = buildMcpToolBlocks({+ selectedMCPServers: ["id-1"],+ mcpServers: [server({})],+ mcpServerToolRestrictions: { "id-1": ["read_wiki_structure"] },+ });+ expect(block.allowed_tools).toEqual(["read_wiki_structure"]);+ });++ it("collapses the all-servers sentinel to a single proxy-wide block", () => {+ expect(buildMcpToolBlocks({ selectedMCPServers: ["__all__", "id-1"] })).toEqual([+ { type: "mcp", server_label: "litellm", server_url: "litellm_proxy/mcp", require_approval: "never" },+ ]);+ });++ it("routes a toolset by its name", () => {+ const toolset = { toolset_id: "ts-1", toolset_name: "docs" } as MCPToolset;+ const [block] = buildMcpToolBlocks({+ selectedMCPServers: ["toolset:ts-1"],+ mcpToolsets: [toolset],+ });+ expect(block.server_url).toBe("litellm_proxy/mcp/docs");+ });+});diff --git a/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.ts b/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.tsindex 42fa94d8208..401d9fd9c84 100644--- a/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.ts+++ b/ui/litellm-dashboard/src/components/llm_calls/mcp_tool_blocks.ts@@ -29,6 +29,10 @@ export interface BuildMcpToolBlocksArgs {* server_name is used for both routing and labelling because it is the unique* registered identifier; aliases can collide across servers, and a duplicated* server_label causes silent tool-routing failures.+ *+ * The name is not percent-encoded: the gateway resolves it with a raw+ * `server_url.split("/")[-1]` and never url-decodes, so an encoded name would+ * fail server lookup rather than round-trip.*/export function buildMcpToolBlocks({selectedMCPServers,@@ -59,7 +63,7 @@ export function buildMcpToolBlocks({return {type: "mcp",server_label: toolsetName,- server_url: `litellm_proxy/mcp/${encodeURIComponent(toolsetName)}`,+ server_url: `litellm_proxy/mcp/${toolsetName}`,require_approval: "never",};}@@ -71,7 +75,7 @@ export function buildMcpToolBlocks({return {type: "mcp",server_label: routeName,- server_url: `litellm_proxy/mcp/${encodeURIComponent(routeName)}`,+ server_url: `litellm_proxy/mcp/${routeName}`,require_approval: "never",...(allowedTools.length > 0 ? { allowed_tools: allowedTools } : {}),};