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 progress and cancel upstream work promptly (#46134)
joshua-berri1fc456917f57
diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.pyindex d74c0cea195..50553b59365 100644--- a/litellm/experimental_mcp_client/client.py+++ b/litellm/experimental_mcp_client/client.py@@ -5,6 +5,7 @@ LiteLLM Proxy uses this MCP Client to connnect to other MCP servers.import asyncioimport base64import hashlib+import inspectimport jsonimport osimport time@@ -1094,7 +1095,7 @@ class MCPClient:async def call_tool(self,call_tool_request_params: MCPCallToolRequestParams,- host_progress_callback: Callable | None = None,+ host_progress_callback: Callable[..., Awaitable[None]] | None = None,raise_on_error: bool = False,allow_input_required: bool = False,persistent_session: "PersistentMCPSession | None" = None,@@ -1126,7 +1127,12 @@ class MCPClient:# Forward to Host if callback providedif host_progress_callback:try:- await host_progress_callback(progress, total)+ try:+ inspect.signature(host_progress_callback).bind(progress, total, message)+ except (TypeError, ValueError):+ await host_progress_callback(progress, total)+ else:+ await host_progress_callback(progress, total, message)except Exception as e:verbose_logger.warning("Failed to forward to Host: %s", e)@@ -1579,6 +1585,20 @@ def _deliver_persistent_outcome()+async def _await_persistent_operation(operation: Awaitable[object], result: asyncio.Future[object]) -> object:+ running: Final = asyncio.ensure_future(operation)++ def cancel_operation(_: asyncio.Future[object]) -> None:+ running.cancel()++ result.add_done_callback(cancel_operation)+ try:+ (outcome,) = await asyncio.gather(running, return_exceptions=True)+ return outcome+ finally:+ result.remove_done_callback(cancel_operation)++class UpstreamSessionClosedError(RuntimeError):def __init__(self) -> None:super().__init__("upstream MCP session closed")@@ -1707,12 +1727,14 @@ class PersistentMCPSession:if callbacks is not None:self._current_callbacks = callbacksasync with self._admission() if self._admission is not None else nullcontext():- if not future.done():- (outcome,) = await asyncio.gather(operation(session), return_exceptions=True)- if _deliver_persistent_outcome(future, outcome, self._stream_error):- self._active = None- self._ended = True- return+ if not future.done() and _deliver_persistent_outcome(+ future,+ await _await_persistent_operation(operation(session), future),+ self._stream_error,+ ):+ self._active = None+ self._ended = True+ returnself._active = Noneif self._retiring and self._queue.empty():returndiff --git a/litellm/proxy/_experimental/mcp_server/contracts.py b/litellm/proxy/_experimental/mcp_server/contracts.pyindex c337c17c9ff..5c3fbde67a6 100644--- a/litellm/proxy/_experimental/mcp_server/contracts.py+++ b/litellm/proxy/_experimental/mcp_server/contracts.py@@ -122,7 +122,7 @@ class OperationContext:class ProgressCallback(Protocol):- async def __call__(self, progress: float, total: float | None, /) -> None: ...+ async def __call__(self, progress: float, total: float | None, message: str | None = None, /) -> None: ...class ClientInteraction(Protocol):diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.pyindex de0a94ba869..906e2c03dc5 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py@@ -6296,7 +6296,7 @@ class MCPServerManager:*,client: MCPClient,call_tool_params: MCPCallToolRequestParams,- host_progress_callback: Callable | None,+ host_progress_callback: Callable[..., Awaitable[None]] | None,mcp_server: MCPServer,server_auth_header: str | dict[str, str] | None,extra_headers: dict[str, str] | None,@@ -6363,7 +6363,7 @@ class MCPServerManager:oauth2_headers: dict[str, str] | None,raw_headers: dict[str, str] | None,proxy_logging_obj: ProxyLogging | None,- host_progress_callback: Callable | None = None,+ host_progress_callback: Callable[..., Awaitable[None]] | None = None,hook_extra_headers: dict[str, str] | None = None,user_api_key_auth: UserAPIKeyAuth | None = None,client_ip: str | None = None,@@ -6840,7 +6840,7 @@ class MCPServerManager:proxy_logging_obj: ProxyLogging | None = None,oauth2_headers: dict[str, str] | None = None,raw_headers: dict[str, str] | None = None,- host_progress_callback: Callable | None = None,+ host_progress_callback: Callable[..., Awaitable[None]] | None = None,litellm_logging_obj: "LiteLLMLoggingObj | None" = None,guardrail_context: Mapping[str, object] | None = None,client_ip: str | None = None,diff --git a/litellm/proxy/_experimental/mcp_server/operations.py b/litellm/proxy/_experimental/mcp_server/operations.pyindex 889ca709eb9..578f54fdd68 100644--- a/litellm/proxy/_experimental/mcp_server/operations.py+++ b/litellm/proxy/_experimental/mcp_server/operations.py@@ -2217,7 +2217,9 @@ async def _execute_mcp_tool(client_ip=client_ip,litellm_logging_obj=litellm_logging_obj,guardrail_context=guardrail_context,- host_progress_callback=host_progress_callback,+ host_progress_callback=_guarded_progress_callback(+ host_progress_callback, litellm_logging_obj, user_api_key_auth, kwargs+ ),wire_compat=wire_compat,input_responses=input_responses,request_state=request_state,@@ -2312,6 +2314,33 @@ async def _execute_mcp_tool()+def _guarded_progress_callback(+ callback: ProgressCallback | None,+ logging_obj: LiteLLMLoggingObj | None,+ caller: UserAPIKeyAuth | None,+ request_data: Mapping[str, object],+) -> ProgressCallback | None:+ if callback is None:+ return None++ async def forward(progress: float, total: float | None, message: str | None = None) -> None:+ if message is None:+ await callback(progress, total, None)+ return+ try:+ checked: Final = await _run_post_mcp_call_guardrails(+ CallToolResult(content=[TextContent(type="text", text=message)]), logging_obj, caller, request_data+ )+ filtered: Final = TextContent.model_validate(checked.content[0]).text+ except Exception: # noqa: BLE001 # any guardrail failure must withhold unverified progress text+ verbose_logger.warning("Withheld MCP progress text because its output guardrail check failed")+ await callback(progress, total, None)+ else:+ await callback(progress, total, filtered)++ return forward++async def _run_post_mcp_call_guardrails(result: CallToolResult,litellm_logging_obj: LiteLLMLoggingObj | None,diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.pyindex 097ec6e1ee9..c6ea55e9642 100644--- a/litellm/proxy/_experimental/mcp_server/server.py+++ b/litellm/proxy/_experimental/mcp_server/server.py@@ -895,14 +895,10 @@ if MCP_AVAILABLE:return Nonehost_session: Final = host_ctx.session- async def forward_progress(progress: float, total: float | None):+ async def forward_progress(progress: float, total: float | None, message: str | None = None):"""Forward progress notifications from external MCP to Host"""try:- await host_session.send_progress_notification(- progress_token=host_token,- progress=progress,- total=total,- )+ await host_session.report_progress(progress=progress, total=total, message=message)verbose_logger.debug("Forwarded progress %s/%s to Host", progress, total)except Exception as e:verbose_logger.error("Failed to forward progress to Host: %s", e)@@ -2449,9 +2445,10 @@ if MCP_AVAILABLE:"top-level key scan, skipping session lock to avoid deadlock")- session_lock: asyncio.Lock | None = None- if use_stateful and session_id and request_method in ("POST", "DELETE") and not is_jsonrpc_response:- session_lock = _stateful_session_locks.setdefault(session_id, asyncio.Lock())+ is_cancellation: Final = request_method == "POST" and _is_cancellation_notification(body)+ session_lock: Final = _stateful_request_lock(+ use_stateful, session_id, request_method, is_jsonrpc_response, is_cancellation+ )active_request_session_ids: Final[list[str]] = []@@ -2484,7 +2481,7 @@ if MCP_AVAILABLE:client_ip=_client_ip,session_id=session_id if use_stateful else None,touch_last_seen=(scope.get("method") or "").upper() != "DELETE",- copy_existing_session_auth_context=is_initialize,+ copy_existing_session_auth_context=is_initialize or is_cancellation,)local_send = scope_response or sendif use_stateful and is_initialize:@@ -2811,6 +2808,29 @@ if MCP_AVAILABLE:auth_context_var.set(auth_user)return auth_user+ def _stateful_request_lock(+ use_stateful: bool,+ session_id: str | None,+ method: str,+ is_response: bool,+ is_cancellation: bool,+ ) -> asyncio.Lock | None:+ if not use_stateful or not session_id or method not in ("POST", "DELETE") or is_response or is_cancellation:+ return None+ return _stateful_session_locks.setdefault(session_id, asyncio.Lock())++ def _is_cancellation_notification(body: bytes) -> bool:+ try:+ payload: Final = TypeAdapter(dict[str, object]).validate_json(body)+ if payload.get("jsonrpc") != "2.0" or payload.get("method") != "notifications/cancelled" or "id" in payload:+ return False+ from mcp.types import CancelledNotification++ CancelledNotification.model_validate(payload, strict=True)+ except (ValueError, TypeError):+ return False+ return True+def _set_or_update_auth_context(user_api_key_auth: UserAPIKeyAuth | None,mcp_auth_header: str | None = None,diff --git a/tests/integration/mcp/test_mcp_transports.py b/tests/integration/mcp/test_mcp_transports.pyindex 2b6494914c8..928aa9ff121 100644--- a/tests/integration/mcp/test_mcp_transports.py+++ b/tests/integration/mcp/test_mcp_transports.py@@ -644,3 +644,176 @@ def test_legacy_gateway_calls_modern_upstream_without_initialize(assert metadata["io.modelcontextprotocol/protocolVersion"] == "2026-07-28"assert "io.modelcontextprotocol/clientCapabilities" in metadataassert b"mcp-session-id" not in row.get("headers", {})++[email protected]("guardrail_action", ["off", "MASK", "BLOCK"])[email protected]("protocol", ["2025-11-25", "2026-07-28"])+def test_sdk_progress_and_cancellation_reach_upstream_without_losing_session(+ tmp_path, protocol: str, guardrail_action: str+) -> None:+ import asyncio+ import os+ from pathlib import Path+ from threading import Event+ from contextlib import asynccontextmanager++ import httpx+ import httpx2+ import yaml+ from mcp import ClientSession, MCPError+ from mcp.client.streamable_http import streamable_http_client+ from mcp.server.mcpserver import Context, MCPServer+ from mcp.server.transport_security import TransportSecuritySettings+ from mcp.types import DiscoverResult+ from sse_starlette.sse import AppStatus+ from starlette.applications import Starlette+ from starlette.routing import Mount++ from integration._support.asgi import asgi_server+ from integration._support.mcp import _drain_sse_streams+ from integration._support.process import owned_proxy++ upstream: Final = MCPServer("progress-cancellation-peer")+ started: Final = Event()+ stopped: Final = Event()+ completed: Final = Event()++ @upstream.tool()+ async def progress(ctx: Context) -> str:+ await ctx.report_progress(1, 2, "halfway")+ return "done"++ @upstream.tool()+ async def final_text() -> str:+ return "halfway"++ @upstream.tool()+ async def slow() -> str:+ started.set()+ try:+ await asyncio.sleep(20)+ completed.set()+ return "completed"+ finally:+ stopped.set()++ async def exercise(gateway: Gateway) -> None:+ observed: Final[list[tuple[float, float | None, str | None]]] = []++ async def receive_progress(value: float, total: float | None, message: str | None) -> None:+ observed.append((value, total, message))++ async with httpx2.AsyncClient(headers={"Authorization": "Bearer " + gateway.key}) as client:+ async with streamable_http_client(+ str(gateway.client.base_url).rstrip("/") + "/mcp/", http_client=client+ ) as streams:+ async with ClientSession(streams[0], streams[1]) as session:+ if protocol == "2026-07-28":+ session.adopt(DiscoverResult.model_validate(await session.send_discover(protocol)))+ else:+ await session.initialize()+ listed = await session.list_tools()+ assert {"peer-progress", "peer-slow"} <= {tool.name for tool in listed.tools}+ if guardrail_action != "off":+ try:+ checked = await session.call_tool("peer-final_text", {})+ except MCPError:+ assert guardrail_action == "BLOCK"+ else:+ if guardrail_action == "BLOCK":+ assert checked.is_error+ else:+ assert not checked.is_error+ assert "halfway" not in str(checked.content)+ result = await session.call_tool("peer-progress", {}, progress_callback=receive_progress)+ assert not result.is_error+ assert len(observed) == 1+ assert observed[0][:2] == (1.0, 2.0)+ if guardrail_action == "BLOCK":+ assert observed[0][2] is None+ elif guardrail_action == "MASK":+ assert observed[0][2] and "halfway" not in observed[0][2]+ else:+ assert observed[0][2] == "halfway"+ call = asyncio.create_task(session.call_tool("peer-slow", {}))+ try:+ assert await asyncio.to_thread(started.wait, 5), "Upstream tool did not start"+ call.cancel()+ with pytest.raises(asyncio.CancelledError):+ await call+ assert await asyncio.to_thread(stopped.wait, 2), "Cancelled upstream work kept running"+ assert not completed.is_set()+ followup = await session.call_tool("peer-progress", {})+ assert not followup.is_error, "Cancellation must leave later calls usable"+ finally:+ call.cancel()+ await asyncio.gather(call, return_exceptions=True)++ app: Final = upstream.streamable_http_app(+ transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False)+ )++ @asynccontextmanager+ async def lifespan(_: Starlette):+ AppStatus.should_exit = False+ async with app.router.lifespan_context(app):+ yield+ _drain_sse_streams()+ watchers = tuple(task for task in asyncio.all_tasks() if "_shutdown_watcher" in repr(task.get_coro()))+ await asyncio.wait_for(asyncio.gather(*watchers), 2)++ hosted: Final = Starlette(routes=[Mount("/", app=app)], lifespan=lifespan)+ with asgi_server(hosted) as upstream_url, httpx.Client() as client:+ config: Final = tmp_path / "proxy.yaml"+ config.write_text(+ yaml.safe_dump(+ {+ "model_list": [],+ "guardrails": []+ if guardrail_action == "off"+ else [+ {+ "guardrail_name": "progress-policy",+ "litellm_params": {+ "guardrail": "litellm_content_filter",+ "mode": "post_mcp_call",+ "default_on": True,+ "blocked_words": [{"keyword": "halfway", "action": guardrail_action}],+ },+ }+ ],+ "mcp_servers": {+ "peer": {"url": upstream_url + "/mcp", "transport": "http", "protocol_version": protocol}+ },+ "general_settings": {+ "master_key": "sk-progress-cancellation-test",+ "store_model_in_db": False,+ "mcp_advertised_versions": ["2025-11-25", "2026-07-28"],+ },+ }+ )+ )+ source: Final = Path(__file__).resolve().parents[3]+ environment: Final = {+ "PYTHONPATH": os.pathsep.join((str(source), str(source / "tests"))),+ "STORE_MODEL_IN_DB": "False",+ "DISABLE_SCHEMA_UPDATE": "true",+ "LITELLM_LOCAL_MODEL_COST_MAP": "True",+ "LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY": "true",+ }+ seed: Final = Gateway(client, "sk-progress-cancellation-test", upstream_url)+ with owned_proxy(+ seed,+ tmp_path / "gateway",+ environment,+ config=config,+ database_setup=(),+ remove_environment=(+ "DATABASE_URL",+ "DATABASE_URL_READ_REPLICA",+ "DIRECT_URL",+ "INTEGRATION_PROXY_DATABASE_URL",+ "INTEGRATION_PROXY_READ_REPLICA_URL",+ ),+ ) as gateway:+ asyncio.run(exercise(gateway))diff --git a/tests/unit/experimental_mcp_client/test_mcp_client.py b/tests/unit/experimental_mcp_client/test_mcp_client.pyindex f92f7f74eb6..5aba5d5dfd6 100644--- a/tests/unit/experimental_mcp_client/test_mcp_client.py+++ b/tests/unit/experimental_mcp_client/test_mcp_client.py@@ -5018,3 +5018,73 @@ async def test_persistent_session_releases_the_current_requests_scope_response(sactive_mcp_request_ctx_var.reset(token)session.close()await asyncio.wait_for(session.wait_closed(), 5)+[email protected]("legacy_callback", [False, True])+async def test_tool_progress_preserves_message_and_legacy_callback(legacy_callback: bool) -> None:+ received = AsyncMock()++ async def legacy(progress: float, total: float | None) -> None:+ await received(progress, total)++ async def modern(progress: float, total: float | None, message: str | None) -> None:+ await received(progress, total, message)++ async def call_tool(**kwargs):+ await kwargs["progress_callback"](1.0, 2.0, "halfway")+ return CallToolResult(content=[])++ session = AsyncMock(spec=ClientSession, call_tool=AsyncMock(side_effect=call_tool))++ async def run(operation, **kwargs):+ return await operation(session)++ persistent = MagicMock(spec=PersistentMCPSession, run=AsyncMock(side_effect=run))+ client = MCPClient(server_url="https://example.com/mcp")+ result = await client.call_tool(+ CallToolRequestParams(name="slow"),+ host_progress_callback=legacy if legacy_callback else modern,+ persistent_session=persistent,+ )+ assert not result.is_error+ if legacy_callback:+ received.assert_awaited_once_with(1.0, 2.0)+ else:+ received.assert_awaited_once_with(1.0, 2.0, "halfway")+++async def test_cancelling_persistent_operation_stops_work_and_keeps_session_usable() -> None:+ app: Final = _stateful_upstream()+ async with app.router.lifespan_context(app):+ client, session = _client_with_session(app)+ started: Final = asyncio.Event()+ stopped: Final = asyncio.Event()++ async def slow_operation(_: ClientSession) -> None:+ started.set()+ try:+ await asyncio.Event().wait()+ finally:+ stopped.set()++ waiter: Final = asyncio.create_task(session.run(slow_operation))+ try:+ await asyncio.wait_for(started.wait(), 5)+ waiter.cancel()+ with pytest.raises(asyncio.CancelledError):+ await waiter+ await asyncio.sleep(0.1)+ assert stopped.is_set(), "Caller cancellation must stop the running upstream operation"+ result: Final = await asyncio.wait_for(+ client.call_tool(+ CallToolRequestParams(name="select_project", arguments={"name": "after-cancellation"}),+ persistent_session=session,+ ),+ 5,+ )+ assert not result.is_error+ finally:+ session.close()+ await asyncio.wait_for(session.wait_closed(), 5)+ await asyncio.gather(waiter, return_exceptions=True)diff --git a/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_tool_calls_and_headers.py b/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_tool_calls_and_headers.pyindex c109d3fdbd0..48106b1de5f 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_tool_calls_and_headers.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_mcp_server_tool_calls_and_headers.py@@ -3756,7 +3756,11 @@ async def test_owner_fingerprint_hashes_custom_api_keys():@pytest.mark.asyncio-async def test_stateful_mcp_session_owner_mismatch_returns_403():[email protected]("body", [+ b'{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}',+ b'{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":0}}',+])+async def test_stateful_mcp_session_owner_mismatch_returns_403(body: bytes):"""A stateful mcp-session-id is bound to its creator. A differentauthenticated caller presenting the same session_id must be rejected@@ -3791,7 +3795,7 @@ async def test_stateful_mcp_session_owner_mismatch_returns_403():receive = AsyncMock(return_value={"type": "http.request",- "body": b'{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}',+ "body": body,"more_body": False,})@@ -11695,3 +11699,124 @@ async def test_streamable_http_admission_auth_sees_only_peeked_jsonrpc_method()assert downstream_bodies == [_INITIALIZE]stateless_handle.assert_not_awaited()send.assert_not_awaited()++ "payload, valid",+ [+ (b"{", False),+ (b"\xff", False),+ ({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 0}}, True),+ ({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": "call"}}, True),+ ({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {}}, True),+ ({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": False}}, False),+ ({"jsonrpc": "2.0", "id": 4, "method": "notifications/cancelled", "params": {"requestId": 0}}, False),+ ({"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}, False),+ ],+)+async def test_stateful_cancellation_does_not_wait_for_call_or_change_its_auth(payload, valid):+ from litellm.proxy._experimental.mcp_server import server as mcp_server++ session_id = "cancellation-isolation-session"+ owner = UserAPIKeyAuth(api_key="owner-key", user_id="owner")+ original = mcp_server.MCPAuthenticatedUser(user_api_key_auth=owner, raw_headers={"x-call": "active"})+ mcp_server._stateful_session_auth_contexts[session_id] = original+ mcp_server._stateful_session_owners[session_id] = mcp_server._owner_fingerprint_for(owner)+ lock = asyncio.Lock()+ mcp_server._stateful_session_locks[session_id] = lock+ reached = asyncio.Event()++ async def handle(scope, receive, send):+ assert lock.locked(), "The active call must still own its session lock"+ assert mcp_server._stateful_session_auth_contexts[session_id] is original+ assert original.raw_headers == {"x-call": "active"}+ assert mcp_server.auth_context_var.get() is not original+ reached.set()++ scope = {+ "type": "http",+ "method": "POST",+ "path": "/mcp",+ "headers": [(b"mcp-session-id", session_id.encode())],+ }+ receive = AsyncMock(+ return_value={+ "type": "http.request",+ "more_body": False,+ "body": payload if isinstance(payload, bytes) else json.dumps(payload).encode(),+ }+ )+ try:+ with (+ patch.object(+ mcp_server,+ "extract_mcp_auth_context",+ new_callable=AsyncMock,+ return_value=(owner, None, None, None, None, {"x-control": "cancel"}),+ ),+ patch.object(mcp_server, "_SESSION_MANAGERS_INITIALIZED", True),+ patch.object(mcp_server.session_manager_stateful, "handle_request", side_effect=handle),+ patch.object(mcp_server.session_manager_stateful, "_server_instances", {session_id: MagicMock()}),+ ):+ async with lock:+ task = asyncio.create_task(mcp_server.handle_streamable_http_mcp(scope, receive, AsyncMock()))+ try:+ done, _ = await asyncio.wait((task,), timeout=0.5)+ if valid:+ assert task in done, "Cancellation waited behind the active tool call"+ await task+ assert reached.is_set()+ else:+ assert not done, "Only a valid cancellation notification may bypass the call lock"+ assert not reached.is_set()+ finally:+ if not task.done():+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ finally:+ mcp_server._remove_stateful_session_tracking(session_id)++[email protected]("action", ["MASK", "BLOCK"])[email protected]("message", [None, "", "halfway"])[email protected]("selected", [False, True])+async def test_progress_text_obeys_request_output_guardrails(monkeypatch, action, message, selected):+ import litellm++ from litellm.caching.caching import DualCache+ from litellm.proxy import proxy_server+ from litellm.proxy._experimental.mcp_server.operations import _guarded_progress_callback+ from litellm.proxy.guardrails.guardrail_hooks.litellm_content_filter.content_filter import ContentFilterGuardrail+ from litellm.proxy.utils import ProxyLogging+ from litellm.types.guardrails import BlockedWord, ContentFilterAction, GuardrailEventHooks++ policy = ContentFilterGuardrail(+ guardrail_name="progress-policy", event_hook=GuardrailEventHooks.post_mcp_call,+ blocked_words=[BlockedWord(keyword="halfway", action=ContentFilterAction(action))],+ keyword_redaction_tag="[masked]", default_on=False,+ )+ monkeypatch.setattr(litellm, "callbacks", [policy])+ monkeypatch.setattr(proxy_server, "proxy_logging_obj", ProxyLogging(user_api_key_cache=DualCache()))+ delivered = AsyncMock()+ caller = UserAPIKeyAuth(user_id="progress-user")+ callback = _guarded_progress_callback(+ delivered, None, caller, {"metadata": {"guardrails": ["progress-policy"] if selected else []}}+ )+ assert callback is not None+ await callback(0, None, message)+ expected = ("[masked]" if action == "MASK" else None) if selected and message == "halfway" else message+ delivered.assert_awaited_once_with(0, None, expected)+++async def test_progress_callback_preserves_absence_and_cancellation():+ import asyncio++ from litellm.proxy._experimental.mcp_server.operations import _guarded_progress_callback++ assert _guarded_progress_callback(None, None, None, {}) is None+ callback = _guarded_progress_callback(AsyncMock(side_effect=asyncio.CancelledError), None, None, {})+ assert callback is not None+ with pytest.raises(asyncio.CancelledError):+ await callback(0, 0, None)diff --git a/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py b/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.pyindex 9cb3e230aa6..ea0dd70cd22 100644--- a/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py+++ b/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py@@ -1284,7 +1284,12 @@ class TestCaptureHostProgressCallback:@pytest.mark.asyncio@pytest.mark.parametrize("token", ["tok12345", 12345, 0])- async def test_forwards_wire_progress_token(self, _mcp_request_ctx, token) -> None:+ @pytest.mark.parametrize("message", [None, "halfway"])+ @pytest.mark.parametrize("delivery_error", [None, RuntimeError("request stream closed")])+ async def test_forwards_progress_on_originating_request(self, _mcp_request_ctx, token, message, delivery_error) -> None:+ from mcp.server.connection import Connection+ from mcp.server.session import ServerSession+ from mcp.shared.dispatcher import DispatchContextfrom mcp.types import CallToolRequestParamsfrom litellm.proxy._experimental.mcp_server.server import _capture_host_progress_callback@@ -1292,13 +1297,14 @@ class TestCaptureHostProgressCallback:params = CallToolRequestParams.model_validate({"name": "tool", "_meta": {"progressToken": token}}, by_name=False)- session = AsyncMock()+ channel = AsyncMock(spec=DispatchContext, progress=AsyncMock(side_effect=delivery_error))+ connection = MagicMock(spec=Connection, protocol_version="2025-11-25", outbound=AsyncMock())+ session = ServerSession(channel, connection, request_meta=params.meta)callback = _capture_host_progress_callback(_mcp_request_ctx(meta=params.meta, session=session))assert callback is not None- await callback(0.5, 1.0)- session.send_progress_notification.assert_awaited_once_with(- progress_token=token, progress=0.5, total=1.0- )+ await callback(0.5, 1.0, message)+ channel.progress.assert_awaited_once_with(0.5, 1.0, message)+ connection.outbound.notify.assert_not_awaited()class TestHandleListToolsVirtual: