Skip to content

fix(guardrails): keep client tools verbatim when an Anthropic Messages guardrail returns them unchanged - #50637

Closed
zhaojiangang-it wants to merge 1 commit into
BerriAI:mainfrom
zhaojiangang-it:litellm_50055_guardrail_websearch_writeback
Closed

zhaojiangang-it wants to merge 1 commit into
BerriAI:mainfrom
zhaojiangang-it:litellm_50055_guardrail_websearch_writeback

Conversation

@zhaojiangang-it

@zhaojiangang-it zhaojiangang-it commented Nov 8, 2026 •

Copy link
Copy Markdown

Handwritten 1-3 sentence description

A guardrail that never touched the tools still made LiteLLM rebuild the tool list on /v1/messages, and the rebuild silently dropped web_search server tools and renamed nameless ones like mcp_toolset to litellm_unnamed_tool_0. This PR snapshots the tools right before the guardrail call and skips the rebuild when the guardrail returns them unchanged, so the provider receives exactly what the client sent. Guardrails that do change tools keep the existing rebuild path.

Details

TLDR

Problem this solves:

  • A guardrail that never touches tools still rebuilt the request's tool list on /v1/messages
  • The rebuild silently dropped web_search server tools
  • It renamed nameless tools like mcp_toolset to litellm_unnamed_tool_0

How it solves it:

  • Snapshot the tools the guardrail receives, right before the call
  • Skip the rebuild when the guardrail hands back tools equal to the snapshot
  • Changed tools still go through the rebuild exactly as before

User Flow

Before: a Claude Code user behind a proxy with a pre_call guardrail loses server tools on every request

  1. They send POST https://litellm-domain/v1/messages with tools including web_search and a nameless mcp_toolset
  2. The guardrail allows the request without changing anything
  3. The provider receives a request where web_search is gone and mcp_toolset became a tool named litellm_unnamed_tool_0
  4. The model cannot search the web, and it can call a tool the client never defined

After: the same request reaches the provider exactly as the client sent it

  1. They send the same POST https://litellm-domain/v1/messages with the same tools
  2. The guardrail allows the request without changing anything
  3. The provider receives all four tools as sent, web_search and mcp_toolset included, with the long tool name and its defer_loading flag intact
  4. The model can search the web, and it only sees tools the client defined

Relevant issues

Fixes #50055

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/unit/<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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

The defect is in the request body LiteLLM sends to the provider, so the proof follows the issue's own repro and points the deployment at a logging upstream that records the body verbatim. A real provider call cannot show more than the body it receives, because the rebuilt request stays valid and the loss is silent. Ran single worker with no Redis since the change is an in-process request transformation with no cross-worker state.

Shared setup, identical for both cases:

  1. Check out the SHA named in the case heading
  2. Save the logging upstream from the collapsed block below as fake_anthropic.py, then start it with python3 fake_anthropic.py received.jsonl 18998
  3. Save the config below as config.yaml, then start the proxy with uv run python litellm/proxy/proxy_cli.py --config config.yaml --port 4100 --detailed_debug > proxy.log 2>&1 &
  4. Send the request below with curl -s http://127.0.0.1:4100/v1/messages -H "Authorization: Bearer sk-test" -H "Content-Type: application/json" -H "anthropic-version: 2023-06-01" -d @request.json
  5. Read what the provider received with python3 -c "import json; [print(json.dumps(json.loads(line)['body'].get('tools'), indent=1)) for line in open('received.jsonl') if json.loads(line)['path'].endswith('/v1/messages')]"
  6. Confirm the guardrail ran with grep "Allowing request" proxy.log
fake_anthropic.py, the logging upstream from the issue's repro
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer

LOG_PATH = sys.argv[1]
PORT = int(sys.argv[2])

RESPONSE = {
    "id": "msg_fake01",
    "type": "message",
    "role": "assistant",
    "content": [{"type": "text", "text": "ok"}],
    "model": "claude-haiku-4-5",
    "stop_reason": "end_turn",
    "stop_sequence": None,
    "usage": {"input_tokens": 10, "output_tokens": 1},
}


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("content-length", 0)))
        with open(LOG_PATH, "a") as log:
            log.write(json.dumps({"path": self.path, "body": json.loads(body)}, ensure_ascii=False) + "\n")
        payload = json.dumps(RESPONSE).encode()
        self.send_response(200)
        self.send_header("content-type", "application/json")
        self.send_header("content-length", str(len(payload)))
        self.end_headers()
        self.wfile.write(payload)

    def log_message(self, *args):
        pass


HTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
config.yaml and request.json
model_list:
  - model_name: claude
    litellm_params:
      model: anthropic/claude-haiku-4-5
      api_key: k
      api_base: http://127.0.0.1:18998

general_settings:
  master_key: sk-test

guardrails:
  - guardrail_name: passthrough
    litellm_params:
      guardrail: custom_code
      mode: pre_call
      default_on: true
      custom_code: |
        async def apply_guardrail(inputs, request_data, input_type):
            return allow()
{
  "model": "claude",
  "max_tokens": 64,
  "messages": [{ "role": "user", "content": "search the docs" }],
  "tools": [
    { "type": "web_search_20250305", "name": "web_search", "max_uses": 1 },
    { "type": "mcp_toolset", "mcp_server_name": "github" },
    { "name": "Read", "description": "d", "input_schema": { "type": "object", "properties": {} } },
    {
      "name": "mcp__atlassian__create_confluence_footer_comment_with_a_very_long_name_x",
      "description": "d",
      "defer_loading": true,
      "input_schema": { "type": "object", "properties": {} }
    }
  ]
}

Before (e58354f)

  1. Steps 1 to 6 of the shared setup. The proxy log shows Custom code guardrail 'passthrough': Allowing request, so the guardrail ran
  2. The logging upstream received 3 tools instead of 4, web_search is gone, mcp_toolset is now a custom tool named litellm_unnamed_tool_0 that lost its mcp_server_name, and defer_loading disappeared from the long-named tool
[{"name": "litellm_unnamed_tool_0", "input_schema": {"type": "object", "properties": {}}, "type": "custom"},
 {"name": "Read", "input_schema": {"type": "object", "properties": {}}, "type": "custom", "description": "d"},
 {"name": "mcp__atlassian__create_confluence_footer_comment_with_a_very_long_name_x", "input_schema": {"type": "object", "properties": {}}, "type": "custom", "description": "d"}]

After (911bfdb)

  1. Same steps, same guardrail log line confirming it ran
  2. The logging upstream received all 4 tools byte-identical to the request, including web_search_20250305, mcp_toolset with its mcp_server_name, and the long name with defer_loading at the top level
[{"type": "web_search_20250305", "name": "web_search", "max_uses": 1},
 {"type": "mcp_toolset", "mcp_server_name": "github"},
 {"name": "Read", "description": "d", "input_schema": {"type": "object", "properties": {}}},
 {"name": "mcp__atlassian__create_confluence_footer_comment_with_a_very_long_name_x", "description": "d", "defer_loading": true, "input_schema": {"type": "object", "properties": {}}}]

Unit tests, uv run pytest tests/unit/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py -q, 134 passed at the tip. The regression test test_unmodified_guardrail_tools_keep_client_tools_verbatim fails at the merge base with the 3-tool rebuild shown above, and passes at the tip.

Type

🐛 Bug Fix

Caveats (if any)

Medium

Low

  • The snapshot deep-copies the translated tools list once per guarded request, which is negligible next to the guardrail call itself

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

…s guardrail returns them unchanged

The Anthropic guardrail translation rebuilt data["tools"] from the guardrail's
return value even when nothing changed. The rebuild drops web_search server
tools, which the translation moved to web_search_options, and renames nameless
tools like mcp_toolset to litellm_unnamed_tool_0. Snapshot the translated tools
before the guardrail call and skip the rebuild when the returned tools match
the snapshot, so unchanged tools reach the provider exactly as the client sent
them.

Fixes BerriAI#50055
@github-actions

Copy link
Copy Markdown
Contributor

#50055 was fixed by #53290 on main, so this pull request is closed. Reopen it if something was missed.

@github-actions github-actions Bot closed this Nov 24, 2026
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.

[Bug]: /v1/messages guardrail tool write-back drops web_search server tools and turns mcp_toolset into litellm_unnamed_tool_0

1 participant