Skip to content

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]

[Feat] enable progress notifications for MCP tool calls (#19809)

houdataali29ee5aab5c05
diff --git a/litellm/experimental_mcp_client/client.py b/litellm/experimental_mcp_client/client.py
index 63433c5a467..3cbb02259b2 100644
--- a/litellm/experimental_mcp_client/client.py
+++ b/litellm/experimental_mcp_client/client.py
@@ -286,7 +286,9 @@ class MCPClient:
return []
async def call_tool(
- self, call_tool_request_params: MCPCallToolRequestParams
+ self,
+ call_tool_request_params: MCPCallToolRequestParams,
+ host_progress_callback: Optional[Callable] = None
) -> MCPCallToolResult:
"""
Call an MCP Tool.
@@ -295,13 +297,28 @@ class MCPClient:
f"MCP client calling tool '{call_tool_request_params.name}' with arguments: {call_tool_request_params.arguments}"
)
+ async def on_progress(progress: float, total: float | None, message: str | None):
+ percentage = (progress / total * 100) if total else 0
+ verbose_logger.info(
+ f"MCP Tool '{call_tool_request_params.name}' progress: "
+ f"{progress}/{total} ({percentage:.0f}%) - {message or ''}"
+ )
+
+ # Forward to Host if callback provided
+ if host_progress_callback:
+ try:
+ await host_progress_callback(progress, total)
+ except Exception as e:
+ verbose_logger.warning(f"Failed to forward to Host: {e}")
+
async def _call_tool_operation(session: ClientSession):
verbose_logger.debug("MCP client sending tool call to session")
return await session.call_tool(
name=call_tool_request_params.name,
arguments=call_tool_request_params.arguments,
- )
+ progress_callback=on_progress,
+ )
try:
tool_result = await self.run_with_session(_call_tool_operation)
verbose_logger.info(
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
index e0217cd9e00..81806d6c066 100644
--- a/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
+++ b/litellm/proxy/_experimental/mcp_server/mcp_server_manager.py
@@ -11,7 +11,7 @@ import datetime
import hashlib
import json
import re
-from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union, cast
+from typing import Any, Dict, List, Literal, Optional, Set, Tuple, Union, cast, Callable
from urllib.parse import urlparse
from fastapi import HTTPException
@@ -1825,6 +1825,7 @@ class MCPServerManager:
oauth2_headers: Optional[Dict[str, str]],
raw_headers: Optional[Dict[str, str]],
proxy_logging_obj: Optional[ProxyLogging],
+ host_progress_callback: Optional[Callable] = None,
) -> CallToolResult:
"""
Call a regular MCP tool using the MCP client.
@@ -1909,7 +1910,7 @@ class MCPServerManager:
)
async def _call_tool_via_client(client, params):
- return await client.call_tool(params)
+ return await client.call_tool(params, host_progress_callback=host_progress_callback)
tasks.append(
asyncio.create_task(_call_tool_via_client(client, call_tool_params))
@@ -1946,6 +1947,8 @@ class MCPServerManager:
proxy_logging_obj: Optional[ProxyLogging] = None,
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
+ host_progress_callback: Optional[Callable] = None,
+
) -> CallToolResult:
"""
Call a tool with the given name and arguments
@@ -2021,6 +2024,7 @@ class MCPServerManager:
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
proxy_logging_obj=proxy_logging_obj,
+ host_progress_callback=host_progress_callback,
)
# For OpenAPI tools, await outside the client context
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 03652ae155e..51f476fad0f 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -8,8 +8,7 @@ import contextlib
from datetime import datetime
import traceback
import uuid
-from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Union, cast
-
+from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Union, cast, Callable
from fastapi import FastAPI, HTTPException
from pydantic import AnyUrl, ConfigDict
from starlette.types import Receive, Scope, Send
@@ -124,8 +123,8 @@ if MCP_AVAILABLE:
session_manager = StreamableHTTPSessionManager(
app=server,
event_store=None,
- json_response=True, # Use JSON responses instead of SSE by default
- stateless=True,
+ json_response=False, # enables SSE streaming
+ stateless=False, # enables session state
)
# Create SSE session manager
@@ -278,6 +277,30 @@ if MCP_AVAILABLE:
verbose_logger.debug(
f"MCP mcp_server_tool_call - User API Key Auth from context: {user_api_key_auth}"
)
+ host_progress_callback = None
+ try:
+ host_ctx = server.request_context
+ if host_ctx and hasattr(host_ctx, 'meta') and host_ctx.meta:
+ host_token = getattr(host_ctx.meta, 'progressToken', None)
+ if host_token and hasattr(host_ctx, 'session') and host_ctx.session:
+ host_session = host_ctx.session
+
+ async def forward_progress(progress: float, total: float | None):
+ """Forward progress notifications from external MCP to Host"""
+ try:
+ await host_session.send_progress_notification(
+ progress_token=host_token,
+ progress=progress,
+ total=total
+ )
+ verbose_logger.debug(f"Forwarded progress {progress}/{total} to Host")
+ except Exception as e:
+ verbose_logger.error(f"Failed to forward progress to Host: {e}")
+
+ host_progress_callback = forward_progress
+ verbose_logger.debug(f"Host progressToken captured: {host_token[:8]}...")
+ except Exception as e:
+ verbose_logger.warning(f"Could not capture host progress context: {e}")
try:
# Create a body date for logging
body_data = {"name": name, "arguments": arguments}
@@ -307,6 +330,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers=mcp_server_auth_headers,
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
+ host_progress_callback=host_progress_callback,
**data, # for logging
)
except BlockedPiiEntityError as e:
@@ -1341,6 +1365,7 @@ if MCP_AVAILABLE:
mcp_server_auth_headers: Optional[Dict[str, Dict[str, str]]] = None,
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
+ host_progress_callback: Optional[Callable] = None,
**kwargs: Any,
) -> CallToolResult:
"""
@@ -1438,6 +1463,7 @@ if MCP_AVAILABLE:
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
litellm_logging_obj=litellm_logging_obj,
+ host_progress_callback=host_progress_callback,
)
# Fall back to local tool registry with original name (legacy support)
@@ -1685,6 +1711,7 @@ if MCP_AVAILABLE:
oauth2_headers: Optional[Dict[str, str]] = None,
raw_headers: Optional[Dict[str, str]] = None,
litellm_logging_obj: Optional[Any] = None,
+ host_progress_callback: Optional[Callable] = None,
) -> CallToolResult:
"""Handle tool execution for managed server tools"""
# Import here to avoid circular import
@@ -1700,6 +1727,7 @@ if MCP_AVAILABLE:
oauth2_headers=oauth2_headers,
raw_headers=raw_headers,
proxy_logging_obj=proxy_logging_obj,
+ host_progress_callback=host_progress_callback,
)
verbose_logger.debug("CALL TOOL RESULT: %s", call_tool_result)
return call_tool_result
diff --git a/tests/mcp_tests/test_mcp_client_unit.py b/tests/mcp_tests/test_mcp_client_unit.py
index fcee3208be1..9533e56bcc8 100644
--- a/tests/mcp_tests/test_mcp_client_unit.py
+++ b/tests/mcp_tests/test_mcp_client_unit.py
@@ -5,7 +5,7 @@ import base64
import os
import sys
import pytest
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch, ANY
# Add the project root to the path
sys.path.insert(0, os.path.abspath("../../.."))
@@ -183,7 +183,7 @@ class TestMCPClientUnitTests:
assert result == mock_result
mock_session_instance.initialize.assert_called_once()
mock_session_instance.call_tool.assert_called_once_with(
- name="test_tool", arguments={"arg1": "value1"}
+ name="test_tool", arguments={"arg1": "value1"},progress_callback=ANY
)