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(mcp): preserve session expiry signals and scope dependency CI
Joshua Valluruf5ab56349915
diff --cc .circleci/scripts/classify_changes.shindex 21a85c1d914,21a85c1d914..01bc8290199--- a/.circleci/scripts/classify_changes.sh+++ b/.circleci/scripts/classify_changes.sh@@@ -1,16 -1,16 +1,22 @@@#!/usr/bin/env bashset -uo pipefail--category="${1:?usage: classify_changes.sh <backend|client|ui|provider-harness|cost-map-only>}"++category="${1:?usage: classify_changes.sh <backend|client|ui|provider-harness|cost-map-only|mcp-dependencies>}"has_client=falsehas_backend=falsehas_ci=falsehas_provider_harness=falsehas_cost_map=false++has_mcp_dependencies=falseoutside_cost_map_set=falsewhile IFS= read -r file || [ -n "$file" ]; do[ -n "$file" ] || continue++ case "$file" in++ *.md | *.mdx) : ;;++ pyproject.toml | */pyproject.toml | uv.lock | uv.toml | .python-version | rust-toolchain.toml | litellm-rust/* | litellm/__init__.py | litellm/proxy/proxy_server.py | litellm/*mcp* | tests/*mcp* | litellm/integrations/arize/* | tests/base_sdk_tests/* | scripts/check_mcp_sdk_install.py | .github/workflows/test-mcp-dependency-resolution.yml | .github/actions/detect-changes/* | .github/actions/setup-uv-with-retries/* | .github/actions/cache-cargo-build/* | .github/scripts/detect_changes.sh | .github/scripts/uv_sync_with_retries.sh | .circleci/scripts/classify_changes.sh | tests/test_litellm/test_circleci_path_filter.py | tests/test_litellm/test_detect_changes.py)++ has_mcp_dependencies=true ;;++ esaccase "$file" intests/e2e/*/*.py) : ;;tests/e2e/*.py | tests/code_coverage_tests/test_provider_cache.py | tests/code_coverage_tests/test_provider_replay_harness.py | tests/test_litellm/test_circleci_path_filter.py | .circleci/* | pyproject.toml | uv.lock)@@@ -31,6 -31,6 +37,9 @@@donecase "$category" in++ mcp-dependencies)++ [ "$has_mcp_dependencies" = true ] && echo run || echo skip++ ;;cost-map-only){ [ "$has_cost_map" = true ] && [ "$outside_cost_map_set" = false ]; } && echo run || echo skip;;diff --cc .github/actions/detect-changes/action.ymlindex 9b22d2c23a8,9b22d2c23a8..b0f9b72f0ee--- a/.github/actions/detect-changes/action.yml+++ b/.github/actions/detect-changes/action.yml@@@ -14,7 -14,7 +14,7 @@@ description: >inputs:category:-- description: "Which classification to apply: backend, client or ui"++ description: "Which classification to apply: backend, client, ui, provider-harness, cost-map-only or mcp-dependencies"required: falsedefault: backendgithub-token:diff --cc .github/workflows/test-mcp-dependency-resolution.ymlindex 251dffccd4f,00000000000..b5dc573c1c1mode 100644,000000..100644--- a/.github/workflows/test-mcp-dependency-resolution.yml+++ b/.github/workflows/test-mcp-dependency-resolution.yml@@@ -1,96 -1,0 +1,98 @@@+name: LiteLLM MCP Dependency Resolution++on:+ pull_request:+ branches:+ - main+ - litellm_internal_staging+ - litellm_oss_staging+ - "litellm_**"++permissions:+ contents: read+ pull-requests: read++concurrency:+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++jobs:+ resolve:+ runs-on: ubuntu-latest+ timeout-minutes: 15+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]++ steps:+ - uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0+ with:+ persist-credentials: false++ - name: Detect relevant changes+ id: changes+ uses: ./.github/actions/detect-changes++ with:++ category: mcp-dependencies++ - name: Set up Python+ if: steps.changes.outputs.decision != 'skip'+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0+ with:+ python-version: ${{ matrix.python-version }}++ - name: Set up uv+ if: steps.changes.outputs.decision != 'skip'+ uses: ./.github/actions/setup-uv-with-retries+ with:+ version: "0.10.9"++ - name: Cache the Rust build+ if: steps.changes.outputs.decision != 'skip'+ uses: ./.github/actions/cache-cargo-build++ - name: Verify lockfile+ if: steps.changes.outputs.decision != 'skip'+ run: |+ uv lock --check++ - name: Check locked runtime installations+ if: steps.changes.outputs.decision != 'skip'+ run: |+ for extra in core mcp proxy; do+ args=()+ if [ "$extra" != core ]; then args=(--extra "$extra"); fi+ UV_PROJECT_ENVIRONMENT=".venv-$extra" .github/scripts/uv_sync_with_retries.sh --frozen --no-dev --no-editable --python ${{ matrix.python-version }} "${args[@]}"+ uv pip check --python ".venv-$extra"+ if [ "$extra" = core ]; then+ checker=("$GITHUB_WORKSPACE/tests/base_sdk_tests/check_base_sdk_install.py")+ else+ checker=("$GITHUB_WORKSPACE/scripts/check_mcp_sdk_install.py" --extra "$extra")+ fi+ (cd "$RUNNER_TEMP" && "$GITHUB_WORKSPACE/.venv-$extra/bin/python" "${checker[@]}")+ done++ - name: Build the public wheel+ if: steps.changes.outputs.decision != 'skip'+ run: uv build --all-packages --wheel --out-dir dist/mcp-check++ - name: Check lowest direct runtime installations+ if: steps.changes.outputs.decision != 'skip'+ run: |+ wheel=$(realpath dist/mcp-check/litellm-[0-9]*.whl)+ for extra in core mcp proxy; do+ args=()+ if [ "$extra" != core ]; then args=(--extra "$extra"); fi+ uv pip compile pyproject.toml --no-sources --find-links dist/mcp-check "${args[@]}" --python-version ${{ matrix.python-version }} --resolution lowest-direct -o "lowest-$extra.txt"+ uv venv --python ${{ matrix.python-version }} ".venv-lowest-$extra"+ uv pip sync --find-links dist/mcp-check --python ".venv-lowest-$extra" "lowest-$extra.txt"+ uv pip install --python ".venv-lowest-$extra" --no-deps "$wheel"+ uv pip check --python ".venv-lowest-$extra"+ if [ "$extra" = core ]; then+ checker=("$GITHUB_WORKSPACE/tests/base_sdk_tests/check_base_sdk_install.py")+ else+ checker=("$GITHUB_WORKSPACE/scripts/check_mcp_sdk_install.py" --extra "$extra")+ fi+ (cd "$RUNNER_TEMP" && "$GITHUB_WORKSPACE/.venv-lowest-$extra/bin/python" "${checker[@]}")+ donediff --cc litellm/experimental_mcp_client/Readme.mdindex 7807f6a7379,4fbd624369c..14e37dda6de--- a/litellm/experimental_mcp_client/Readme.md+++ b/litellm/experimental_mcp_client/Readme.md@@@ -1,15 -1,6 +1,15 @@@# LiteLLM MCP Client-LiteLLM MCP Client is a client that allows you to use MCP tools with LiteLLM.+LiteLLM MCP Client allows you to use MCP tools with LiteLLM+## MCP Python SDK compatibility+The `mcp` and `proxy` extras require MCP Python SDK 2.2 or newer within the 2.x release line. Installing core LiteLLM without these extras does not require MCP- Existing MCP SDK1 clients can continue connecting to the gateway over the supported legacy MCP protocols. The client and gateway can use different SDK versions in separate Python environments. Modern protocol advertisement remains disabled during the Phase 0 upgrade++Existing MCP SDK1 clients can continue connecting to the gateway over the supported legacy MCP protocols. The client and gateway can use different SDK versions in separate Python environments. Modern protocol advertisement remains disabled during the Phase 0 upgrade. An initialize body requesting `2026-07-28` falls back to the supported legacy version `2025-11-25`; an explicit `MCP-Protocol-Version: 2026-07-28` HTTP header is rejected with HTTP 400++Code sharing the gateway's Python environment must support SDK2. Its Python API has breaking changes, including renamed imports and snake_case model attributes such as `input_schema`, `is_error`, and `structured_content`. This also applies to callers consuming SDK objects returned by LiteLLM's experimental MCP client. MCP JSON fields retain their protocol spelling, such as `inputSchema` and `isError`++Upgrade SDK1-dependent libraries before installing them alongside `litellm[mcp]` or `litellm[proxy]`, or keep those clients in a separate environment and connect over the network. For example, `langchain-mcp-adapters==0.2.1` uses SDK1 Python APIs and is tested as a separate legacy client, not as a shared SDK2 dependency++See the official [SDK migration guide](https://py.sdk.modelcontextprotocol.io/migration/) for Python API changesdiff --cc litellm/experimental_mcp_client/client.pyindex a1f0e5c0830,56ee5f30d02..4b456710057--- a/litellm/experimental_mcp_client/client.py+++ b/litellm/experimental_mcp_client/client.py@@@ -149,26 -179,9 +149,25 @@@ def as_mcp_read_timeout(exc: BaseExceptTSessionResult = TypeVar("TSessionResult")-class MCPSigV4Auth(httpx.Auth):+class _MCPHTTPClient(httpx2.AsyncClient):+ async def send(+ self,+ request: httpx2.Request,+ *,+ stream: bool = False,+ auth: AuthTypes | UseClientDefault | None = httpx2.USE_CLIENT_DEFAULT,+ follow_redirects: bool | UseClientDefault = httpx2.USE_CLIENT_DEFAULT,+ ) -> httpx2.Response:+ response: Final = await super().send(request, stream=stream, auth=auth, follow_redirects=follow_redirects)- # Check after the auth flow completes so a refreshable 401 can still be retried.- if request.method == "POST" and response.is_error:++ if request.method == "POST" and response.is_error and response.status_code != 404:+ await response.aclose()+ response.raise_for_status()+ return response+++class MCPSigV4Auth(httpx2.Auth):"""- httpx Auth class that signs each request with AWS SigV4.+ httpx2 Auth class that signs each request with AWS SigV4.This is used for MCP servers that require AWS SigV4 authentication,such as AWS Bedrock AgentCore MCP servers. httpx calls auth_flow()for every outgoing request, enabling per-request signature computation.diff --cc tests/test_litellm/experimental_mcp_client/test_mcp_client.pyindex ad58ce5f00f,d9ffb0d64fe..b78d61c7bd4--- a/tests/test_litellm/experimental_mcp_client/test_mcp_client.py+++ b/tests/test_litellm/experimental_mcp_client/test_mcp_client.py@@@ -1995,3 -1949,3 +1995,63 @@@ async def test_request_auth_preview_useassert str(request.url) == "https://upstream.example/mcp"assert request.headers["Authorization"] == "Bearer resolved"assert request.headers["X-Trace"] == "trace"++++[email protected]("rpc_error", [False, True])++async def test_expired_session_preserves_sdk_error_and_next_operation_reinitializes(rpc_error: bool) -> None:++ from mcp.types import INVALID_REQUEST, METHOD_NOT_FOUND++++ requests = []++++ def respond(request: httpx2.Request) -> httpx2.Response:++ if request.method != "POST":++ return httpx2.Response(405)++ payload = json.loads(request.content)++ if "id" not in payload:++ return httpx2.Response(202)++ requests.append((payload["method"], request.headers.get("mcp-session-id")))++ if payload["method"] == "initialize":++ return httpx2.Response(200, headers={"mcp-session-id": f"session-{len(requests)}"}, json={++ "jsonrpc": "2.0", "id": payload["id"], "result": {++ "protocolVersion": "2025-06-18", "capabilities": {},++ "serverInfo": {"name": "expiry-test", "version": "1"},++ },++ })++ if len(requests) == 2:++ if rpc_error:++ return httpx2.Response(404, json={++ "jsonrpc": "2.0", "id": payload["id"],++ "error": {"code": METHOD_NOT_FOUND, "message": "Tool catalog unavailable"},++ })++ return httpx2.Response(404)++ return httpx2.Response(200, json={"jsonrpc": "2.0", "id": payload["id"], "result": {"tools": []}})++++ client = MCPClient(server_url="https://example.com/mcp", timeout=3)++ async with client._create_httpx_client_factory(transport=httpx2.MockTransport(respond))() as http_client:++ with pytest.raises(MCPError) as caught:++ await client._execute_session_operation(++ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()++ )++ assert caught.value.error.code == (METHOD_NOT_FOUND if rpc_error else INVALID_REQUEST)++ assert caught.value.error.message == ("Tool catalog unavailable" if rpc_error else "Session terminated")++ result = await client._execute_session_operation(++ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()++ )++ assert result.tools == []++ assert requests == [("initialize", None), ("tools/list", "session-1"), ("initialize", None), ("tools/list", "session-3")]++++++async def test_404_before_session_initialization_preserves_method_not_found() -> None:++ from mcp.types import METHOD_NOT_FOUND++++ client = MCPClient(server_url="https://example.com/mcp", timeout=3)++ transport = httpx2.MockTransport(lambda request: httpx2.Response(404))++ async with client._create_httpx_client_factory(transport=transport)() as http_client:++ with pytest.raises(MCPError) as caught:++ await client._execute_session_operation(++ streamable_http_client(client.server_url, http_client=http_client), lambda session: session.list_tools()++ )++ assert caught.value.error.code == METHOD_NOT_FOUND++ assert caught.value.error.message == "Not Found"diff --cc tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.pyindex 41287c122a0,33e14736357..47ec25a90f7--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_server.py@@@ -1,6 -1,6 +1,7 @@@import asyncio+ import contextlibimport contextvars+import jsonimport osfrom datetime import datetime, timedeltafrom types import SimpleNamespace@@@ -19,10 -18,9 +20,11 @@@ from mcp.types importTextContent,TextResourceContents,)+from mcp_types.version import HANDSHAKE_PROTOCOL_VERSIONS, LATEST_HANDSHAKE_VERSION- from starlette.types import Message, Scope+ from pydantic import TypeAdapter-from starlette.types import Receive, Scope, Send++from starlette.types import Message, Receive, Scope, Send+from litellm.proxy._experimental.mcp_server.mcp_context import active_mcp_request_ctx_varfrom litellm.proxy._types import (LiteLLM_MCPServerTable,MCPTransport,diff --cc tests/test_litellm/test_circleci_path_filter.pyindex 07fab42bad6,07fab42bad6..84e2327057d--- a/tests/test_litellm/test_circleci_path_filter.py+++ b/tests/test_litellm/test_circleci_path_filter.py@@@ -49,6 -49,6 +49,16 @@@ CI = [".github/workflows/test-litellm-u@pytest.mark.parametrize("category,changed,expected",[++ ("mcp-dependencies", ["pyproject.toml"], "run"),++ ("mcp-dependencies", ["uv.lock"], "run"),++ ("mcp-dependencies", ["litellm/experimental_mcp_client/client.py"], "run"),++ ("mcp-dependencies", ["tests/e2e/mcp/oauth_chat_client.py"], "run"),++ ("mcp-dependencies", ["litellm-proxy-extras/pyproject.toml"], "run"),++ ("mcp-dependencies", ["scripts/check_mcp_sdk_install.py"], "run"),++ ("mcp-dependencies", [".github/workflows/test-mcp-dependency-resolution.yml"], "run"),++ ("mcp-dependencies", [".circleci/scripts/classify_changes.sh"], "run"),++ ("mcp-dependencies", ["litellm/llms/openai/chat/gpt_transformation.py"], "skip"),++ ("mcp-dependencies", DOCS + CLIENT, "skip"),("provider-harness", ["tests/e2e/provider_cache.py"], "run"),("provider-harness", ["tests/e2e/conftest.py"], "run"),("provider-harness", ["tests/e2e/e2e_http.py"], "run"),