Skip to content

fix(mcp)!: backport large SSE results and main cost map to 1.106 - #47241

Draft
joshua-berri wants to merge 30 commits into
stable/1.106.xfrom
litellm_backport_mcp_sse_1_106
Draft

joshua-berri wants to merge 30 commits into
stable/1.106.xfrom
litellm_backport_mcp_sse_1_106

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Large MCP SSE results fail on stable 1.106
  • Mirrored model capabilities require main's Bedrock compatibility fixes

How it solves it:

Intentional product change: the exact main catalog mirror retires model-price rows and updates capability flags. Integrations relying on removed bundled prices need explicit registered pricing or a supported catalog entry, and callers must use the mirrored capability flags

User Flow

Before, a large tool result fails through the proxy

  1. Register a Streamable HTTP MCP server with the proxy
  2. Call its tool through POST http://localhost:4000/mcp-rest/tools/call
  3. A 3 MiB SSE result returns SSE stream ended without a response

After, the same tool returns its complete result

  1. Register a Streamable HTTP MCP server with the proxy
  2. Call its tool through POST http://localhost:4000/mcp-rest/tools/call
  3. The 3 MiB result arrives intact with isError=false

Relevant issues

Backports merged #47034 to stable/1.106.x. Remaining source-scan findings use versions still on main and are disclosed below

Linear ticket

Resolves LIT-9750

Picked changes and necessity

The new fallback route exposed a response regression. Main #45871 supplies only the needed response-envelope handling and its regression cases. A required top-level values object is preserved again. Its separate Vertex request-field migration is excluded because that field location is unchanged from the release base

The two-line guard from main #46331 makes streamed values conversion agree with non-streaming output and main. Only that guard and its regression cases are included

Release timeout interfaces remain intact. Main #47162 is not needed. Catalog-only retargets stay in separate test-only commits. Copied Vertex wire tests now validate this release's existing output_format interface while retaining their schema and routing assertions. No provider cases are skipped or removed

The public response-conversion forwarder passes the schema argument positionally, exactly as main does. The existing subclass-forwarding regression fails before this one-line correction and passes afterwards

The search-cost regression follows main’s three-line retarget from the retired OpenRouter entry to Azure, in a separate test-only commit

Pre-Submission checklist

  • Meaningful regression tests are included
  • Local MCP and Bedrock compatibility checks executed
  • Current-tip CI and completed coverage report reviewed
  • All four current-tip automated reviews completed
  • Shared-main fixable vulnerability findings resolved

Verification

Current base 978b4d1e4e91cdaaab2e16fbd02d855439e143c1, candidate f21e423323655c1c89194619a911e35460bd8f60

The affected suite passed 4836 tests with one skip and twelve class-identity failures in unchanged catalog reload behavior. The same catalog module passed all 60 cases in isolation. These isolated results are not added to the affected-suite count. The streaming-fix focused run reports 674 passed, 43 warnings in 53.20s. At this final test-only tip, the affected unit run reports 577 passed, 4 warnings in 53.86s, and copied provider collection reports 74 tests collected in 0.08s. These overlapping runs are separate measurements

The full canonical check passes backend lint, formatting, strict rules, type discipline, test quality, dashboard checks and API-type synchronization

Local changed executable-line coverage is 578/584 (98.97%). Touched-function branch coverage is separately 595/808 (73.64%). Hosted Codecov is complete at this exact tip, reporting 84.77% repository line coverage after the unit workflow completed

Both cost-map JSON files and their schema are byte-identical to main 4aec80f5ee1b3bbd2804abc123fe6663be77f775. There are no line-only catalog edits

The candidate passes all 32 live MCP observations. Both transports list tools and preserve exact 500000-byte and 3145728-byte results. The configured SSE limit rejects an oversized event and accepts the next smaller result. JSON remains independent of that limit. Zero, negative, invalid and unset limits use the safe default. All replay processes were stopped

SDK integration against a local HTTP peer preserves the requested {"values":{}} object. Streaming and non-streaming conversion of the legacy values wrapper both return [1, 2], matching main. Commands and results are recorded below

The source Grype scan uses an empty configuration and reports zero retired JavaScript dependency findings. The remaining 36 fixable matches use versions still locked by main 159b5b2f7243bba757c08e4ddc45a2514e4cd037. Exact-main upgrades cannot resolve those findings yet. No suppressions or line-only dependency overrides were added

Provider proof reaches the approved integration tier. Real-provider credentials are unavailable. The source PR's actual provider captures are linked below, and release behavior is exercised through the SDK and HTTP wire

Screenshots / Proof of Fix

The Bedrock rejection fixtures come from the source PRs’ real-provider captures. grammar_limits.txt records the grammar-limit rejection, proof_cases.md records the unsupported output-format rejection, and native_schema_keywords.txt records schema-keyword rejection. These are source-PR captures, not a claim of real-provider execution on this release. Release verification uses the executed integration tier because provider credentials are unavailable

The fixture is a real MCP SDK server. Paid LLM calls are not needed for this MCP flow. The commands and measured output below came from source-built proxies with their locked MCP versions, 2.2.0 before and 2.3.0 after. Ports in the captured commands are ephemeral; use port 4000 with the replay setup

Replay setup

Paths are relative and the key is a dummy local value. Run it once per SHA, base and head.

  1. Build a checkout and check what it imports:
git switch --detach "$SHA"
uv sync --frozen --python 3.12 --group proxy-dev --group e2e-dev --extra proxy
uv pip install --python .venv/bin/python --no-deps -e .
.venv/bin/python scripts/prisma_generate_if_needed.py
.venv/bin/python -c 'import litellm,importlib.metadata as m;print(litellm.__file__,m.version("litellm"),m.version("mcp"))'
  1. Save this as big_server.py. It is a real SDK MCPServer, SSE by default and JSON when BIG_JSON_RESPONSE=1:
import os, sys
from mcp.server.mcpserver import MCPServer
server = MCPServer("big")

@server.tool()
def dump(size: int) -> str:
    return "x" * size

if __name__ == "__main__":
    server.run("streamable-http", host="127.0.0.1", port=int(sys.argv[1]),
               json_response=os.environ.get("BIG_JSON_RESPONSE") == "1")
  1. Save this as config.yaml:
general_settings:
  master_key: sk-local-test
mcp_servers:
  big:
    url: http://127.0.0.1:18901/mcp
    transport: http
  bigjson:
    url: http://127.0.0.1:18902/mcp
    transport: http
  1. Start both MCP servers and the proxy. Add LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=200000 in front of the proxy command for the override cases:
.venv/bin/python big_server.py 18901 &
BIG_JSON_RESPONSE=1 .venv/bin/python big_server.py 18902 &
env -u DATABASE_URL -u DIRECT_URL PYTHONPATH=$PWD:$PWD/enterprise PYTHON_DOTENV_DISABLED=1 LITELLM_LOCAL_MODEL_COST_MAP=True \
  .venv/bin/python -m litellm.proxy.proxy_cli --config config.yaml --port 4000 --num_workers 1
  1. List tools, then call dump and check the returned text exactly:
H='Authorization: Bearer sk-local-test'
for srv in big bigjson; do curl -s "localhost:4000/mcp-rest/tools/list?server_id=$srv" -H "$H"; echo; done
for srv in big bigjson; do for n in 500000 3145728; do
  curl -s -X POST localhost:4000/mcp-rest/tools/call -H "$H" -H 'Content-Type: application/json' \
    -d "{\"server_id\":\"$srv\",\"name\":\"dump\",\"arguments\":{\"size\":$n}}" |
  python3 -c 'import json,sys;b=json.load(sys.stdin);t=b["content"][0]["text"];n=int(sys.argv[2]);print(sys.argv[1],n,"isError",b["isError"],"len",len(t),"exact",t=="x"*n,"" if t=="x"*n else t[:120])' $srv $n
done; done

The limit case uses sizes 90000, then 110000, then 90000 against big.

Expected output

  • Base: big 3145728 isError True len 45 exact False MCPError: SSE stream ended without a response, and every other row exact True.
  • Head: every row exact True.

Before (978b4d1)

Large tool result

  1. Run curl -sS --max-time 30 -w ' %{http_code}' 'http://127.0.0.1:51200/mcp-rest/tools/list?server_id=big' -H 'Authorization: Bearer sk-local-sse-verification'

    Output summary {"status":200,"tools":["dump"],"error":null}

  2. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:51200/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 3145728}}'

    Output summary {"status":200,"size":3145728,"isError":true,"length":45,"exact":false,"error":"MCPError: SSE stream ended without a response"}

Configured limit and recovery

  1. Run curl -sS --max-time 30 -w ' %{http_code}' 'http://127.0.0.1:51077/mcp-rest/tools/list?server_id=big' -H 'Authorization: Bearer sk-local-sse-verification'

    Output summary {"status":200,"tools":["dump"],"error":null}

  2. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:51077/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 90000}}'

    Output summary {"status":200,"size":90000,"isError":false,"length":90000,"exact":true,"error":null}

  3. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:51077/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 110000}}'

    Output summary {"status":200,"size":110000,"isError":false,"length":110000,"exact":true,"error":null}

  4. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:51077/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 90000}}'

    Output summary {"status":200,"size":90000,"isError":false,"length":90000,"exact":true,"error":null}

After (f21e423)

Large tool result

  1. Run curl -sS --max-time 30 -w ' %{http_code}' 'http://127.0.0.1:53288/mcp-rest/tools/list?server_id=big' -H 'Authorization: Bearer sk-local-sse-verification'

    Output summary {"status":200,"tools":["dump"],"error":null}

  2. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:53288/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 3145728}}'

    Output summary {"status":200,"size":3145728,"isError":false,"length":3145728,"exact":true,"error":null}

Configured limit and recovery

  1. Run curl -sS --max-time 30 -w ' %{http_code}' 'http://127.0.0.1:53171/mcp-rest/tools/list?server_id=big' -H 'Authorization: Bearer sk-local-sse-verification'

    Output summary {"status":200,"tools":["dump"],"error":null}

  2. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:53171/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 90000}}'

    Output summary {"status":200,"size":90000,"isError":false,"length":90000,"exact":true,"error":null}

  3. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:53171/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 110000}}'

    Output summary {"status":200,"size":110000,"isError":true,"length":78,"exact":false,"error":"MCPError: SSE stream failed: Server-sent event exceeded the 200000 byte limit."}

  4. Run curl -sS --max-time 30 -w ' %{http_code}' http://127.0.0.1:53171/mcp-rest/tools/call -H 'Authorization: Bearer sk-local-sse-verification' -H 'Content-Type: application/json' -d '{"server_id": "big", "name": "dump", "arguments": {"size": 90000}}'

    Output summary {"status":200,"size":90000,"isError":false,"length":90000,"exact":true,"error":null}

The reproducible response-shape commands are in the companion 1.103 backport. At f21e423323655c1c89194619a911e35460bd8f60, the required-object replay returns {"values": {}} with matches_requested_shape=true, and both streamed and non-streamed wrapper replies return [1, 2]

Adversarial review

Independent final verification passed the executed cases at f21e423323655c1c89194619a911e35460bd8f60, using this head’s frozen lock and a matching release-base source build. It passed 599 focused unit cases and all 74 batch, native-output and Vertex provider integration cases. Before, the 3 MiB MCP SSE response failed. After, both transports return exact results and the configured limit rejects an oversized event followed by successful recovery. The streamed values replay returns [1, 2] consistently. Commands and caller-visible proof are recorded above

The independent full alias suite passed 884 cases with one skip. The previous head failed the specific schema-forwarding case, which passes at this tip

The current-tip full unit workflow completed with failures, so full CI is not green. Its failed jobs repeat previously classified baseline or infrastructure failures. These are distinct from the reviewer findings below

LiteReview reviewed this tip at 5/5. Greptile is 2/5, with shared-main conversion concerns and missing annotations in new streamed-wrapper tests. The latest values-plus-summary case is being checked against main. Bugbot refuses the full catalog-sized diff, and no current-tip Veria review is available. Readiness is not claimed

Main-shared behavior is disclosed without a line-only repair. With only output_config.format, a Converse native rejection retries without the requested schema and can return plain text. The same two-request SDK/HTTP-wire probe reproduces on main 159b5b2f7243bba757c08e4ddc45a2514e4cd037

Main's response helper also treats omitted additionalProperties as disallowed when deciding whether to unwrap an object. Schema {"type":"object","properties":{"score":{"type":"integer"}}} and tool input {"meta":{"score":7}} produce {"score":7} on both builds. This is a helper-level reproduction. Independent SDK replay on the native route preserves the original object and does not reach that helper

For an empty-property open schema, the new forced-tool route returns [1, 2] from {"values":[1,2]}, matching main. The release base used native output and preserved the wrapper. This shared-main conversion is disclosed; the line-only streaming inconsistency is fixed by the selected #46331 guard

Independent SDK replay also confirms the parameters-first wrapper concern on main and 1.105. Input {"parameters":{"tier":2},"name":"json_tool_call"} remains wrapped when streamed but returns {"tier":2} without streaming. Putting name first returns {"tier":2} in both modes on both builds. This main-shared behavior is reported without extending the release patch

Type

Bug Fix

Caveats

High

  • The 36 shared-main fixable findings remain unresolved under the exact-main version requirement
  • Full unit CI is red and review gaps remain

Medium

  • Events exceeding the finite SSE limit still fail
  • Legacy SSE transport and downstream client limits remain unchanged

Release-note publication is pending the actual shipping patch version. No release version or published release note is claimed

Final Attestation

  • Every fixable Grype finding is resolved using main's versions
  • Both cost maps match the named main SHA exactly
  • Final batch verdict and reviewed SHA are recorded
  • Current-tip CI, coverage and all four reviews are complete

The retired OpenRouter Sonnet variant is removed from the catalog test exactly as on main. All 10 remaining cases pass, with coverage refreshed and no application-code change

The final test-only follow-up follows main #45668 by removing assertions about retired OpenRouter image catalog rows. It also removes the obsolete covers decorator from the new streaming-spend test and gives copied Anthropic test helpers precise types. Production code and both mirrored JSONs are unchanged

All 32 live MCP observations were replayed successfully at this final tip. Current-tip hosted CI, coverage and final independent review are being refreshed

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review this release backport at the current tip, including SDK compatibility and the large SSE response regression

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review this release backport at its current tip, including the SDK upgrade and large SSE response regression

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run Please review this release backport at its current tip, including SDK compatibility and the large SSE response regression

@codecov

codecov Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

@cursor cursor Bot left a comment

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.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit b971a75. Configure here.

@litereview

litereview Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

The earlier open finding about failing Vertex structured-output integration tests is fixed at this head. I ran all 74 cases in the changed provider files against a local proxy with Postgres and Redis, and every case passed, including both Vertex native cases.

Checks and execution details
  • Passed · real-testing-evidence (required): The PR changes translation code under litellm/llms/** (Anthropic, Bedrock converse/invoke, the native-output fallback, response envelope unwrapping and the streamed values guard) and under litellm/litellm_core_utils/prompt_templates/**. I ran the qualifying integration tests at head f21e4233 against a real proxy, Postgres, Redis and the owned scripted upstream (tests/integration/run.py):

  • providers: test_vertex_anthropic_structured_output_wire.py, test_bedrock_native_structured_output_wire.py and test_bedrock_batch_files_wire.py. 74 passed. These cover native output versus the JSON tool, retry after a native-output rejection on converse/invoke in both streaming and non-streaming modes, thinking retention, one spend row per retried request, open-object values preservation, and the Vertex output_format cases.

  • sdk: test_bedrock_native_output_fallback_sdk.py, test_bedrock_native_output_register_model_sdk.py and test_bedrock_converse_stream_sync_decoder_wire.py. 32 passed.

Fixture provenance: the PR links real Bedrock rejection captures from the source PRs (gist files grammar_limits.txt, proof_cases.md and native_schema_keywords.txt). The peers' rejection strings match those shapes.

  • Passed · compatibility-notice (required): The cost-map mirror removes bundled catalog rows. For example, get_model_info("openrouter/openai/gpt-4o") returned a model before this change and now raises isn't mapped. It also changes capability flags. The PR title carries fix(mcp)!:, and the description explains the impact and the migration: register explicit pricing or use a supported catalog entry. Raising the mcp floor from 2.2.0 to 2.3.0 is a dependency floor bump, not a broken API. LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES is a new optional setting with a safe default.
  • Passed · behavioral-coverage (required): Standards read: root AGENTS.md, tests/AGENTS.md, tests/integration/AGENTS.md and README, and tests/unit/AGENTS.md.

Traced paths:

  • MCP: env var → constants.MCP_MAX_SSE_EVENT_SIZE_BYTES (get_env_int_in_range, which falls back to 64 MiB for 0, negative, invalid or empty values) → streamable_http_client(max_sse_event_size=...) → /mcp-rest/tools/call. The MCP integration run passed 145 cases, including the 3 MiB single SSE event case and the configured-limit reject/recover case on an owned proxy.
  • Bedrock: native-output rejection → call_with_native_output_fallback on sync and async paths → second dispatch without native output. A second rejection, or any other 400, is raised to the caller.
  • Anthropic and Azure AI JSON tool responses → JsonModeRequest.tool_schema() → schema-aware unwrap_response_format_envelope. The bare values unwrap applies only when no schema is present. The streaming handler uses envelope verdicts.

Boundary cases are covered by tests: unset, empty, zero and overflowing limits; open-object values; forced-tool refusal; thinking with native output.

Unit tests: changed and related suites (anthropic, bedrock, prompt_templates, mcp client, constants, schema, cost, get_model_info, azure, pass-through) gave 8326 passed, 34 skipped. The observability integration file passed 19 of 19.

Prior finding 884537b8eeca4427a821fcb1f5a81b6b:1 is fixed. No unresolved items remain.

  • Passed · MCP integration shard (changed file) (optional): Ran tests/integration/run.py mcp tests/integration/mcp/test_mcp_transports.py: 145 passed, including test_tool_result_larger_than_one_mib_in_a_single_sse_event_reaches_the_caller and test_configured_sse_limit_rejects_large_results_and_allows_the_next_call.

View review · Reviewed f21e42332365

Comment thread litellm/constants.py Outdated

# MCP timeout defaults (seconds). Override via env vars for slow/custom MCP servers.
MCP_CLIENT_TIMEOUT: Final = float(os.getenv("LITELLM_MCP_CLIENT_TIMEOUT", "60.0"))
MCP_MAX_SSE_EVENT_SIZE_BYTES: Final = get_env_int("LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES", 64 * 1024 * 1024)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Low · Setting the SSE limit env var to 0 breaks every Streamable HTTP MCP server

  1. An operator sets LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=0, a common way to say "no limit".
  2. get_env_int accepts 0 without range checks. MCP_MAX_SSE_EVENT_SIZE_BYTES becomes 0.
  3. _create_transport_context passes that value to streamable_http_client(max_sse_event_size=0).
  4. MCP 2.3.0 raises ValueError: max_sse_event_size must be positive or None for every value at or below zero. Each Streamable HTTP tool list and tool call to any server fails. JSON-only servers fail as well.

The PR caveat asks operators to use a positive integer, but nothing enforces it. Use the existing get_env_int_in_range helper with a minimum of 1, as TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS does in constants.py. Out-of-range values then log a warning and fall back to 64 MiB.

Evidence

Reproduced in this checkout with /tmp/repro.py, a local Starlette Streamable HTTP server driven through MCPClient.call_tool.

LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=0 run with a 100-character payload logged MCP client call_tool failed - Error Type: ValueError, Error: max_sse_event_size must be positive or None and returned is_error=True.

The same payload with LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=abc succeeded because the non-numeric value fell back to the default. That run shows the only gap is the missing range check.

mcp/client/streamable_http.py:121: if max_sse_event_size is not None and max_sse_event_size <= 0: raise ValueError(...)

Latest summary by code-review · View this review · Reviewed b971a75098bf

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This backport preserves #47034’s documented positive integer requirement. Zero is unsupported, and no previously supported configuration breaks. Please reassess accordingly

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Finding still applies

Thanks for the context. You're right that this variable is new and that no previously supported configuration breaks. The finding doesn't depend on a compatibility break, though. It reports that LiteLLM accepts an invalid value without checking it.

A documented "use a positive integer" requirement is a caveat. The code doesn't enforce it, so it doesn't refute the defect:

  1. An operator sets LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=0. Many operators use 0 to mean "no limit", and the PR's replay steps also suggest 0 as an override case.
  2. get_env_int returns 0 without checking its range.
  3. _create_transport_context passes 0 to streamable_http_client for every HTTP-transport server.
  4. MCP 2.3.0 raises ValueError. Tool listing and tool calls then fail for every Streamable HTTP server, including servers that only return JSON.

A non-numeric value such as abc falls back safely to the default. A zero or negative value instead disables the transport. Switching to the existing get_env_int_in_range(..., minimum=1, ...) helper would make the documented requirement real. It would log a warning and fall back to the 64 MiB default. The severity stays low because only an operator misconfiguration can trigger this.

Evidence

litellm/constants.py:221: MCP_MAX_SSE_EVENT_SIZE_BYTES: Final = get_env_int("LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES", 64 * 1024 * 1024) has no range check.

litellm/litellm_core_utils/env_utils.py:10-23: get_env_int returns any parsed int, including 0 and negative values.

litellm/experimental_mcp_client/client.py:512-516 passes the constant to streamable_http_client on every HTTP-transport connection.

MCP 2.3.0 streamable_http.py: if max_sse_event_size is not None and max_sse_event_size <= 0: raise ValueError("max_sse_event_size must be positive or None").

Local run: LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=0 .venv/bin/python -c ... printed 0, then ValueError max_sse_event_size must be positive or None.

litellm/constants.py:470-487: get_env_int_in_range(..., minimum=1, ...) already guards TIKTOKEN_ENCODE_CHUNK_SIZE_CHARS and similar settings.

In the PR description, replay step 4 says to add LITELLM_MCP_MAX_SSE_EVENT_SIZE_BYTES=200000 "(or 0)". The Caveats section says to use a positive integer, but no code enforces that.

Reviewed b971a75098bf · View follow-up

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please reassess the low-severity finding against the documented positive integer requirement and the clarification in its review thread

@joshua-berri
joshua-berri marked this pull request as draft October 20, 2026 23:38
joshua-berri and others added 6 commits October 20, 2026 17:08
…5, and fix Fable 5 and Sonnet 4.6 schema 400s (#46870)

* fix(bedrock): use native structured output on every Claude model whose Bedrock profiles accept it

Bedrock accepts outputConfig structured output on every reachable profile of
Claude Opus 4.7, 4.8, 5, 5.5, Sonnet 5, 5.5, Haiku 5.5, and Fable 5.1, so
json_schema now goes out natively there instead of as a forced tool, which kept
Bedrock from returning adaptive thinking. Fable 5 rejects outputConfig, so its
keys go back to the tool path. GovCloud keys keep their flags, and the drift
tests let GovCloud lag its commercial base but never lead it.

* fix(bedrock): clean Claude schemas for native structured output and keep recursive schemas on the old path

Bedrock native output rejects minimum/maximum, minItems, uniqueItems, oneOf,
additionalProperties true, and recursive or unresolved $ref, all of which the
forced tool accepted. Claude schemas on the Bedrock native paths now go through
the cleaner the Anthropic native path already uses, and a schema with a
recursive or unresolved $ref keeps the forced tool, inline, or drop path it had.

* fix(bedrock): keep older installs on the json tool with a Bedrock-only native output key

Older installs fetch the model map from main, so flipping supports_native_structured_output
moved them onto native output with their old schema handling. The new
supports_bedrock_native_structured_output key is ignored by older code. Schemas native output
cannot hold (recursive refs, open objects such as dict fields) keep the json tool on the new
key, models on the old key keep their current behavior for those shapes, and the Anthropic
API, Vertex AI, and Azure keep their current behavior.

* chore(cost-map): regenerate the model prices schema for the Bedrock native output key

* fix(bedrock): keep native output to profiles every account accepts and route schemas Bedrock rejects to the json tool

Only Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.1 keep the Bedrock native output key, since
Opus 4.8 and Sonnet 5 answer 400 on some accounts and Opus 5 garbles escaped characters.
Lookaround patterns and string formats outside Bedrock's list now keep the json tool, objects
typed as a union with null are closed, and the cleaner keeps minItems of 0 or 1.

* fix(bedrock): keep Opus 5.5 and Fable 5.1 on the json tool, since native output stops their adaptive thinking

* fix(bedrock): keep shared $defs in native schemas and send refused schemas to the json tool on every native model

Native output now keeps $defs instead of inlining each use, so a submodel reused across a schema counts once against Bedrock's optional and union limits. Schemas native output cannot hold use the json tool on Converse and Invoke chat for both native keys, and minItems is only kept when it is an integer 0 or 1

* fix(bedrock): keep the json tool unless thinking is requested and bound native output schemas

The Bedrock native output key now applies only when the call asks for thinking, so calls without
thinking keep the json tool as before. Schemas past Bedrock's documented union and optional counts,
or past a grammar size estimate fitted to live probes, keep the json tool on both map keys. Open
objects keep the json tool on the Anthropic API, Vertex AI and Azure AI, where native output returned
them empty. The $ref check no longer expands $defs, so doubling definitions no longer stall the request.

* fix(bedrock): resolve root-path $defs refs so nested Pydantic models keep native output on Invoke

* test(bedrock): cover native structured output and json tool routing through the proxy

Integration cells drive the proxy against a scripted Bedrock peer that enforces Bedrock's structured output schema rules, covering thinking with native output on Converse, Converse streaming, Invoke, /v1/responses and /v1/messages, the deployment opt-in, Fable 5, schema cleaning on every native entry, open objects, and malformed schemas. Vertex, Anthropic and Azure AI cells cover open objects on native-capable models and the cleaner's minItems and nullable object handling. The unit table now covers reasoning_effort none and disabled thinking

* fix(bedrock): keep native output for numeric formats and wide old-key schemas, and keep thinking in json mode

Check string formats only on nodes that can be strings, apply the 64-field cap only to the Bedrock-only key, carry thinking blocks into the json mode message, and send malformed json tool schemas as object schemas.

* fix(anthropic): keep native output for dict fields unless the json tool can be forced

* fix(anthropic): keep native output for dict fields when the caller sends tools

* test(bedrock): close the dangerous-tool-use test schema, since Bedrock native output requires closed objects

* test(anthropic): cover forced and unforced open-object routing, json mode thinking, numeric formats and wide schemas

Add proxy cells for open-object schemas that keep native output when the json tool cannot be forced (a model that refuses forced tools on the Anthropic API and Vertex AI, thinking, caller tools), for the thinking block a json mode answer keeps on Vertex AI and Bedrock Invoke, and for integer and number formats and 65-field schemas on each Bedrock map key. Point the forced open-object cells at the Anthropic API and Azure AI only, since no Vertex AI model in the cost map takes both native output and a forced tool

* fix(bedrock): keep the native output opt-in on the deployment that sets it, and route effort none open objects to native output

* test(bedrock): cover deployment-scoped native output opt-in, register_model and effort none open objects
…net 5 and fall back to the json tool when Bedrock rejects it (#47100)

* fix(bedrock): send native structured output first on Opus 4.8 and Sonnet 5 and fall back to the json tool when Bedrock rejects it

* fix(bedrock): retry with the json tool when Bedrock refuses the native output schema

Count a 400 under output_config.format.schema: as a native output rejection, so a schema Bedrock cannot compile (like a pattern with a nested {n,m} group) gets the json tool retry instead of reaching the caller

* fix(bedrock): make the native output retry send what an opted-out deployment sends

The retry after a native output rejection now reruns the same optional param
mapping completion() ran, with the deployment model_info opted out of
supports_bedrock_native_structured_output, so tool_choice, effort and the json
tool schema match an opted-out deployment instead of a hand-built tool. Each
config keeps only the predicate that decides when native output came from the
opt-in key.

Bedrock batch records for Anthropic models map with the opt-in turned off,
since a batch job has no retry. Models on supports_native_structured_output
keep native output in batch

* fix(bedrock): build the messages retry from the caller's request and keep other errors unchanged

* fix(bedrock): give sync converse stream errors the upstream body as text

* fix(bedrock): let a malformed caller outputConfig reach Bedrock instead of raising

A Converse json_schema request whose caller outputConfig failed litellm's
shape check raised a pydantic error before the request was sent, so the
caller got a 500 where the merge base passed Bedrock's 400 through. The
opt-in check now treats that outputConfig as carrying no native output.

Also opts the vertex wire test's pinned Opus 4.8 json tool deployment out of
native output, and extends the Bedrock native output integration tests.

* fix(bedrock): send a refused caller outputConfig once and give opt-out advice only when native output is unsupported

A caller can send its own outputConfig on Converse. When Bedrock refused that
schema on an opt-in deployment, the retry still carried the caller's textFormat,
so Bedrock got the same request twice and the warning told the operator to turn
off an opt-in that was not the cause. The retry is now skipped when the opted-out
request would still carry a native textFormat, so Bedrock's 400 reaches the
caller after one call as on the merge base. The opt-out advice is logged only for
the account-level "Extra inputs are not permitted" rejection.

* fix(bedrock): keep the caller's continuation message on the native output retry

The Converse transform pops user_continue_message from litellm_params on the first attempt, so a retry built from those params afterwards dropped it. Both Bedrock chat routes now hand the fallback a copy taken before the first attempt.

* test(bedrock): pin additional_drop_params on the /v1/messages native output retry

* fix(bedrock): give the Converse native output retry the fake stream timeout
@joshua-berri
joshua-berri changed the base branch from rc/1.106.0 to stable/1.106.x October 21, 2026 01:10
@joshua-berri joshua-berri changed the title fix(mcp): backport large SSE responses to 1.106 fix(mcp): backport large SSE results and required compatibility to 1.106 Oct 21, 2026
@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review the complete backport at 1a9c678, including catalog corrections and the retained Python credential template

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review the complete backport at 1a9c678, including catalog corrections and the retained Python credential template

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review final tip 5b4c0c8, including the retained credential template and the main-aligned Sonnet catalog variant correction

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review final tip 5b4c0c8, including the retained credential template and refreshed current-tip live MCP evidence

@joshua-berri joshua-berri changed the title fix(mcp): backport large SSE results and required compatibility to 1.106 fix(mcp)!: backport large SSE results and main cost map to 1.106 Oct 21, 2026
@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Test helpers now have precise types and the obsolete marker is removed. Please review the final test-only follow-up

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review the current tip with refreshed MCP evidence, main catalog retirement, and documented identical baseline provider failures

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review 5c102bc, including the main response-preservation repair, release compatibility and the refreshed before-and-after evidence

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review 5c102bc for MCP correctness and regressions, including the main schema-preservation repair and refreshed integration evidence

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run Please review 5c102bc for actionable MCP and structured-output regressions, using the refreshed before-and-after evidence in the description

Comment on lines +193 to +199
def _allows_undeclared_keys(document: Mapping[str, JsonValue]) -> bool:
additional_properties: Final = document.get("additionalProperties")
return (
additional_properties is True
or as_json_object(additional_properties) is not None
or bool(as_json_object(document.get("patternProperties")))
)

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 Valid response fields disappear

With an optional score property and omitted additionalProperties, {"meta":{"score":7}} is valid output. _allows_undeclared_keys treats this schema as closed, so the new converter strips meta and returns {"score":7}. Preserve the default-open behavior before deciding that an object is a wrapper

Knowledge Base Used: Provider adapters and capabilities

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please verify the current tip, including copied provider tests adapted to release interfaces and the documented response-shape repairs.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review this final tip. Main-shared findings are documented, streamed values conversion is repaired, and catalog tests follow main.

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run Please review this final MCP backport tip for release-specific regressions, using the refreshed verification evidence in the description.

Comment on lines +119 to +120
if first_key.group(1) == "values" and "values" not in schema.property_names:
return "hold"

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 Valid streamed fields disappear

With additionalProperties: true, {"values":[1],"summary":"ok"} can be valid output. The new branch holds it, then returns only [1], dropping summary and replacing the object with an array. Preserve valid schema objects before unwrapping values

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!

Comment on lines +2680 to +2684
def test_streamed_json_mode_values_wrapper_is_unwrapped_like_the_non_stream_answer(
schema: dict[str, object], values: object
):
wrapped = {"values": values}
encoded = json.dumps(wrapped)

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.

P2 New tests lack required annotations

Both new tests omit -> None, and their local variables lack Final. The repository requires fully typed functions and Final annotations. Add them before merging

Context Used: AGENTS.md (source)

This branch was successfully deployed

No deployments
e2e-changed — f21e4233 Deployed Oct 21, 2026 by joshua-berri via oauth #6024
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.

2 participants