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]

[MCP Gateway] - Allow using custom post call MCP hook for cost tracking (#12469)

Ishaan Jaff35bfa7c9ee53
diff --git a/docs/my-website/docs/mcp.md b/docs/my-website/docs/mcp.md
index 3ef22387533..28d2535dbd7 100644
--- a/docs/my-website/docs/mcp.md
+++ b/docs/my-website/docs/mcp.md
@@ -494,6 +494,122 @@ curl --location '<your-litellm-proxy-base-url>/v1/responses' \
+## ✨ MCP Cost Tracking
+
+LiteLLM provides two ways to track costs for MCP tool calls:
+
+| Method | When to Use | What It Does |
+|--------|-------------|--------------|
+| **Config-based Cost Tracking** | Simple cost tracking with fixed costs per tool/server | Automatically tracks costs based on configuration |
+| **Custom Post-MCP Hook** | Dynamic cost tracking with custom logic | Allows custom cost calculations and response modifications |
+
+### Config-based Cost Tracking
+
+Configure fixed costs for MCP servers directly in your config.yaml:
+
+```yaml title="config.yaml" showLineNumbers
+model_list:
+ - model_name: gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: sk-xxxxxxx
+
+mcp_servers:
+ zapier_server:
+ url: "https://actions.zapier.com/mcp/sk-xxxxx/sse"
+ mcp_info:
+ mcp_server_cost_info:
+ # Default cost for all tools in this server
+ default_cost_per_query: 0.01
+ # Custom cost for specific tools
+ tool_name_to_cost_per_query:
+ send_email: 0.05
+ create_document: 0.03
+
+ expensive_api_server:
+ url: "https://api.expensive-service.com/mcp"
+ mcp_info:
+ mcp_server_cost_info:
+ default_cost_per_query: 1.50
+```
+
+### Custom Post-MCP Hook
+
+Use this when you need dynamic cost calculation or want to modify the MCP response before it's returned to the user.
+
+#### 1. Create a custom MCP hook file
+
+```python title="custom_mcp_hook.py" showLineNumbers
+from typing import Optional
+from litellm.integrations.custom_logger import CustomLogger
+from litellm.types.mcp import MCPPostCallResponseObject
+
+
+class CustomMCPCostTracker(CustomLogger):
+ """
+ Custom handler for MCP cost tracking and response modification
+ """
+
+ async def async_post_mcp_tool_call_hook(
+ self,
+ kwargs,
+ response_obj: MCPPostCallResponseObject,
+ start_time,
+ end_time
+ ) -> Optional[MCPPostCallResponseObject]:
+ """
+ Called after each MCP tool call.
+ Modify costs and response before returning to user.
+ """
+
+ # Extract tool information from kwargs
+ tool_name = kwargs.get("name", "")
+ server_name = kwargs.get("server_name", "")
+
+ # Calculate custom cost based on your logic
+ custom_cost = 42.00
+
+ # Set the response cost
+ response_obj.hidden_params.response_cost = custom_cost
+
+
+
+ return response_obj
+
+
+# Create instance for LiteLLM to use
+custom_mcp_cost_tracker = CustomMCPCostTracker()
+```
+
+#### 2. Configure in config.yaml
+
+```yaml title="config.yaml" showLineNumbers
+model_list:
+ - model_name: gpt-4o
+ litellm_params:
+ model: openai/gpt-4o
+ api_key: sk-xxxxxxx
+
+# Add your custom MCP hook
+callbacks:
+ - custom_mcp_hook.custom_mcp_cost_tracker
+
+mcp_servers:
+ zapier_server:
+ url: "https://actions.zapier.com/mcp/sk-xxxxx/sse"
+```
+
+#### 3. Start the proxy
+
+```shell
+$ litellm --config /path/to/config.yaml
+```
+
+When MCP tools are called, your custom hook will:
+1. Calculate costs based on your custom logic
+2. Modify the response if needed
+3. Track costs in LiteLLM's logging system
+
## ✨ MCP Permission Management
LiteLLM supports managing permissions for MCP Servers by Keys, Teams, Organizations (entities) on LiteLLM. When a MCP client attempts to list tools, LiteLLM will only return the tools the entity has permissions to access.
diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.py
index a9cbc65e6f4..a73dc6791e2 100644
--- a/litellm/integrations/custom_logger.py
+++ b/litellm/integrations/custom_logger.py
@@ -33,12 +33,14 @@ if TYPE_CHECKING:
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.proxy._types import UserAPIKeyAuth
+ from litellm.types.mcp import MCPPostCallResponseObject
Span = Union[_Span, Any]
else:
Span = Any
LiteLLMLoggingObj = Any
UserAPIKeyAuth = Any
+ MCPPostCallResponseObject = Any
class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callback#callback-class
@@ -353,6 +355,18 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbac
except Exception:
print_verbose(f"Custom Logger Error - {traceback.format_exc()}")
pass
+
+ #########################################################
+ # MCP TOOL CALL HOOKS
+ #########################################################
+ async def async_post_mcp_tool_call_hook(self, kwargs, response_obj: MCPPostCallResponseObject, start_time, end_time) -> Optional[MCPPostCallResponseObject]:
+ """
+ This log gets called after the MCP tool call is made.
+
+ Useful if you want to modiy the standard logging payload after the MCP tool call is made.
+ """
+ return None
+
# Useful helpers for custom logger classes
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 0b5fea85176..e1b8d8b5dbc 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -82,6 +82,7 @@ from litellm.types.llms.openai import (
ResponseCompletedEvent,
ResponsesAPIResponse,
)
+from litellm.types.mcp import MCPPostCallResponseObject
from litellm.types.rerank import RerankResponse
from litellm.types.router import CustomPricingLiteLLMParams
from litellm.types.utils import (
@@ -1061,6 +1062,63 @@ class Logging(LiteLLMLoggingBaseClass):
)
)
+ async def async_post_mcp_tool_call_hook(
+ self,
+ kwargs: dict,
+ response_obj: Any,
+ start_time: datetime.datetime,
+ end_time: datetime.datetime,
+ ):
+ """
+ Post MCP Tool Call Hook
+
+ Use this to modify the MCP tool call response before it is returned to the user.
+ """
+ from litellm.types.llms.base import HiddenParams
+ from litellm.types.mcp import MCPPostCallResponseObject
+ callbacks = self.get_combined_callback_list(
+ dynamic_success_callbacks=self.dynamic_success_callbacks,
+ global_callbacks=litellm.success_callback,
+ )
+ post_mcp_tool_call_response_obj: MCPPostCallResponseObject = MCPPostCallResponseObject(
+ mcp_tool_call_response=response_obj,
+ hidden_params=HiddenParams()
+ )
+ for callback in callbacks:
+ try:
+ if isinstance(callback, CustomLogger):
+ response: Optional[MCPPostCallResponseObject] = await callback.async_post_mcp_tool_call_hook(
+ kwargs=kwargs,
+ response_obj=post_mcp_tool_call_response_obj,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ ######################################################################
+ # if any of the callbacks modify the response, use the modified response
+ # current implementation returns the first modified response
+ ######################################################################
+ if response is not None:
+ response_obj = self._parse_post_mcp_call_hook_response(response=response)
+ except Exception as e:
+ verbose_logger.exception(
+ "LiteLLM.LoggingError: [Non-Blocking] Exception occurred while logging {}".format(
+ str(e)
+ )
+ )
+ return response_obj
+
+ def _parse_post_mcp_call_hook_response(self, response: Optional[MCPPostCallResponseObject]) -> Any:
+ """
+ Parse the response from the post_mcp_tool_call_hook
+
+ 1. Unpack the mcp_tool_call_response
+ 2. save the updated response_cost to the model_call_details
+ """
+ if response is None:
+ return None
+ self.model_call_details["response_cost"] = response.hidden_params.response_cost
+ return response.mcp_tool_call_response
+
def get_response_ms(self) -> float:
return (
self.model_call_details.get("end_time", datetime.datetime.now())
diff --git a/litellm/proxy/_experimental/mcp_server/cost_calculator.py b/litellm/proxy/_experimental/mcp_server/cost_calculator.py
index da47682be6b..eea10924a11 100644
--- a/litellm/proxy/_experimental/mcp_server/cost_calculator.py
+++ b/litellm/proxy/_experimental/mcp_server/cost_calculator.py
@@ -15,7 +15,9 @@ else:
class MCPCostCalculator:
@staticmethod
- def calculate_mcp_tool_call_cost(litellm_logging_obj: Optional[LitellmLoggingObject]) -> float:
+ def calculate_mcp_tool_call_cost(
+ litellm_logging_obj: Optional[LitellmLoggingObject],
+ ) -> float:
"""
Calculate the cost of an MCP tool call.
@@ -24,6 +26,14 @@ class MCPCostCalculator:
if litellm_logging_obj is None:
return 0.0
+ #########################################################
+ # Get the response cost from logging object model_call_details
+ # This is set when a user modifies the response in a post_mcp_tool_call_hook
+ #########################################################
+ response_cost = litellm_logging_obj.model_call_details.get("response_cost", None)
+ if response_cost is not None:
+ return response_cost
+
#########################################################
# Unpack the mcp_tool_call_metadata
#########################################################
diff --git a/litellm/proxy/_experimental/mcp_server/server.py b/litellm/proxy/_experimental/mcp_server/server.py
index 6ec68aba1f0..79f31ad03c6 100644
--- a/litellm/proxy/_experimental/mcp_server/server.py
+++ b/litellm/proxy/_experimental/mcp_server/server.py
@@ -4,6 +4,7 @@ LiteLLM MCP Server Routes
import asyncio
import contextlib
+from datetime import datetime
from typing import Any, AsyncIterator, Dict, List, Optional, Tuple, Union
from fastapi import FastAPI, HTTPException
@@ -50,9 +51,7 @@ if MCP_AVAILABLE:
auth_context_var,
)
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
- from mcp.types import EmbeddedResource as MCPEmbeddedResource
- from mcp.types import ImageContent as MCPImageContent
- from mcp.types import TextContent as MCPTextContent
+ from mcp.types import EmbeddedResource, ImageContent, TextContent
from mcp.types import Tool as MCPTool
from litellm.proxy._experimental.mcp_server.auth.litellm_auth_handler import (
@@ -185,7 +184,7 @@ if MCP_AVAILABLE:
@server.call_tool()
async def mcp_server_tool_call(
name: str, arguments: Dict[str, Any] | None
- ) -> List[Union[MCPTextContent, MCPImageContent, MCPEmbeddedResource]]:
+ ) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""
Call a specific tool with the provided arguments
@@ -333,16 +332,16 @@ if MCP_AVAILABLE:
@client
async def call_mcp_tool(
- name: str,
- arguments: Optional[Dict[str, Any]] = None,
- user_api_key_auth: Optional[UserAPIKeyAuth] = None,
- mcp_auth_header: Optional[str] = None,
- **kwargs: Any,
- ) -> List[Union[MCPTextContent, MCPImageContent, MCPEmbeddedResource]]:
+ name: str,
+ arguments: Optional[Dict[str, Any]] = None,
+ user_api_key_auth: Optional[UserAPIKeyAuth] = None,
+ mcp_auth_header: Optional[str] = None,
+ **kwargs: Any
+ ) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""
Call a specific tool with the provided arguments (handles prefixed tool names)
"""
-
+ start_time = datetime.now()
if arguments is None:
raise HTTPException(
status_code=400, detail="Request arguments are required"
@@ -367,6 +366,7 @@ if MCP_AVAILABLE:
litellm_logging_obj.model_call_details["mcp_tool_call_metadata"] = (
standard_logging_mcp_tool_call
)
+ litellm_logging_obj.model = f"MCP: {name}"
# Try managed server tool first (pass the full prefixed name)
# Primary and recommended way to use MCP servers
#########################################################
@@ -377,7 +377,7 @@ if MCP_AVAILABLE:
standard_logging_mcp_tool_call["mcp_server_cost_info"] = (
mcp_server.mcp_info or {}
).get("mcp_server_cost_info")
- return await _handle_managed_mcp_tool(
+ response = await _handle_managed_mcp_tool(
name=name, # Pass the full name (potentially prefixed)
arguments=arguments,
user_api_key_auth=user_api_key_auth,
@@ -388,7 +388,22 @@ if MCP_AVAILABLE:
#########################################################
# Deprecated: Local MCP Server Tool
#########################################################
- return await _handle_local_mcp_tool(original_tool_name, arguments)
+ else:
+ response = await _handle_local_mcp_tool(original_tool_name, arguments)
+
+ #########################################################
+ # Post MCP Tool Call Hook
+ # Allow modifying the MCP tool call response before it is returned to the user
+ #########################################################
+ if litellm_logging_obj:
+ end_time = datetime.now()
+ await litellm_logging_obj.async_post_mcp_tool_call_hook(
+ kwargs=litellm_logging_obj.model_call_details,
+ response_obj=response,
+ start_time=start_time,
+ end_time=end_time,
+ )
+ return response
def _get_standard_logging_mcp_tool_call(
name: str,
@@ -417,7 +432,7 @@ if MCP_AVAILABLE:
arguments: Dict[str, Any],
user_api_key_auth: Optional[UserAPIKeyAuth] = None,
mcp_auth_header: Optional[str] = None,
- ) -> List[Union[MCPTextContent, MCPImageContent, MCPEmbeddedResource]]:
+ ) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""Handle tool execution for managed server tools"""
call_tool_result = await global_mcp_server_manager.call_tool(
name=name,
@@ -430,7 +445,7 @@ if MCP_AVAILABLE:
async def _handle_local_mcp_tool(
name: str, arguments: Dict[str, Any]
- ) -> List[Union[MCPTextContent, MCPImageContent, MCPEmbeddedResource]]:
+ ) -> List[Union[TextContent, ImageContent, EmbeddedResource]]:
"""
Handle tool execution for local registry tools
Note: Local tools don't use prefixes, so we use the original name
@@ -441,9 +456,9 @@ if MCP_AVAILABLE:
try:
result = tool.handler(**arguments)
- return [MCPTextContent(text=str(result), type="text")]
+ return [TextContent(text=str(result), type="text")]
except Exception as e:
- return [MCPTextContent(text=f"Error: {str(e)}", type="text")]
+ return [TextContent(text=f"Error: {str(e)}", type="text")]
async def handle_streamable_http_mcp(
scope: Scope, receive: Receive, send: Send
diff --git a/litellm/types/llms/base.py b/litellm/types/llms/base.py
index 007bcc0ebb8..ec0d3ed95d6 100644
--- a/litellm/types/llms/base.py
+++ b/litellm/types/llms/base.py
@@ -1,3 +1,6 @@
+from typing import Any, Optional, Union
+
+from openai._models import BaseModel as OpenAIObject
from pydantic import BaseModel, ConfigDict
@@ -37,3 +40,38 @@ class BaseLiteLLMOpenAIResponseObject(BaseModel):
def items(self):
return self.__dict__.items()
+
+
+class HiddenParams(OpenAIObject):
+ original_response: Optional[Union[str, Any]] = None
+ model_id: Optional[str] = None # used in Router for individual deployments
+ api_base: Optional[str] = None # returns api base used for making completion call
+ _response_ms: Optional[float] = None
+ response_cost: Optional[float] = None
+
+ model_config = ConfigDict(extra="allow", protected_namespaces=())
+
+ def get(self, key, default=None):
+ # Custom .get() method to access attributes with a default value if the attribute doesn't exist
+ return getattr(self, key, default)
+
+ def __getitem__(self, key):
+ # Allow dictionary-style access to attributes
+ return getattr(self, key)
+
+ def __setitem__(self, key, value):
+ # Allow dictionary-style assignment of attributes
+ setattr(self, key, value)
+
+ def json(self, **kwargs): # type: ignore
+ try:
+ return self.model_dump() # noqa
+ except Exception:
+ # if using pydantic v1
+ return self.dict()
+
+ def model_dump(self, **kwargs):
+ # Override model_dump to include private attributes
+ data = super().model_dump(**kwargs)
+ data["_response_ms"] = self._response_ms
+ return data
\ No newline at end of file
diff --git a/litellm/types/mcp.py b/litellm/types/mcp.py
index 5f8876946b8..081bce10b69 100644
--- a/litellm/types/mcp.py
+++ b/litellm/types/mcp.py
@@ -1,9 +1,19 @@
import enum
-from typing import Dict, Literal, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel
from typing_extensions import TypedDict
+from litellm.types.llms.base import HiddenParams
+
+if TYPE_CHECKING:
+ from mcp.types import EmbeddedResource as MCPEmbeddedResource
+ from mcp.types import ImageContent as MCPImageContent
+ from mcp.types import TextContent as MCPTextContent
+else:
+ MCPEmbeddedResource = Any
+ MCPImageContent = Any
+ MCPTextContent = Any
class MCPTransport(str, enum.Enum):
sse = "sse"
@@ -39,4 +49,12 @@ class MCPServerCostInfo(TypedDict, total=False):
tool_name_to_cost_per_query: Optional[Dict[str, float]]
"""
Granular, set a custom cost for each tool in the MCP server
- """
\ No newline at end of file
+ """
+
+
+class MCPPostCallResponseObject(BaseModel):
+ """
+ Pydantic object used for MCP post_call_hook response
+ """
+ mcp_tool_call_response: List[Union[MCPTextContent, MCPImageContent, MCPEmbeddedResource]]
+ hidden_params: HiddenParams
\ No newline at end of file
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index 70b6c97a051..f16e3aac58c 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -41,6 +41,7 @@ from litellm.types.mcp import MCPServerCostInfo
from ..litellm_core_utils.core_helpers import map_finish_reason
from .guardrails import GuardrailEventHooks
+from .llms.base import HiddenParams
from .llms.openai import (
Batch,
ChatCompletionAnnotation,
@@ -473,40 +474,6 @@ class ChatCompletionDeltaToolCall(OpenAIObject):
setattr(self, key, value)
-class HiddenParams(OpenAIObject):
- original_response: Optional[Union[str, Any]] = None
- model_id: Optional[str] = None # used in Router for individual deployments
- api_base: Optional[str] = None # returns api base used for making completion call
- _response_ms: Optional[float] = None
-
- model_config = ConfigDict(extra="allow", protected_namespaces=())
-
- def get(self, key, default=None):
- # Custom .get() method to access attributes with a default value if the attribute doesn't exist
- return getattr(self, key, default)
-
- def __getitem__(self, key):
- # Allow dictionary-style access to attributes
- return getattr(self, key)
-
- def __setitem__(self, key, value):
- # Allow dictionary-style assignment of attributes
- setattr(self, key, value)
-
- def json(self, **kwargs): # type: ignore
- try:
- return self.model_dump() # noqa
- except Exception:
- # if using pydantic v1
- return self.dict()
-
- def model_dump(self, **kwargs):
- # Override model_dump to include private attributes
- data = super().model_dump(**kwargs)
- data["_response_ms"] = self._response_ms
- return data
-
-
class ChatCompletionMessageToolCall(OpenAIObject):
def __init__(
self,
diff --git a/tests/mcp_tests/test_mcp_logging.py b/tests/mcp_tests/test_mcp_logging.py
index 6fed5628072..7049a773450 100644
--- a/tests/mcp_tests/test_mcp_logging.py
+++ b/tests/mcp_tests/test_mcp_logging.py
@@ -3,6 +3,7 @@ import sys
import pytest
import asyncio
import json
+from typing import Optional
from unittest.mock import AsyncMock, patch
@@ -18,6 +19,8 @@ from litellm.proxy._experimental.mcp_server.server import (
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
MCPServerManager,
)
+from litellm.types.mcp import MCPPostCallResponseObject
+from litellm.types.utils import HiddenParams
from mcp.types import Tool as MCPTool, CallToolResult, TextContent
@@ -30,7 +33,7 @@ class TestMCPLogger(CustomLogger):
print("success event")
self.standard_logging_payload = kwargs.get("standard_logging_object", None)
print(f"Captured standard_logging_payload: {self.standard_logging_payload}")
-
+
@pytest.mark.asyncio
async def test_mcp_cost_tracking():
@@ -89,9 +92,13 @@ async def test_mcp_cost_tracking():
print("tool_name_to_mcp_server_name_mapping", local_mcp_server_manager.tool_name_to_mcp_server_name_mapping)
+ # Manually add the tool mapping to ensure it's available (since mocking might not capture it properly)
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["add_tools"] = "zapier_gmail_server"
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["zapier_gmail_server-add_tools"] = "zapier_gmail_server"
+
# Call mcp tool
response = await mcp_server_tool_call(
- name="zapier_gmail_server/add_tools", # Use prefixed name
+ name="zapier_gmail_server-add_tools", # Use correct prefixed name with - separator
arguments={
"test": "test"
}
@@ -148,6 +155,7 @@ async def test_mcp_cost_tracking_per_tool():
])
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=None)
+ mock_client.disconnect = AsyncMock(return_value=None)
# Mock the MCPClient constructor
def mock_client_constructor(*args, **kwargs):
@@ -182,6 +190,12 @@ async def test_mcp_cost_tracking_per_tool():
# Initialize the tool mapping
await local_mcp_server_manager._initialize_tool_name_to_mcp_server_name_mapping()
+ # Manually add the tool mapping to ensure it's available (since mocking might not capture it properly)
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["expensive_tool"] = "test_server"
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["test_server-expensive_tool"] = "test_server"
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["cheap_tool"] = "test_server"
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["test_server-cheap_tool"] = "test_server"
+
# Patch the global manager in both modules where it's used
with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager', local_mcp_server_manager), \
patch('litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager', local_mcp_server_manager):
@@ -190,7 +204,7 @@ async def test_mcp_cost_tracking_per_tool():
# Test 1: Call expensive_tool - should cost 5.0
response1 = await mcp_server_tool_call(
- name="test_server/expensive_tool", # Use prefixed name
+ name="test_server-expensive_tool", # Use correct prefixed name with - separator
arguments={
"data": "test_expensive"
}
@@ -211,7 +225,7 @@ async def test_mcp_cost_tracking_per_tool():
# Test 2: Call cheap_tool - should cost 0.1
response2 = await mcp_server_tool_call(
- name="test_server/cheap_tool", # Use prefixed name
+ name="test_server-cheap_tool", # Use correct prefixed name with - separator
arguments={
"data": "test_cheap"
}
@@ -242,4 +256,99 @@ async def test_mcp_cost_tracking_per_tool():
assert response_list_2[0].text == "Test response"
# Verify client methods were called twice
- assert mock_client.call_tool.call_count == 2
\ No newline at end of file
+ assert mock_client.call_tool.call_count == 2
+
+
+
+
+class MCPLoggerHook(CustomLogger):
+ def __init__(self):
+ self.standard_logging_payload = None
+ super().__init__()
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ print("success event")
+ self.standard_logging_payload = kwargs.get("standard_logging_object", None)
+ print(f"Captured standard_logging_payload: {self.standard_logging_payload}")
+
+ async def async_post_mcp_tool_call_hook(self, kwargs, response_obj: MCPPostCallResponseObject, start_time, end_time) -> Optional[MCPPostCallResponseObject]:
+ print("post mcp tool call response_obj", response_obj)
+ # update the MCPPostCallResponseObject with the response_cost
+ response_obj.hidden_params.response_cost = 1.42
+ return response_obj
+
+
+async def test_mcp_tool_call_hook():
+ # Create a mock tool call result
+ litellm.logging_callback_manager._reset_all_callbacks()
+ mock_result = CallToolResult(
+ content=[TextContent(type="text", text="Test response")],
+ isError=False
+ )
+
+ # Create a mock MCPClient
+ mock_client = AsyncMock()
+ mock_client.call_tool = AsyncMock(return_value=mock_result)
+ mock_client.list_tools = AsyncMock(return_value=[
+ MCPTool(
+ name="add_tools",
+ description="Test tool",
+ inputSchema={"type": "object", "properties": {"test": {"type": "string"}}}
+ )
+ ])
+ mock_client.__aenter__ = AsyncMock(return_value=mock_client)
+ mock_client.__aexit__ = AsyncMock(return_value=None)
+ mock_client.disconnect = AsyncMock(return_value=None)
+
+ # Mock the MCPClient constructor
+ def mock_client_constructor(*args, **kwargs):
+ return mock_client
+
+ # Initialize the server manager
+ local_mcp_server_manager = MCPServerManager()
+
+ with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient', mock_client_constructor):
+ # Load the server config
+ local_mcp_server_manager.load_servers_from_config(
+ mcp_servers_config={
+ "zapier_gmail_server": {
+ "url": os.getenv("ZAPIER_MCP_HTTPS_SERVER_URL"),
+ }
+ }
+ )
+
+ # Set up the test logger
+ test_logger = MCPLoggerHook()
+ litellm.callbacks = [test_logger]
+
+ # Initialize the tool mapping
+ await local_mcp_server_manager._initialize_tool_name_to_mcp_server_name_mapping()
+
+ # Manually add the tool mapping to ensure it's available (since mocking might not capture it properly)
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["add_tools"] = "zapier_gmail_server"
+ local_mcp_server_manager.tool_name_to_mcp_server_name_mapping["zapier_gmail_server-add_tools"] = "zapier_gmail_server"
+
+ # Patch the global manager in both modules where it's used
+ with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.global_mcp_server_manager', local_mcp_server_manager), \
+ patch('litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager', local_mcp_server_manager):
+
+ print("tool_name_to_mcp_server_name_mapping", local_mcp_server_manager.tool_name_to_mcp_server_name_mapping)
+
+ # Call mcp tool using the correct separator format (- not /)
+ response = await mcp_server_tool_call(
+ name="zapier_gmail_server-add_tools", # Use correct prefixed name with - separator
+ arguments={
+ "test": "test"
+ }
+ )
+
+ # wait 1-2 seconds for logging to be processed
+ await asyncio.sleep(2)
+
+
+ # check logged standard logging payload
+ logged_standard_logging_payload = test_logger.standard_logging_payload
+ print("logged_standard_logging_payload", json.dumps(logged_standard_logging_payload, indent=4))
+ assert logged_standard_logging_payload is not None, "Standard logging payload should not be None"
+ assert logged_standard_logging_payload["response_cost"] == 1.42
\ No newline at end of file
diff --git a/tests/mcp_tests/test_mcp_server.py b/tests/mcp_tests/test_mcp_server.py
index e36e1267a46..4963dfff2d6 100644
--- a/tests/mcp_tests/test_mcp_server.py
+++ b/tests/mcp_tests/test_mcp_server.py
@@ -90,10 +90,10 @@ async def test_mcp_server_manager_https_server():
# Verify tools were returned and properly prefixed
assert len(tools) == 1
- assert tools[0].name == "zapier_mcp_server/gmail_send_email"
+ assert tools[0].name == "zapier_mcp_server-gmail_send_email"
result = await mcp_server_manager.call_tool(
- name="zapier_mcp_server/gmail_send_email",
+ name="zapier_mcp_server-gmail_send_email",
arguments={
"body": "Test",
"message": "Test",
@@ -177,16 +177,16 @@ async def test_mcp_http_transport_list_tools_mock():
# Assertions
assert len(tools) == 2
- assert tools[0].name == "test_http_server/gmail_send_email"
- assert tools[1].name == "test_http_server/calendar_create_event"
+ assert tools[0].name == "test_http_server-gmail_send_email"
+ assert tools[1].name == "test_http_server-calendar_create_event"
# Verify client methods were called
mock_client.__aenter__.assert_called()
mock_client.list_tools.assert_called_once()
# Verify tool mapping was updated
- assert test_manager.tool_name_to_mcp_server_name_mapping["test_http_server/gmail_send_email"] == "test_http_server"
- assert test_manager.tool_name_to_mcp_server_name_mapping["test_http_server/calendar_create_event"] == "test_http_server"
+ assert test_manager.tool_name_to_mcp_server_name_mapping["test_http_server-gmail_send_email"] == "test_http_server"
+ assert test_manager.tool_name_to_mcp_server_name_mapping["test_http_server-calendar_create_event"] == "test_http_server"
@pytest.mark.asyncio
@@ -640,7 +640,7 @@ async def test_list_tools_rest_api_success():
assert isinstance(response, dict)
assert len(response["tools"]) == 1
- assert response["tools"][0].name == "test_server/test_tool"
+ assert response["tools"][0].name == "test_server-test_tool"
finally:
# Restore original state
global_mcp_server_manager.registry = {}