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(bedrock): drop dangerous-tool-use beta without safeguards (#44471)
AxelRay388251a5b863
diff --git a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.pyindex 04747405375..fc6088ddc66 100644--- a/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py+++ b/litellm/llms/bedrock/chat/invoke_transformations/anthropic_claude3_transformation.py@@ -32,6 +32,7 @@ from litellm.llms.bedrock.common_utils import (tools_without_eager_input_streaming,)from litellm.types.llms.anthropic import (+ ANTHROPIC_BETA_HEADER_VALUES,ANTHROPIC_FINE_GRAINED_TOOL_STREAMING_BETA_HEADER,ANTHROPIC_TOOL_SEARCH_BETA_HEADER,AnthropicThinkingParam,@@ -270,7 +271,12 @@ class AmazonAnthropicClaudeConfig(AmazonInvokeConfig, AnthropicConfig):is_mid_conversation_output_config_used: Final = self.is_mid_conversation_output_config_used(messages)is_thinking_display_updates_used: Final = self.is_thinking_display_updates_used(thinking)- user_beta_set: Final = set(get_anthropic_beta_from_headers(headers))+ client_beta_set: Final = set(get_anthropic_beta_from_headers(headers))+ user_beta_set: Final = (+ client_beta_set+ if "safeguards" in optional_params+ else client_beta_set - {ANTHROPIC_BETA_HEADER_VALUES.DANGEROUS_TOOL_USE_2026_09_03.value}+ )beta_set: Final = set(user_beta_set)auto_betas: Final = self.get_anthropic_beta_list(model=model,diff --git a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.pyindex 88ae0d4d514..95e81fa3ee7 100644--- a/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py+++ b/litellm/llms/bedrock/messages/invoke_transformations/anthropic_claude3_transformation.py@@ -90,6 +90,9 @@ class AmazonAnthropicClaudeMessagesConfig(def beta_headers_provider(self) -> str:return self.custom_llm_provider or "bedrock"+ def drops_dangerous_tool_use_beta_without_safeguards(self) -> bool:+ return True+BEDROCK_INVOKE_ALLOWED_TOP_LEVEL_FIELDS = frozenset(BedrockInvokeAnthropicMessagesRequest.__annotations__.keys())def get_error_class(@@ -552,8 +555,17 @@ class AmazonAnthropicClaudeMessagesConfig(if anthropic_model_info.is_eager_input_streaming_used(tools):beta_set.add(ANTHROPIC_FINE_GRAINED_TOOL_STREAMING_BETA_HEADER)+ dangerous_tool_use_beta: Final = ANTHROPIC_BETA_HEADER_VALUES.DANGEROUS_TOOL_USE_2026_09_03.valueif anthropic_messages_optional_request_params.get("safeguards") is not None:- beta_set.add(ANTHROPIC_BETA_HEADER_VALUES.DANGEROUS_TOOL_USE_2026_09_03.value)+ beta_set.add(dangerous_tool_use_beta)+ elif dangerous_tool_use_beta in beta_set and self.drops_dangerous_tool_use_beta_without_safeguards():+ beta_set.discard(dangerous_tool_use_beta)+ verbose_logger.debug(+ "Bedrock Invoke: dropping %s from client headers because the request has no safeguards. Bedrock "+ "answers it with 'invalid beta flag' next to structured outputs before Opus 4.7, and on Sonnet 4.5, "+ "Opus 4.5, and Opus 4.6 even alone.",+ dangerous_tool_use_beta,+ )self._filter_context_management_for_bedrock_invoke(anthropic_messages_request=anthropic_messages_request,diff --git a/litellm/llms/bedrock/messages/mantle_transformation.py b/litellm/llms/bedrock/messages/mantle_transformation.pyindex ca93cc3e617..1ad84761bc9 100644--- a/litellm/llms/bedrock/messages/mantle_transformation.py+++ b/litellm/llms/bedrock/messages/mantle_transformation.py@@ -67,6 +67,9 @@ class AmazonMantleMessagesConfig(AmazonAnthropicClaudeMessagesConfig):def should_filter_anthropic_beta_headers(self) -> bool:return False+ def drops_dangerous_tool_use_beta_without_safeguards(self) -> bool:+ return False+def get_complete_url(self,api_base: str | None,diff --git a/tests/integration/providers/test_bedrock_invoke_dangerous_tool_use_beta_wire.py b/tests/integration/providers/test_bedrock_invoke_dangerous_tool_use_beta_wire.pynew file mode 100644index 00000000000..ca22ab4f23d--- /dev/null+++ b/tests/integration/providers/test_bedrock_invoke_dangerous_tool_use_beta_wire.py@@ -0,0 +1,138 @@+import json+from collections.abc import Callable, Mapping+from typing import Final+from urllib.parse import unquote++import pytest+from integration._support.client import Gateway+from integration._support.wire import Reply, Request, Wire, wire_server+from pydantic import JsonValue, TypeAdapter++CLAUDE_ID: Final = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"+MANTLE_CLAUDE_ID: Final = "anthropic.claude-haiku-4-5"+TOKEN: Final = "synthetic-bedrock-bearer"+DANGEROUS_TOOL_USE_BETA: Final = "dangerous-tool-use-2026-09-03"+KEPT_BETA: Final = "context-1m-2025-08-07"+SAFEGUARDS: Final[JsonValue] = [{"type": "dangerous_tool_use"}]+NO_CACHE: Final[JsonValue] = {"no-cache": True}+INVOKE_TARGET: Final = f"/model/{CLAUDE_ID}/invoke"+MANTLE_TARGET: Final = "/anthropic/v1/messages"+REPLY: Final = json.dumps(+ {+ "id": "msg_scripted",+ "type": "message",+ "role": "assistant",+ "model": CLAUDE_ID,+ "content": [{"type": "text", "text": "scripted reply"}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {"input_tokens": 3, "output_tokens": 2},+ }+).encode()+_OBJECT: Final = TypeAdapter(dict[str, JsonValue])+_BETAS: Final = TypeAdapter(tuple[str, ...])+++def _peer(request: Request) -> Reply:+ if unquote(request.target) not in (INVOKE_TARGET, MANTLE_TARGET):+ return Reply(status=404, body=json.dumps({"error": f"unscripted target {request.target}"}).encode())+ assert request.headers["authorization"] == f"Bearer {TOKEN}", request.headers+ return Reply(body=REPLY)+++def _invoke_body_betas(request: Request) -> frozenset[str]:+ return frozenset(_BETAS.validate_python(_OBJECT.validate_json(request.body).get("anthropic_beta") or ()))+++def _mantle_header_betas(request: Request) -> frozenset[str]:+ return frozenset(beta.strip() for beta in request.headers.get("anthropic-beta", "").split(",") if beta.strip())+++def _delivered(gateway: Gateway, wire: Wire, path: str, body: Mapping[str, JsonValue], client_betas: str) -> Request:+ response: Final = gateway.request("POST", path, body, headers={"anthropic-beta": client_betas})+ assert response.status_code == 200, response.text+ (sent,) = wire.drain()+ return sent+++def _messages_body(model: str, **extra: JsonValue) -> dict[str, JsonValue]:+ return {+ "model": model,+ "max_tokens": 16,+ "messages": [{"role": "user", "content": "hi"}],+ "cache": NO_CACHE,+ **extra,+ }+++def _chat_body(model: str, **extra: JsonValue) -> dict[str, JsonValue]:+ return {"model": model, "messages": [{"role": "user", "content": "hi"}], "cache": NO_CACHE, **extra}+++def _responses_body(model: str, **extra: JsonValue) -> dict[str, JsonValue]:+ return {"model": model, "input": "hi", "cache": NO_CACHE, **extra}+++def test_invoke_messages_without_safeguards_sends_the_betas_of_a_request_that_never_had_the_beta(+ gateway: Gateway,+) -> None:+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"bedrock/{CLAUDE_ID}", api_key=TOKEN, aws_region_name="us-east-1", api_base=wire.url+ )+ with_beta: Final = _invoke_body_betas(+ _delivered(gateway, wire, "/v1/messages", _messages_body(model), f"{KEPT_BETA},{DANGEROUS_TOOL_USE_BETA}")+ )+ without_beta: Final = _invoke_body_betas(+ _delivered(gateway, wire, "/v1/messages", _messages_body(model), KEPT_BETA)+ )+ assert KEPT_BETA in without_beta, without_beta+ assert with_beta == without_beta, (with_beta, without_beta)+++def test_invoke_messages_with_safeguards_keeps_the_dangerous_beta(gateway: Gateway) -> None:+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"bedrock/{CLAUDE_ID}", api_key=TOKEN, aws_region_name="us-east-1", api_base=wire.url+ )+ sent: Final = _invoke_body_betas(+ _delivered(+ gateway,+ wire,+ "/v1/messages",+ _messages_body(model, safeguards=SAFEGUARDS),+ f"{KEPT_BETA},{DANGEROUS_TOOL_USE_BETA}",+ )+ )+ assert {KEPT_BETA, DANGEROUS_TOOL_USE_BETA} <= sent, sent+++ ("path", "build"),+ [("/v1/chat/completions", _chat_body), ("/v1/responses", _responses_body)],+ ids=["chat_completions", "responses"],+)+def test_invoke_chat_shaped_routes_without_safeguards_drop_only_the_dangerous_beta(+ gateway: Gateway, path: str, build: Callable[[str], dict[str, JsonValue]]+) -> None:+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"bedrock/invoke/{CLAUDE_ID}", api_key=TOKEN, aws_region_name="us-east-1", api_base=wire.url+ )+ with_beta: Final = _invoke_body_betas(+ _delivered(gateway, wire, path, build(model), f"{KEPT_BETA},{DANGEROUS_TOOL_USE_BETA}")+ )+ without_beta: Final = _invoke_body_betas(_delivered(gateway, wire, path, build(model), KEPT_BETA))+ assert KEPT_BETA in without_beta, without_beta+ assert with_beta == without_beta, (with_beta, without_beta)+++def test_mantle_messages_without_safeguards_keeps_the_dangerous_beta(gateway: Gateway) -> None:+ with wire_server(_peer) as wire, gateway.scenario() as scenario:+ model: Final = scenario.model(+ model=f"bedrock_mantle/{MANTLE_CLAUDE_ID}", api_key=TOKEN, aws_region_name="us-east-1", api_base=wire.url+ )+ sent: Final = _mantle_header_betas(+ _delivered(gateway, wire, "/v1/messages", _messages_body(model), f"{KEPT_BETA},{DANGEROUS_TOOL_USE_BETA}")+ )+ assert DANGEROUS_TOOL_USE_BETA in sent, sentdiff --git a/tests/unit/llms/bedrock/chat/invoke_transformations/test_bedrock_chat_invoke_transformations_anthropic_claude3_transformation.py b/tests/unit/llms/bedrock/chat/invoke_transformations/test_bedrock_chat_invoke_transformations_anthropic_claude3_transformation.pyindex 72857246d85..16f44f4f35f 100644--- a/tests/unit/llms/bedrock/chat/invoke_transformations/test_bedrock_chat_invoke_transformations_anthropic_claude3_transformation.py+++ b/tests/unit/llms/bedrock/chat/invoke_transformations/test_bedrock_chat_invoke_transformations_anthropic_claude3_transformation.py@@ -1087,6 +1087,35 @@ def test_bedrock_chat_invoke_eager_input_streaming_beta_not_duplicated_with_clieassert result["anthropic_beta"] == [FINE_GRAINED_TOOL_STREAMING_BETA]+DANGEROUS_TOOL_USE_BETA: Final = "dangerous-tool-use-2026-09-03"+++def _chat_invoke_betas(extra_optional_params: dict[str, object]) -> object:+ config: Final = AmazonAnthropicClaudeConfig()+ model: Final = "us.anthropic.claude-sonnet-4-5-20250929-v1:0"+ optional_params: Final = config.map_openai_params(+ non_default_params={"max_tokens": 64}, optional_params={}, model=model, drop_params=False+ )+ return config.transform_request(+ model=model,+ messages=[{"role": "user", "content": "hi"}],+ optional_params={**optional_params, **extra_optional_params},+ litellm_params={},+ headers={"anthropic-beta": f"claude-code-20250219,{DANGEROUS_TOOL_USE_BETA}"},+ ).get("anthropic_beta")+++def test_bedrock_chat_invoke_drops_client_dangerous_tool_use_beta_without_safeguards() -> None:+ assert _chat_invoke_betas({}) == ["claude-code-20250219"]+++def test_bedrock_chat_invoke_keeps_client_dangerous_tool_use_beta_with_safeguards() -> None:+ assert _chat_invoke_betas({"safeguards": [{"type": "dangerous_tool_use"}]}) == [+ "claude-code-20250219",+ DANGEROUS_TOOL_USE_BETA,+ ]++def _mid_conversation_system_conversation() -> list[dict]:return [{diff --git a/tests/unit/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py b/tests/unit/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.pyindex dffe2c36e20..c91eb75dbd9 100644--- a/tests/unit/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py+++ b/tests/unit/llms/bedrock/messages/invoke_transformations/test_anthropic_claude3_transformation.py@@ -1677,6 +1677,60 @@ def test_bedrock_messages_does_not_add_dangerous_tool_use_beta_without_safeguardassert "dangerous-tool-use-2026-09-03" not in result.get("anthropic_beta", [])+_NAME_SCHEMA: Final = {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}+++ "request_params",+ [+ {},+ {"output_config": {"format": {"type": "json_schema", "schema": _NAME_SCHEMA}}},+ {"tools": [{"name": "get_name", "strict": True, "input_schema": _NAME_SCHEMA}]},+ ],+ ids=["plain", "output_config_format", "strict_tool"],+)+def test_bedrock_messages_drops_client_dangerous_tool_use_beta_without_safeguards(+ local_model_cost_map: None, local_beta_headers_config: None, request_params: dict[str, object]+) -> None:+ from litellm.types.router import GenericLiteLLMParams++ result: Final = AmazonAnthropicClaudeMessagesConfig().transform_anthropic_messages_request(+ model="us.anthropic.claude-haiku-4-5-20251001-v1:0",+ messages=[{"role": "user", "content": [{"type": "text", "text": "Name a color."}]}],+ anthropic_messages_optional_request_params={"max_tokens": 64, **request_params},+ litellm_params=GenericLiteLLMParams(),+ headers={"anthropic-beta": "dangerous-tool-use-2026-09-03"},+ )++ assert all(result.get(key) == value for key, value in request_params.items())+ assert "dangerous-tool-use-2026-09-03" not in result.get("anthropic_beta", [])+++def test_bedrock_messages_keeps_client_dangerous_tool_use_beta_with_safeguards_and_structured_outputs(+ local_model_cost_map: None, local_beta_headers_config: None+) -> None:+ from litellm.types.router import GenericLiteLLMParams++ safeguards: Final = [{"type": "dangerous_tool_use", "classifier_context": {"v": 1, "permission_mode": "auto"}}]+ strict_tool: Final = {"name": "get_name", "strict": True, "input_schema": _NAME_SCHEMA}++ result: Final = AmazonAnthropicClaudeMessagesConfig().transform_anthropic_messages_request(+ model="us.anthropic.claude-sonnet-5",+ messages=[{"role": "user", "content": [{"type": "text", "text": "Name a color."}]}],+ anthropic_messages_optional_request_params={+ "max_tokens": 64,+ "safeguards": safeguards,+ "tools": [strict_tool],+ },+ litellm_params=GenericLiteLLMParams(),+ headers={"anthropic-beta": "dangerous-tool-use-2026-09-03"},+ )++ assert result["safeguards"] == safeguards+ assert result["tools"] == [strict_tool]+ assert result["anthropic_beta"].count("dangerous-tool-use-2026-09-03") == 1++def test_bedrock_messages_stream_decoder_keeps_safeguard_results():"""Bedrock streams the classifier verdicts on message_start and on the final message_delta, exactly as api.anthropic.com does."""decoder = AmazonAnthropicClaudeMessagesStreamDecoder(model="us.anthropic.claude-sonnet-5")diff --git a/tests/unit/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.py b/tests/unit/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.pyindex 923572c4f46..3236efbbfba 100644--- a/tests/unit/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.py+++ b/tests/unit/llms/bedrock_mantle/test_bedrock_mantle_messages_transformation.py@@ -10,6 +10,7 @@ Bearer/SigV4 auth chain, and the wire request through the public entrypoint."""import json+from typing import Finalfrom unittest.mock import MagicMockimport httpx@@ -453,6 +454,14 @@ class TestBetaHeadersOnTheWire:assert _sent_betas(route) == ["dangerous-tool-use-2026-09-03"]assert _sent_body(route)["safeguards"] == safeguards+ @pytest.mark.asyncio+ @respx.mock+ async def test_client_dangerous_tool_use_beta_reaches_mantle_without_safeguards(self) -> None:+ route: Final = await self._send(extra_headers={"anthropic-beta": "dangerous-tool-use-2026-09-03"})++ assert _sent_betas(route) == ["dangerous-tool-use-2026-09-03"]+ assert "safeguards" not in _sent_body(route)+@pytest.mark.asyncio@respx.mockasync def test_betas_and_version_never_travel_in_the_body(self):