Skip to content

fix(guardrails): keep client tools untouched when a guardrail does not rewrite them - #40077

Closed
duhd-vnpay wants to merge 1 commit into
BerriAI:mainfrom
duhd-vnpay:litellm_guardrail_tools_writeback
Closed

duhd-vnpay wants to merge 1 commit into
BerriAI:mainfrom
duhd-vnpay:litellm_guardrail_tools_writeback

Conversation

@duhd-vnpay

@duhd-vnpay duhd-vnpay commented Sep 7, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • Guarded /v1/messages requests get their tools rewritten
  • Rewrite adds type:"custom", strict Anthropic-compatible upstreams 400
  • Happens even when the guardrail masked nothing

How it solves it:

  • Rewrite tools only when the guardrail returns a different list
  • Same contract the function already uses for structured_messages
  • Genuine tool rewrites and tool injections keep working

User Flow

Before: a developer using an Anthropic-compatible model behind a guardrailed key cannot use tools at all, and the error text points at a tool type they never sent

  1. Their key has a content-scanning guardrail on in pre_call mode
  2. They send POST https://litellm-domain/v1/messages with a model served by an Anthropic-compatible provider, and one tool shaped {"name": "Bash", "description": "Run a shell command", "input_schema": {...}}
  3. They get back HTTP 400 reading Failed to deserialize the JSON body into the target type: tools[0]: unknown variant 'custom', expected 'web_search_20250305' or 'web_search_20260209', naming a custom variant that was never in their request
  4. Every retry fails the same way, and any configured fallback that lands on the same provider fails identically
  5. They send the exact same request with no tools at all and it returns 200, so the tools array is the only difference
  6. They turn the guardrail off for that key and the original tool-bearing request returns 200

After: the same request works with the guardrail left on

  1. Their key has a content-scanning guardrail on in pre_call mode
  2. They send the same POST https://litellm-domain/v1/messages with the same tool
  3. They get back HTTP 200 with a normal message, and a tool_use block when the model decides to call Bash
  4. The guardrail still scans and still masks: a secret placed in the prompt or in a tool description comes back redacted

Relevant issues

Related to #24913, which is the mirror-image leak in the other direction (translate_anthropic_tools_to_openai copying the tool-level type into function.parameters). That one is fixed, this is the write-back side of the same round-trip and is not covered by it

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Shared setup, both runs use the same config and the same payload

config.yaml, pointed at an Anthropic-compatible upstream that rejects the explicit tool discriminator, with a content-scanning guardrail on for every request:

model_list:
  - model_name: compat-model
    litellm_params:
      model: anthropic/deepseek-chat
      api_base: https://api.deepseek.com/anthropic
      api_key: os.environ/DEEPSEEK_API_KEY

guardrails:
  - guardrail_name: content-scan
    litellm_params:
      guardrail: litellm_content_filter
      mode: pre_call
      default_on: true

Proxy started with python litellm/proxy/proxy_cli.py --config config.yaml --detailed_debug

Payload, a client tool in the shape Anthropic clients actually send, with no type key:

curl -sS -o /dev/stderr -w '\nHTTP %{http_code}\n' http://localhost:4000/v1/messages \
  -H 'Authorization: Bearer sk-1234' \
  -H 'anthropic-version: 2023-06-01' \
  -H 'content-type: application/json' \
  -d '{"model":"compat-model","max_tokens":128,
       "messages":[{"role":"user","content":[{"type":"text","text":"Use your Bash tool to list /tmp, then stop."}]}],
       "tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}]}'

Before (168a005)

  1. Run the curl above. The upstream rejects a tool type the client never sent
HTTP 400
{"type":"error","error":{"type":"invalid_request_error","message":"litellm.BadRequestError: AnthropicException - {\"error\":{\"message\":\"Failed to deserialize the JSON body into the target type: tools[0]: unknown variant `custom`, expected `web_search_20250305` or `web_search_20260209` at line 1 column 372\",\"type\":\"invalid_request_error\",\"param\":null,\"code\":\"invalid_request_error\"}}. Received Model Group=compat-model"}}
  1. The outbound body in the debug log carries a type the request did not have
'tools': [{'name': 'Bash', 'input_schema': {'type': 'object', 'properties': {'command': {'type': 'string'}}, 'required': ['command']}, 'type': 'custom', 'description': 'Run a shell command'}]

After (27470d7)

  1. Run the same curl. The schema rejection is gone: the request now gets past deserialization and reaches billing, where this particular test account happens to be out of credit
HTTP 402
{"type":"error","error":{"type":"api_error","message":"litellm.BadRequestError: AnthropicException - {\"error\":{\"message\":\"Insufficient Balance\",\"type\":\"unknown_error\",\"param\":null,\"code\":\"invalid_request_error\"}}. Received Model Group=compat-model"}}
  1. The outbound body now matches what the client sent, with no injected type
'tools': [{'name': 'Bash', 'description': 'Run a shell command', 'input_schema': {'type': 'object', 'properties': {'command': {'type': 'string'}}, 'required': ['command']}}]

Staying in draft until the same run lands a funded 200 with a tool_use block. The guardrail is on for both runs, so the difference is the write-back and nothing else

Type

🐛 Bug Fix

Caveats (if any)

Low

  • Guardrails must return a new list to signal a tool rewrite
  • In-place mutation of the received list is no longer picked up
  • That is already the contract for structured_messages in the same function

…t rewrite them

The Anthropic /v1/messages guardrail translation re-serialized tools back into
Anthropic shape whenever a guardrail returned a tools list, even when the
guardrail had returned the very list it was handed. _map_tool_helper always
stamps type:"custom", so a client tool sent as {name, description, input_schema}
reached the upstream as {name, description, input_schema, type:"custom"}. The
real Anthropic API accepts both forms, but strict Anthropic-compatible upstreams
reject the explicit discriminator, so a guarded request that changed nothing
came back 400 with `tools[0]: unknown variant 'custom'`.

Guardrails now have to hand back a different list object to trigger the rewrite,
which is the contract the same function already uses for structured_messages a
few lines below. Genuine tool rewrites and tool injections keep working, and the
scan_only_tool_results merge path is unaffected because the guardrail never
receives the request tools there, so anything it returns is a new object.
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@codspeed

codspeed Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing duhd-vnpay:litellm_guardrail_tools_writeback (27470d7) with litellm_internal_staging (02522a5)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (168a005) during the generation of this report, so 02522a5 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Sep 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@duhd-vnpay
duhd-vnpay marked this pull request as ready for review September 7, 2026 06:23
@duhd-vnpay
duhd-vnpay requested a review from a team September 7, 2026 06:23
@greptile-apps

greptile-apps Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR avoids reserializing Anthropic tools when a guardrail returns the original list and adds regression coverage for unchanged and rewritten tools

  • Preserves client tool shapes for identity-preserving pass-through guardrails
  • Continues converting replacement tool lists back to Anthropic format
  • Uses object identity as a change signal, which breaks copied pass-through lists and in-place mutations

Confidence Score: 4/5

The PR should not merge until tool changes are detected without breaking existing custom guardrails or retriggering serialization for equivalent copies

The identity check fixes one pass-through shape but silently drops in-place tool edits and still rewrites equivalent copied lists

Files Needing Attention: litellm/llms/anthropic/chat/guardrail_translation/handler.py

Important Files Changed

Filename Overview
litellm/llms/anthropic/chat/guardrail_translation/handler.py Adds identity-based tool rewrite detection, fixing the reported pass-through path but introducing compatibility failures for other valid custom guardrail return patterns
tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py Adds focused coverage for identity-preserving pass-through and replacement-list rewrites, but does not cover copied unchanged lists or in-place edits

Reviews (1): Last reviewed commit: "fix(guardrails): keep client tools untou..." | Re-trigger Greptile

# structured_messages below). Re-serializing an untouched list would stamp type:"custom" onto
# every tool, which strict Anthropic-compat upstreams (e.g. DeepSeek) reject with
# `tools[0]: unknown variant 'custom'`.
if guardrailed_tools is not None and guardrailed_tools is not tools_to_check:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Identity Misclassifies Tool Changes

Copied lists are reserialized and may be rejected upstream; in-place edits are dropped. This violates the requirement to gate incompatible behavior behind a user flag

Rule Used: What: avoid backwards-incompatible changes without... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

# structured_messages below). Re-serializing an untouched list would stamp type:"custom" onto
# every tool, which strict Anthropic-compat upstreams (e.g. DeepSeek) reject with
# `tools[0]: unknown variant 'custom'`.
if guardrailed_tools is not None and guardrailed_tools is not tools_to_check:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low: In-place tool sanitization is discarded

GenericGuardrailAPIInputs exposes a mutable tool list, and custom guardrails can modify its tool dictionaries in place before returning inputs. In that case guardrailed_tools is tools_to_check, so this branch skips write-back; for example, an attacker-controlled secret in an Anthropic tool description remains in data["tools"] and is sent upstream even if the guardrail replaced that description in place. Preserve a pre-guardrail snapshot and write back when either list identity or contents changed, rather than making copy-on-write an undocumented requirement.

@veria-ai

veria-ai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

PR overview

This PR updates Anthropic guardrail translation so client-provided tool definitions remain untouched when a guardrail does not rewrite them.

One security issue remains: in-place tool edits made by a custom guardrail may not be written back to the outgoing request. This could cause sensitive content in attacker-influenced tool descriptions to be sent upstream despite attempted sanitization, though exploitation depends on a guardrail that mutates existing tool objects in place.

Open issues (1)

Fixed/addressed: 0 · PR risk: 4/10

@mateo-berri

Copy link
Copy Markdown
Contributor

Closing this since main already keeps unchanged tools exactly as sent after #53290. Thanks for putting it together, and comment here if something is still missing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants