Skip to content

fix(bedrock): filter LiteLLM-internal params from invoke request bodies - #30398

Closed
kimnamu wants to merge 8 commits into
BerriAI:mainfrom
kimnamu:fix/bedrock-invoke-filter-oss
Closed

kimnamu wants to merge 8 commits into
BerriAI:mainfrom
kimnamu:fix/bedrock-invoke-filter-oss

Conversation

@kimnamu

@kimnamu kimnamu commented Jun 13, 2026

Copy link
Copy Markdown
Contributor

Thanks for LiteLLM! (Re-targeted to litellm_oss_branch per the repo's external-contributor guard — supersedes #30372.)

Summary

The Bedrock invoke transform splats leftover inference_params into the provider request body without filtering LiteLLM-internal control flags (e.g. the MCP handler keys). These are not valid Bedrock inference parameters and can make Bedrock reject the request. This is the same leak class as #30240 (stream_chunk_size), which was patched with an ad-hoc pop().

Change — fills an existing pattern

The Converse path already routes its params through the shared filter_internal_params helper (converse_transformation.py). The invoke path didn't. This applies the same helper to the invoke path's inference_params, right after the existing AWS-auth filtering:

inference_params = filter_internal_params(inference_params)

One import + one line, reusing the existing helper — no new abstraction, and it does not touch the contested core_helpers internal-key set.

Before After
optional_params={"skip_mcp_handler": True, "max_tokens": 10} (mistral invoke) body contains "skip_mcp_handler": true ❌ skip_mcp_handler removed ✅
max_tokens and real inference params forwarded ✅ forwarded (unchanged)
Converse path already filters ✅ unchanged

Tests

Added test_transform_request_drops_internal_params (mirrors the existing test_transform_request_drops_stream_chunk_size). Uses skip_mcp_handler, already in filter_internal_params's internal set — valid without widening that set. Removing the fix → 1 failed (skip_mcp_handler leaks into the body); restored → passes.


This contribution was prepared with the help of an AI agent (Claude Code); a human reviewed the change, rationale, and test results before submission.

@kimnamu
kimnamu requested a review from a team June 13, 2026 21:58
@CLAassistant

CLAassistant commented Jun 13, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@codecov

codecov Bot commented Jun 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes LiteLLM-internal control flags (MCP handler keys) leaking into Bedrock invoke request bodies by applying the existing filter_internal_params helper — already used on the Converse path — to the invoke path's inference_params, plus importing it. The change is one import and one line.

  • Production fix (base_invoke_transformation.py): filter_internal_params is called immediately after the AWS-auth-param strip, cleanly mirroring the Converse path's approach and ensuring MCP flags like skip_mcp_handler are removed before the provider body is assembled.
  • Test regression (test_base_invoke_transformation.py): The PR replaces the existing 4-case parametrized test for stream_chunk_size filtering with a single Mistral-only test for skip_mcp_handler, removing regression coverage for stream_chunk_size and three model/config combinations that were previously verified.

Confidence Score: 4/5

The production fix is safe to merge, but the test file drops meaningful existing coverage that should be restored first.

The one-line production change is correct and self-contained. The test change, however, silently removes the 4-case parametrized regression test for stream_chunk_size filtering and three model/config combinations, leaving that guard completely untested. A future refactor that drops the pop("stream_chunk_size", None) line would not be caught by any test.

The test file needs the old stream_chunk_size cases and multi-model parametrize coverage restored before merging.

Important Files Changed

Filename Overview
litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py Adds filter_internal_params call after the AWS-auth-param strip; minimal one-line fix that correctly mirrors the Converse path's existing filtering behaviour.
tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py Replaces the 4-case parametrized stream_chunk_size regression test with a single Mistral-only skip_mcp_handler test, silently removing coverage for stream_chunk_size filtering and three other model/config combinations.

Reviews (3): Last reviewed commit: "test(bedrock): scope invoke test to filt..." | Re-trigger Greptile

@kimnamu

kimnamu commented Jun 13, 2026

Copy link
Copy Markdown
Contributor Author

@greptileai review

(Re-requesting after scoping the test file down to this change — the earlier stream_chunk_size parametrized cases were an artifact of the rebase onto litellm_oss_branch and have been removed, since that behavior isn't on this branch. The PR now only adds the one-line filter_internal_params call on the invoke path plus its focused test_transform_request_drops_internal_params regression test, mirroring the existing Converse-path filtering.)

@BroderickHigby BroderickHigby left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

{"linked_issue":null,"fix_shapes":["param_filter_or_allowlist"],"merge_gate":{"safe_for_high_rps_gateway":"yes","one_liner":"Merge: this is a narrow Bedrock invoke request-body sanitation fix that reuses the existing internal-param filter and does not expand provider behavior beyond the failing class.","unintended_consequences":["Internal MCP flags will no longer reach Bedrock invoke providers that splat inference params; if a provider accidentally depended on one of those LiteLLM-only keys in the provider body, that unsupported behavior stops.","The Anthropic/Nova special branches still use their own transforms; this PR does not claim to centralize all Bedrock internal-param filtering."],"hot_path_notes":["Bedrock invoke request transformation is on a request path, but the added work is a small dict filter after the existing AWS-auth param filtering and before provider-specific serialization."],"what_would_make_yes":"Already yes; keep the patch constrained to the shared invoke inference_params path."},"findings":[]}

@kimnamu

kimnamu commented Jun 19, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the thorough review @BroderickHigby 🙏 — and for confirming the merge gate (narrow Bedrock invoke request-body sanitation, reusing the existing internal-param filter, no expansion of provider behavior). That's exactly the intent.

To your noted consequence — "internal MCP flags will no longer reach Bedrock invoke providers that splat inference params" — that's the desired effect: those are LiteLLM-internal keys that Bedrock's invoke body should never have received, and the Converse path already filters them. This PR just brings the invoke path to parity. The Anthropic/Nova special branches keep their own transforms untouched, as you noted.

The patch stays constrained to the shared invoke inference_params path. Happy to address anything else needed for merge.

@Sameerlite

Copy link
Copy Markdown
Contributor

@kimnamu Please rebase this to litellm_internal_staging

kimnamu added 2 commits June 24, 2026 06:56
Remove the stream_chunk_size parametrized test that came along during the
cherry-pick — that behavior (BerriAI#30240) isn't present on litellm_oss_branch, so
the test fails here and is out of scope for this PR. Keep only the
skip_mcp_handler regression test for this change.
@kimnamu
kimnamu changed the base branch from litellm_oss_branch to litellm_internal_staging June 23, 2026 21:56
@kimnamu
kimnamu force-pushed the fix/bedrock-invoke-filter-oss branch from 9f8ca48 to 113b971 Compare June 23, 2026 21:56
@kimnamu

kimnamu commented Jun 23, 2026

Copy link
Copy Markdown
Contributor Author

Done, @Sameerlite — rebased onto litellm_internal_staging and retargeted the PR there. The diff is clean (just the base_invoke_transformation.py filter + its test), cherry-picked cleanly onto the latest staging with no unrelated commits mixed in. It merges cleanly.

The change is unchanged in intent: the invoke path now calls filter_internal_params like the Converse path already does, so LiteLLM-internal control flags (e.g. skip_mcp_handler) no longer leak into the Bedrock request body. Ready for review whenever you'd like. Thanks!

@Sameerlite

Copy link
Copy Markdown
Contributor

Thanks for the contribution! A couple of things:

  • The Block fork dependency changes, lint, and osv-scan CI checks are failing, and several test suites were cancelled as a result — please take a look.
  • Could you add some evidence the filtering works? Test output or before/after logs showing the LiteLLM-internal params are stripped from the Bedrock invoke body would help.
  • Triggering a fresh Greptile review on the latest commit.

@greptileai

@Sameerlite

Copy link
Copy Markdown
Contributor

Great work on this fix, @kimnamu! The production change is clean and the before/after table makes the behavior crystal clear. A couple of items still need attention:\n\n1. Greptile score 4/5: Greptile flagged that the test file removes the existing 4-case parametrized regression suite for filtering and replaces it with a single Mistral-only test for . Restoring the cases and multi-model coverage alongside the new test should bring this to 5/5.\n2. CI failures: The , , and checks are failing. The fork checks are typical for external contributor PRs; the failure needs investigation to ensure there are no linting issues introduced by the change.\n\nOnce those are addressed, this should be in great shape!

kimnamu commented Jun 30, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Sameerlite — addressed in 6803a6ae0e.

What changed:

  • Restored the existing 4-case parametrized stream_chunk_size regression coverage (AmazonInvokeConfig for Anthropic/Titan/Mistral plus AmazonAnthropicClaudeConfig).
  • Kept the new focused skip_mcp_handler regression test for this PR's filter_internal_params invoke-path fix.
  • No production-code change beyond the original one-line invoke filtering fix.

Validation I ran on the updated branch:

$ uv run pytest tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py -q
.....                                                                    [100%]
5 passed in 0.12s

$ uv run black --check litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py
2 files would be left unchanged.

$ uv run ruff check litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py
All checks passed!

And a direct transform check for the new behavior:

optional_params={"skip_mcp_handler": True, "max_tokens": 10}
=> {"max_tokens": 10, "prompt": "<s>[INST] hi [/INST]\n"}

So the LiteLLM-internal flag is stripped from the Bedrock invoke body, while the existing stream_chunk_size coverage is back in place.

kimnamu added 2 commits June 30, 2026 14:25
… fix/bedrock-invoke-filter-oss

# Conflicts:
#	tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py
@codspeed

codspeed Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing kimnamu:fix/bedrock-invoke-filter-oss (6310499) with main (254c2f6)

Open in CodSpeed

@kimnamu

kimnamu commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged litellm_internal_staging in to clear the conflict (c1281c8). Every conflicting hunk was formatting-only — this branch was Black-formatted and staging has since moved to ruff format — so I took staging's base_invoke_transformation.py as-is and re-applied just the import and the filter_internal_params(...) call. That also removes the lint failure (Would reformat: base_invoke_transformation.py). Diff vs base is now +6/−1 in the source file and the one added test.

On the merged tree (ruff 0.15.3): ruff format --check and ruff check clean, ruff_strict_gate / type_discipline_gate / test_quality_gate all OK vs litellm_internal_staging, from litellm import * OK. pytest tests/test_litellm/llms/bedrock/chat/invoke_transformations/test_base_invoke_transformation.py → 18 passed; dropping the filter_internal_params line makes the new test fail again with "skip_mcp_handler": true in the Mistral body.

@yuneng-berri
yuneng-berri deleted the branch BerriAI:main September 13, 2026 04:24
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main September 23, 2026 16:04
…lter-oss

main moved test_base_invoke_transformation.py to tests/unit, so the regression test moves with it
…lter-oss

main added a stored_control_options import next to the core_helpers import (BerriAI#43222), keep both
fangkangmi pushed a commit to fangkangmi/litellm that referenced this pull request Oct 12, 2026
Carried over from BerriAI#30398 by kimnamu and applied to current main, where
the test file now lives under tests/unit

Fixes BerriAI#30371
fangkangmi added a commit to fangkangmi/litellm that referenced this pull request Oct 12, 2026
… one pass

The invoke filter now reads MCP_HANDLER_KWARG_NAMES from the registry
inside the existing comprehension, so it adds no rebind and no import of
the untyped helper. Behavior and the regression test from BerriAI#30398 are
unchanged
mateo-berri added a commit that referenced this pull request Nov 17, 2026
)

* fix(embeddings): keep prompt-management params out of embedding provider requests

A deployment whose litellm_params carry cache_control_injection_points,
knowledge_bases or vector_store_ids fails every embedding call against a
strict provider, because embedding() forwarded those keys as provider
params. Bedrock Titan rejects them with "extraneous key ... is not
permitted" (#30314). Embeddings never run prompt-management hooks, so
nothing consumes these params there. They are now excluded where
embedding() builds provider params, and an explicit extra_body is still
passed through

Refs #30301

Co-authored-by: tsushanth <78000697+tsushanth@users.noreply.github.com>

* fix(mcp): own the MCP handler keys and read fake_stream as a control

completion() and embedding() already keep owned kwargs out of provider
params, but skip_mcp_handler, mcp_handler_context and fake_stream were
in no registry, so a caller that passed them sent them to the provider.
Some OpenAI-compatible providers crashed with a TypeError before
sending, others forwarded the field and failed on strict APIs

The MCP keys now live in McpHandlerState. filter_internal_params builds
its set from the same declaration instead of a separate hand-written
list, and stays MCP-only because fallback callers pass the remaining
kwargs back into acompletion

fake_stream is a ControlOptions field next to stream_chunk_size. A value
from a caller or a deployment is validated, carried in litellm_params and
read by the HTTP and Converse handlers alongside the flag provider configs
set internally, so it turns on fake streaming and never reaches the
provider body

Refs #30301 #30371

Co-authored-by: Chenglun Hu <chenglunhu@gmail.com>

* test(providers): walk every chat and embedding route with internal params seeded

The wire test covered six providers. This walks every chat and embedding
route that can reach a local wire server, including each Bedrock route,
Invoke family and Bedrock embedding family. Each call carries every
LiteLLM-owned name a plain call can take, and the test fails if one of
them, a prompt-management param on embeddings, any other owned name at
the top level, or any top-level underscore key reaches the request body

The seeds follow the registry. Every owned name is seeded or listed with
the reason it can't be, so a new field fails until someone decides

A provider without a route must either have a stated reason it can't
reach the wire and send nothing to it, or raise LiteLLMUnknownProvider
without sending. A provider that gains a handler fails until it is walked

Routes the walk shows sending or rejecting max_retries are pytest.skip
with a BUG reason, per tests/integration/AGENTS.md

Closes #30301

* fix(bedrock): filter LiteLLM-internal params from invoke request bodies

Carried over from #30398 by kimnamu and applied to current main, where
the test file now lives under tests/unit

Fixes #30371

* refactor(bedrock): check invoke params against the owned MCP names in one pass

The invoke filter now reads MCP_HANDLER_KWARG_NAMES from the registry
inside the existing comprehension, so it adds no rebind and no import of
the untyped helper. Behavior and the regression test from #30398 are
unchanged

* test(providers): walk the providers and owned names that landed on main

Main added the opencode_go, coralbricks, openinfer, databricks_agent and inferenceapis chat providers and the
aws_bedrock_control_plane_endpoint, kubernetes_pod_discovery and _encrypted_content_affinity_pinned owned
names, so the wire walk now covers them too

* test(providers): walk the providers and owned names that landed on main

Main added the bigmodel, aiand, abliteration, empiriolabs, kyma, refuseless, hostinger_router, clf_ai_gateway,
zerogpu, streamlake and wally chat providers, the empiriolabs and hostinger_router embedding routes, and the rpd,
tpd, daily_reset_time, switchyard_router_config and thought_signature_in_tool_call_id owned names. chatgpt now
sends with a plain api_key, so the walk covers it as a chat route instead of keeping it off the wire

* style(tests): match main's formatting in the Bedrock Converse handler tests

The file now differs from main only by the caller fake_stream test and its imports

* fix(main): bound a caller or deployment fake_stream by the request timeout

completion() picks the faked-stream timeout by asking _completion_fakes_stream, which only looked at
optional_params. A caller's or deployment's fake_stream lives in the stored control options instead, so a
faked stream was bounded by the short stream_timeout alone and a slow non-streamed answer timed out. The
check now also reads control_options.fake_stream, which covers the first attempt and the Bedrock native
output retry

* fix: drop only the invalid control option under drop_params

A bad stream_chunk_size under drop_params reset every control option, so a
valid fake_stream was lost and the stream went upstream for real. Keep each
option that validates on its own instead.

Also annotate the new Bedrock locals and tests with Final and return types.

* fix: replay fake_stream as a stream on every chat route

completion() now makes one plain provider call when a caller or deployment
sets fake_stream and replays the answer as a stream, so OpenAI, Anthropic and
every other chat handler honor it instead of streaming live with the faked
stream timeout. The replayed chunks keep the answer's own model name

fake_stream accepts only true or false, as a bool or a string, so values like
"yes", 1 or 1.0 get the invalid control option 400 instead of turning it on

filter_internal_params takes a typed Mapping and the Converse handler reads
stream as a bool

* fix: keep token logprobs on a replayed fake stream

The replayed chunk now carries each choice's logprobs from the plain answer,
so a fake_stream request with logprobs gets the same token probabilities a
live stream returned

* fix: keep provider headers, service tier and fingerprint on a replayed fake stream

The replayed stream now carries the plain answer's provider response headers, so
the proxy still returns llm_provider-* and x-ratelimit-* headers with fake_stream

Replayed chunks keep the answer's service_tier and system_fingerprint

Image generation and image edit drop deployment prompt-management params like
cache_control_injection_points, which Bedrock rejected as an invalid field

* fix: replay a text completion answer when fake_stream is set

text_completion, atext_completion and the Codestral completion route returned a raw TextCompletionResponse from the plain call, so the replay crashed with "'coroutine' object is not iterable" or an async-for error after the provider answered. The replay now turns that answer into a chat answer first and streams it like the other routes

* fix: keep every answer when a text completion stream holds several choices

A text completion stream converted only the first choice of each chunk, so a
fake_stream replay with n=2 lost the second answer. Each chunk now converts
every choice it carries

---------

Co-authored-by: tsushanth <78000697+tsushanth@users.noreply.github.com>
Co-authored-by: Chenglun Hu <chenglunhu@gmail.com>
Co-authored-by: kimnamu <jihoon.lucas.kim@gmail.com>
Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
@mateo-berri

Copy link
Copy Markdown
Contributor

Closing since #46083 merged and keeps these internal params out of provider requests. Thanks for the fix here

mateo-berri pushed a commit to norkelbyte/litellm that referenced this pull request Nov 17, 2026
Carried over from BerriAI#30398 by kimnamu and applied to current main, where
the test file now lives under tests/unit

Fixes BerriAI#30371

(cherry picked from commit abb00c1)
mateo-berri pushed a commit to norkelbyte/litellm that referenced this pull request Nov 17, 2026
… one pass

The invoke filter now reads MCP_HANDLER_KWARG_NAMES from the registry
inside the existing comprehension, so it adds no rebind and no import of
the untyped helper. Behavior and the regression test from BerriAI#30398 are
unchanged

(cherry picked from commit dd6aa60)
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.

6 participants