Spaces:
Configuration error
Configuration error
File size: 11,282 Bytes
447ebeb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 |
# Create server parameters for stdio connection
import os
import sys
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from contextlib import asynccontextmanager
sys.path.insert(
0, os.path.abspath("../../..")
) # Adds the parent directory to the system path
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
MCPServerManager,
MCPServer,
MCPTransport,
)
from mcp.types import Tool as MCPTool, CallToolResult, ListToolsResult
from mcp.types import TextContent
mcp_server_manager = MCPServerManager()
@pytest.mark.asyncio
@pytest.mark.skip(reason="Local only test")
async def test_mcp_server_manager():
mcp_server_manager.load_servers_from_config(
{
"zapier_mcp_server": {
"url": os.environ.get("ZAPIER_MCP_SERVER_URL"),
}
}
)
tools = await mcp_server_manager.list_tools()
print("TOOLS FROM MCP SERVER MANAGER== ", tools)
result = await mcp_server_manager.call_tool(
name="gmail_send_email", arguments={"body": "Test"}
)
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
@pytest.mark.asyncio
async def test_mcp_server_manager_https_server():
mcp_server_manager.load_servers_from_config(
{
"zapier_mcp_server": {
"url": os.environ.get("ZAPIER_MCP_HTTPS_SERVER_URL"),
"transport": MCPTransport.http,
}
}
)
tools = await mcp_server_manager.list_tools()
print("TOOLS FROM MCP SERVER MANAGER== ", tools)
result = await mcp_server_manager.call_tool(
name="gmail_send_email",
arguments={
"body": "Test",
"message": "Test",
"instructions": "Test",
},
)
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
@pytest.mark.asyncio
async def test_mcp_http_transport_list_tools_mock():
"""Test HTTP transport list_tools functionality with mocked dependencies"""
# Create a fresh manager for testing
test_manager = MCPServerManager()
# Mock tools that should be returned
mock_tools = [
MCPTool(
name="gmail_send_email",
description="Send an email via Gmail",
inputSchema={
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"}
},
"required": ["to", "subject", "body"]
}
),
MCPTool(
name="calendar_create_event",
description="Create a calendar event",
inputSchema={
"type": "object",
"properties": {
"title": {"type": "string"},
"date": {"type": "string"},
"time": {"type": "string"}
},
"required": ["title", "date"]
}
)
]
# Mock the session and its methods
mock_session = AsyncMock()
mock_session.initialize = AsyncMock()
mock_session.list_tools = AsyncMock(return_value=ListToolsResult(tools=mock_tools))
# Create an async context manager mock for streamablehttp_client
@asynccontextmanager
async def mock_streamablehttp_client(url):
read_stream = AsyncMock()
write_stream = AsyncMock()
get_session_id = MagicMock(return_value="test-session-123")
yield (read_stream, write_stream, get_session_id)
# Create an async context manager mock for ClientSession
@asynccontextmanager
async def mock_client_session(read_stream, write_stream):
yield mock_session
with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.streamablehttp_client', mock_streamablehttp_client), \
patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.ClientSession', mock_client_session):
# Load server config with HTTP transport
test_manager.load_servers_from_config({
"test_http_server": {
"url": "https://test-mcp-server.com/mcp",
"transport": MCPTransport.http,
"description": "Test HTTP MCP Server"
}
})
# Call list_tools
tools = await test_manager.list_tools()
# Assertions
assert len(tools) == 2
assert tools[0].name == "gmail_send_email"
assert tools[1].name == "calendar_create_event"
# Verify session methods were called
mock_session.initialize.assert_called_once()
mock_session.list_tools.assert_called_once()
# Verify tool mapping was updated
assert test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] == "test_http_server"
assert test_manager.tool_name_to_mcp_server_name_mapping["calendar_create_event"] == "test_http_server"
@pytest.mark.asyncio
async def test_mcp_http_transport_call_tool_mock():
"""Test HTTP transport call_tool functionality with mocked dependencies"""
# Create a fresh manager for testing
test_manager = MCPServerManager()
# Mock tool call result
mock_result = CallToolResult(
content=[
TextContent(
type="text",
text="Email sent successfully to [email protected]"
)
],
isError=False
)
# Mock the session and its methods
mock_session = AsyncMock()
mock_session.initialize = AsyncMock()
mock_session.call_tool = AsyncMock(return_value=mock_result)
# Create an async context manager mock for streamablehttp_client
@asynccontextmanager
async def mock_streamablehttp_client(url):
read_stream = AsyncMock()
write_stream = AsyncMock()
get_session_id = MagicMock(return_value="test-session-456")
yield (read_stream, write_stream, get_session_id)
# Create an async context manager mock for ClientSession
@asynccontextmanager
async def mock_client_session(read_stream, write_stream):
yield mock_session
with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.streamablehttp_client', mock_streamablehttp_client), \
patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.ClientSession', mock_client_session):
# Load server config with HTTP transport
test_manager.load_servers_from_config({
"test_http_server": {
"url": "https://test-mcp-server.com/mcp",
"transport": MCPTransport.http,
"description": "Test HTTP MCP Server"
}
})
# Manually set up tool mapping (normally done by list_tools)
test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = "test_http_server"
# Call the tool
result = await test_manager.call_tool(
name="gmail_send_email",
arguments={
"to": "[email protected]",
"subject": "Test Subject",
"body": "Test email body"
}
)
# Assertions
assert result.isError is False
assert len(result.content) == 1
# Type check before accessing text attribute
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "Email sent successfully to [email protected]"
# Verify session methods were called
mock_session.initialize.assert_called_once()
mock_session.call_tool.assert_called_once_with(
"gmail_send_email",
{
"to": "[email protected]",
"subject": "Test Subject",
"body": "Test email body"
}
)
@pytest.mark.asyncio
async def test_mcp_http_transport_call_tool_error_mock():
"""Test HTTP transport call_tool error handling with mocked dependencies"""
# Create a fresh manager for testing
test_manager = MCPServerManager()
# Mock tool call error result
mock_error_result = CallToolResult(
content=[
TextContent(
type="text",
text="Error: Invalid email address"
)
],
isError=True
)
# Mock the session and its methods
mock_session = AsyncMock()
mock_session.initialize = AsyncMock()
mock_session.call_tool = AsyncMock(return_value=mock_error_result)
# Create an async context manager mock for streamablehttp_client
@asynccontextmanager
async def mock_streamablehttp_client(url):
read_stream = AsyncMock()
write_stream = AsyncMock()
get_session_id = MagicMock(return_value="test-session-789")
yield (read_stream, write_stream, get_session_id)
# Create an async context manager mock for ClientSession
@asynccontextmanager
async def mock_client_session(read_stream, write_stream):
yield mock_session
with patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.streamablehttp_client', mock_streamablehttp_client), \
patch('litellm.proxy._experimental.mcp_server.mcp_server_manager.ClientSession', mock_client_session):
# Load server config with HTTP transport
test_manager.load_servers_from_config({
"test_http_server": {
"url": "https://test-mcp-server.com/mcp",
"transport": MCPTransport.http,
"description": "Test HTTP MCP Server"
}
})
# Manually set up tool mapping
test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = "test_http_server"
# Call the tool with invalid data
result = await test_manager.call_tool(
name="gmail_send_email",
arguments={"to": "invalid-email", "subject": "Test", "body": "Test"}
)
# Assertions for error case
assert result.isError is True
assert len(result.content) == 1
# Type check before accessing text attribute
assert isinstance(result.content[0], TextContent)
assert "Error: Invalid email address" in result.content[0].text
# Verify session methods were called
mock_session.initialize.assert_called_once()
mock_session.call_tool.assert_called_once()
@pytest.mark.asyncio
async def test_mcp_http_transport_tool_not_found():
"""Test calling a tool that doesn't exist"""
# Create a fresh manager for testing
test_manager = MCPServerManager()
# Load server config
test_manager.load_servers_from_config({
"test_http_server": {
"url": "https://test-mcp-server.com/mcp",
"transport": MCPTransport.http,
"description": "Test HTTP MCP Server"
}
})
# Try to call a tool that doesn't exist in mapping
with pytest.raises(ValueError, match="Tool nonexistent_tool not found"):
await test_manager.call_tool(
name="nonexistent_tool",
arguments={"param": "value"}
)
|