mirror of
https://github.com/BerriAI/litellm.git
synced 2026-09-13 23:11:40 +00:00
* fix(anthropic): support Bearer auth for custom api_base endpoints (Fixes #30926) * style: format common_utils.py with black * fix(anthropic): extract api_base from litellm_params in batches/files validate_environment * fix(anthropic): scope Bearer key check to custom api_base endpoints * fix(streaming): reset Anthropic message_start cursor (output_tokens=1) when no message_delta arrives The Anthropic streaming protocol emits `message_start.usage.output_tokens=1` as a placeholder cursor; the real cumulative output count only arrives in the final `message_delta` event. When a stream is cancelled before `message_delta` lands (common for thinking models on long-tail prompts), ChunkProcessor._calculate_usage_per_chunk's last-wins accumulator left completion_tokens stuck at 1. Because 1 is truthy, the `completion_tokens or token_counter(text=...)` fallback in calculate_usage() never fired, and requests were billed for 1 output token even when several thousand tokens of text had actually streamed. Fix: track whether any chunk's completion_tokens exceeded 1 (saw_non_cursor_completion). If the only update we saw was the cursor, reset completion_tokens to 0 so the text-based fallback estimates from the real completion content. Legitimate 1-token completions (model returns "Yes." etc.) are unaffected in practice — token_counter on a 1-token completion_output also yields ~1, so billing stays approximately correct. Tests: - TestAnthropicCursorBug (6 cases) — pins the post-fix behavior - TestNonAnthropicStreamingIntact (2 cases) — guards against regression on providers without the cursor pattern All 8 new tests pass; 9 existing streaming_chunk_builder_utils tests still pass. * fix(streaming): scope cursor reset to anthropic provider + recognize message_delta arrival Addresses both Greptile P2 threads on PR #30420: CLASS A — Anthropic-specific heuristic was applied globally ============================================================ The `completion_tokens == 1 and not saw_non_cursor_completion` reset lived in provider-neutral `streaming_chunk_builder_utils.py`. Any non-Anthropic provider that legitimately reports completion_tokens=1 in a single usage chunk (perfectly normal for short OpenAI / Bedrock / Vertex single-token replies with stream_options.include_usage=true) would have its value silently rewritten to 0 and re-billed via token_counter — producing a different number than what the provider actually charged. Fix: gate the reset on `custom_llm_provider == "anthropic"`, resolved from the first chunk's `_hidden_params` (the same field set by streaming_handler.py:722 on the live path). Unknown / missing provider is treated as non-Anthropic and skips the reset, so newer providers and custom plugins are also safe by default. CLASS B — `saw_non_cursor_completion` missed legitimate single-token replies ============================================================ Previous condition was `usage_chunk_dict["completion_tokens"] > 1`, which never fires for an Anthropic stream where the model legitimately emits exactly one output token (e.g., "Yes."). Anthropic still sends message_start (output_tokens=1, the cursor) AND message_delta (output_tokens=1, the real value) — same value, but two distinct usage events. The old check couldn't tell that apart from a cancelled stream where only message_start landed. Fix: track `completion_usage_updates` and flip `saw_non_cursor_completion` when EITHER (1) the value exceeds 1 (definitely not a placeholder), OR (2) we've seen >=2 completion-bearing usage events (positive evidence that message_delta arrived). Cancelled cursor-only streams still have exactly one event and still hit the reset; cache chunks with completion_tokens=0 don't count toward the threshold. Tests ============================================================ - _make_chunk now sets `_hidden_params["custom_llm_provider"]` (default "anthropic") so the gate is exercised by every existing test — none of them needed assertion changes besides the legitimate-single- token case, which now expects exactly 1 (was a fuzzy 0..3 range). - New: test_anthropic_cache_only_chunks_after_message_start_still_resets - New: test_non_anthropic_provider_completion_tokens_one_not_reset - New: test_unknown_provider_completion_tokens_one_not_reset 11/11 tests pass. * chore: add Co-authored-by trailer for attribution Co-authored-by: songkuan-zheng <songkuan-zheng@users.noreply.github.com> * fix(anthropic): preserve messages cache usage * style(anthropic): format messages cache usage helper * fix(anthropic): accept integral float cache token counts Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * fix(anthropic): accept integral float cache token counts * test(anthropic): cover cache usage edge cases * fix(gemini): preserve thoughtSignature for server-side tool responses When Gemini API returns toolCall and toolResponse parts, they might have different thoughtSignatures. Previously, LiteLLM merged them into a single dict, overwriting the response's thoughtSignature with the call's. This fix extracts them separately and re-injects them correctly. TAG=agy CONV=755b21d0-3200-40bc-bd1a-bb58a378a9a6 * fix(gemini): address PR comments on thoughtSignature handling - Fix orphan-response thoughtSignature regression by copying thought_signature to response_thought_signature - Add missing assertions in existing tests - Add new unit tests for orphan-response signature handling TAG=agy CONV=755b21d0-3200-40bc-bd1a-bb58a378a9a6 * feat(mcp): include server alias and server_id in mcp_info response - Add alias and server_id fields to mcp_info object in /mcp-rest/tools/list endpoint - Update rest_endpoints.py to surface alias from server config - Add test coverage in test_mcp_server.py and test_rest_endpoints.py Fixes #31015 * fix(proxy): reject non-finite spend via validate_finite_spend A NaN/-inf spend would bypass spend >= max_budget enforcement. Add a shared finite-value guard, defined above the litellm.proxy.* imports to avoid the module-level cyclic-import warning. * fix(proxy): require admin for any /key/update spend, reject non-finite Gate the admin check on the presence of `spend` (not a value diff): the DB spend lags the live cross-pod counter, so an "unchanged" spend on the non-admin path let a key owner / team member overwrite the live counter below real usage. Also reject NaN/+-inf spend before the DB write. * fix(proxy): invalidate spend counter on /user/update spend change A direct spend change on /user/update wrote the DB row but left the warm cross-pod counter at the stale value, so enforcement kept reading the old spend. Invalidate spend:user:{user_id} after the write (reseed-from-DB), and reject non-finite spend before the write. * fix(cache): route Bedrock semantic-cache sync embedding through the Router (#28244) The semantic cache's embedding model is a proxy Router alias whose AWS credentials (aws_role_name, aws_session_name) live only in the Router deployment's litellm_params. The sync embedding paths called litellm.embedding() directly, bypassing the Router, so they could neither resolve the alias nor assume the configured role; cross-account Bedrock semantic caching failed with "bedrock:InvokeModel is not authorized". On Redis this surfaced at proxy startup because redisvl's CustomTextVectorizer eagerly fires a dimension-probe embedding during cache construction, while llm_router is still None. Fix A: make the sync paths mirror the already-correct async paths. A shared, dependency-injected helper (litellm/caching/_embedding_router.py) decides whether to route through llm_router.embedding(...) when the model is a Router deployment, else fall back to direct litellm.embedding(...). Redis and qdrant sync set_cache/get_cache now precompute the embedding and pass vector= to the backend, exactly as the async astore/acheck already do. Both async _get_async_embedding methods are unified onto the same helper and now forward the caller's full metadata instead of a hand-picked subset. Fix B (Redis only): defer redisvl index construction from __init__ into a lazy, memoized llmcache property, so the dimension-probe embedding fires on first cache use, after llm_router is wired. A failed build is not memoized, so a transient outage recovers on the next request. Known limitation: resolve_embedding_router gates on an exact model-name match (same as the shipped async path); wildcard/alias/team-public routes still fall back to direct embedding. Tracked as a follow-up. * fix(cache): harden embedding-router and shrink Any surface (review) Address review feedback on the semantic-cache aws-role fix (#28244): - resolve_embedding_router now skips deployment entries missing model_name instead of raising KeyError on a malformed model_list (Greptile P2); add a regression test that fails on the old direct-key access. - Replace the `**kwargs: Any` passthrough on the four cache _get_embedding / _get_async_embedding helpers with an explicit, typed `metadata: Optional[Dict[str, Any]] = None` parameter. The helpers only ever consumed kwargs["metadata"], so this is behavior-preserving, makes the forwarded field obvious at the call site, and removes three bare-Any annotations (keeps the strict-rule ANN401 budget within ceiling). - Note in _build_llmcache that redisvl's dimension-probe embedding adds one extra billable embedding on the first cache request (Greptile P2). * fix(bedrock_mantle): correct responses routing for openai.gpt-5.x models Dashboard Test Connection for bedrock_mantle/openai.gpt-5.4 and openai.gpt-5.5 was failing with maximum recursion depth errors and "model does not exist" Route detection in the bedrock provider matched route tokens by plain substring, so the bedrock_mantle/ prefix was mistaken for the mantle/ invoke route and the body model was rewritten to bedrock_openai.gpt-5.5; route tokens now only match at a path-segment boundary so the bare model name is preserved A responses-mode model whose provider has no responses config bounced forever between the responses API and chat completions; the responses to completion fallback now tags its call so completion() does not bridge back, breaking the loop The Test Connection endpoint hardcoded the test mode to chat, which disabled mode auto-detection for responses-only models; the default is now None so the mode is detected from model capabilities acompletion() now drops a duplicate acompletion kwarg before building the partial and treats model_info=None as an empty dict to avoid a NoneType crash * test(bedrock_mantle): cover route guard and bridge flag; fix reportArgumentType regression Adds the regression coverage codecov flagged on the two responses to completion bridge guard lines and the bedrock route-prefix helper. The handler tests drive both the sync and async fallback paths with litellm.completion and litellm.acompletion mocked, and assert the forwarded kwargs carry _skip_responses_api_bridge=True, so dropping either flag line fails the suite. The common_utils tests assert that bedrock_mantle/openai.gpt-5.x no longer resolves to the mantle route while the genuine mantle/ and bedrock/mantle/ ids still do, exercising both branches of _model_has_route_prefix. Also aligns update_messages_with_model_file_ids model_id to Optional[str], matching its Responses API sibling, so the defensive model_info fallback no longer introduces a new reportArgumentType in completion(); the file-id lookup narrows model_id before the dict get * chore(ui): sync generated OpenAPI types for optional test_connection mode The test_model_connection mode body param default changed from chat to None so the mode is auto-detected from model capabilities, which makes the field optional in the proxy OpenAPI spec. Regenerate the committed schema so the dashboard types match: mode becomes optional and the description and default JSDoc follow the spec, keeping the Check UI API Types Sync gate green * refactor(bedrock): match all explicit route prefixes at path-segment boundary Migrates the remaining substring route checks to the existing _model_has_route_prefix helper so every explicit route token matches only as a leading path segment, consistent with get_bedrock_route and the mantle route. Covers _explicit_converse_route, _explicit_claude_platform_route, _explicit_invoke_route, _explicit_agent_route, _explicit_agentcore_route, _explicit_converse_like_route, _explicit_async_invoke_route and _explicit_openai_route. This also stops invoke/ from substring-matching async_invoke/. Route precedence and order are unchanged, and a note on the segment invariant is added to the helper docstring * test(bedrock): cover explicit route prefix segment matching Exercises all eight migrated _explicit_*_route helpers (converse, converse_like, invoke, async_invoke, agent, agentcore, claude_platform, openai) directly: each matches its token as a leading path segment and rejects the token glued to a preceding segment, so reverting any method to the old substring check fails the suite. Also asserts invoke/ no longer matches async_invoke/ models, the concrete improvement of the segment-boundary migration * test(proxy): assert negative spend is allowed (one-time grant use-case) Negative spend is intentionally permitted so admins can grant extra allowance for the current budget period only, without raising the recurring budget ceiling. Cover it explicitly in validate_finite_spend and via the /user/update invalidation test. * fix(google_genai): forward native generateContent top-level fields Google's native generateContent REST body carries safetySettings, toolConfig, cachedContent and labels at the top level as siblings of generationConfig. The proxy's :generateContent endpoint spread them into agenerate_content as loose kwargs and then dropped them, so callers had to wrap them in extra_body for them to take effect; safetySettings, for instance, was silently ignored The provider config now exposes the native top-level field names and setup_generate_content_call collects whichever are present, merging them into the outgoing request body through the existing extra_body merge so they reach Google verbatim. An explicit extra_body still wins on conflict. The sync generate_content_stream path now also forwards systemInstruction, matching the other three entry points Fixes #12671 Claude-Session: https://claude.ai/code/session_016MFtMXokCjT8u6mvyASudK * fix(proxy): resolve env refs for DB-stored models * fix(proxy): restrict DB env ref resolution * fix(proxy): block team DB env ref resolution * fix(lint): resolve ANN401/UP045/C901 strict-gate violations - Replace Optional[X] with X | None (UP045) in 8 files - Replace Any return/param types with concrete types or object (ANN401) - Extract _make_api_key_auth_header helper to reduce get_anthropic_headers complexity below C901 threshold (17 → 14) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(anthropic): preserve x-api-key for custom endpoints; opt-in Bearer via prefix Users who pass a key already prefixed with "Bearer " get Authorization: Bearer. All other keys continue to use x-api-key, preserving backward compatibility with custom api_base endpoints that expect x-api-key rather than Authorization. Also consolidates get_auth_header to reuse _make_api_key_auth_header helper, eliminating the duplicated custom-endpoint routing logic. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * revert(anthropic): restore Bearer routing for non-sk-ant- keys on custom api_base The backwards-compat change broke existing tests that verify the intentional Bearer-for-custom-base behavior (Fixes #30926). Restore original logic while keeping the _make_api_key_auth_header helper for code deduplication. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(anthropic): gate Bearer-for-custom-base behind use_bearer_for_custom_base flag Previously the auth-header switch from x-api-key to Authorization: Bearer applied unconditionally for non-sk-ant- keys on a custom api_base, silently breaking existing deployments that proxied to gateways expecting x-api-key. Introduce use_bearer_for_custom_base: bool = False on _make_api_key_auth_header, get_anthropic_headers, and get_auth_header. validate_environment reads it from litellm_params so callers can opt in per-model without any API surface change. Tests updated to pass use_bearer_for_custom_base=True where Bearer behavior is asserted. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix(redis): apply namespace prefix in delete_cache and async_delete_cache (#29981) DEL was the only Redis cache operation that skipped check_and_fix_namespace, so it targeted the raw SHA256 hash (e.g. 3997c4...) rather than the namespaced key (litellm:3997c4...). This caused two problems: a Redis NOPERM error on deployments with an ACL restricting DEL to the litellm:* pattern, and a silent no-op on all other deployments since the un-prefixed key was never stored. * style(anthropic): reformat common_utils.py with Black (--target-version py312) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: preserve cache metadata and spend counters * style: apply ruff format to streaming_iterator.py * refactor: reduce complexity of usage/spend helpers to satisfy strict ruff gate Extract Anthropic message_start cursor reset into _reset_anthropic_cursor_completion_tokens and the cross-pod spend-counter invalidation into _invalidate_user_spend_counter_if_changed, keeping both _calculate_usage_per_chunk and _update_single_user_helper under the max-complexity ceiling. Use builtin generics in the new signatures so no new UP006 violations are introduced. Behavior unchanged. --------- Co-authored-by: rupak-eng <rupakji99@gmail.com> Co-authored-by: songkuan-zheng <252822057+songkuan-zheng@users.noreply.github.com> Co-authored-by: songkuan-zheng <songkuan-zheng@users.noreply.github.com> Co-authored-by: Kannan Priyadharshan <kpd2204@gmail.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Co-authored-by: Marco Georgaklis <mgeorgaklis@google.com> Co-authored-by: Anjaiah Methuku <anjaiahspr@gmail.com> Co-authored-by: Andrii Butko <booandrew23@gmail.com> Co-authored-by: Kent <kingdooo@gmail.com> Co-authored-by: kunal2002 <k.nayyar2002@gmail.com> Co-authored-by: Ali Khan <alirazakhan.offi@gmail.com> Co-authored-by: jesco-absolut <team@srswti.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: Matt Hill <mhill@dataminr.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com>
3001 lines
108 KiB
Python
3001 lines
108 KiB
Python
# 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 litellm.proxy._types import LiteLLM_ObjectPermissionTable
|
|
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():
|
|
await 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"}, proxy_logging_obj=None
|
|
)
|
|
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_https_server():
|
|
# Create mock tools and results
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="gmail_send_email",
|
|
description="Send an email via Gmail",
|
|
inputSchema={
|
|
"type": "object",
|
|
"properties": {
|
|
"body": {"type": "string"},
|
|
"message": {"type": "string"},
|
|
"instructions": {"type": "string"},
|
|
},
|
|
"required": ["body"],
|
|
},
|
|
)
|
|
]
|
|
|
|
mock_result = CallToolResult(
|
|
content=[TextContent(type="text", text="Email sent successfully")],
|
|
isError=False,
|
|
)
|
|
|
|
# Create a mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.call_tool = AsyncMock(return_value=mock_result)
|
|
|
|
# Mock the MCPClient constructor
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
await mcp_server_manager.load_servers_from_config(
|
|
{
|
|
"zapier_mcp_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
}
|
|
}
|
|
)
|
|
|
|
allowed_server_ids = list(mcp_server_manager.get_registry().keys())
|
|
assert allowed_server_ids, "Expected registry to contain the configured server"
|
|
|
|
with patch.object(
|
|
mcp_server_manager,
|
|
"get_allowed_mcp_servers",
|
|
new=AsyncMock(return_value=allowed_server_ids),
|
|
):
|
|
tools = await mcp_server_manager.list_tools()
|
|
print("TOOLS FROM MCP SERVER MANAGER== ", tools)
|
|
|
|
# Verify tools were returned and properly prefixed
|
|
assert len(tools) == 1
|
|
# The server should use the server_name as prefix since no alias is provided
|
|
expected_prefix = "zapier_mcp_server"
|
|
assert tools[0].name == f"{expected_prefix}-gmail_send_email"
|
|
|
|
# Manually set up the tool mapping for the call_tool test
|
|
mcp_server_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = (
|
|
expected_prefix
|
|
)
|
|
mcp_server_manager.tool_name_to_mcp_server_name_mapping[
|
|
f"{expected_prefix}-gmail_send_email"
|
|
] = expected_prefix
|
|
|
|
result = await mcp_server_manager.call_tool(
|
|
server_name="zapier_mcp_server",
|
|
name=f"{expected_prefix}-gmail_send_email",
|
|
arguments={
|
|
"body": "Test",
|
|
"message": "Test",
|
|
"instructions": "Test",
|
|
},
|
|
proxy_logging_obj=None,
|
|
)
|
|
print("RESULT FROM CALLING TOOL FROM MCP SERVER MANAGER== ", result)
|
|
|
|
# Verify result
|
|
assert result.isError is False
|
|
assert len(result.content) == 1
|
|
assert isinstance(result.content[0], TextContent)
|
|
assert result.content[0].text == "Email sent successfully"
|
|
|
|
# Verify client methods were called
|
|
mock_client.list_tools.assert_called()
|
|
mock_client.call_tool.assert_called_once()
|
|
|
|
|
|
@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"],
|
|
},
|
|
),
|
|
]
|
|
|
|
# Create a mock MCPClient that returns our test tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
# Mock the MCPClient constructor to return our mock
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Load server config with HTTP transport
|
|
await 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
|
|
allowed_server_ids = list(test_manager.get_registry().keys())
|
|
assert allowed_server_ids, "Expected registry to contain configured server"
|
|
|
|
with patch.object(
|
|
test_manager,
|
|
"get_allowed_mcp_servers",
|
|
new=AsyncMock(return_value=allowed_server_ids),
|
|
):
|
|
tools = await test_manager.list_tools()
|
|
|
|
# Assertions
|
|
assert len(tools) == 2
|
|
# The server should use the server_name as prefix since no alias is provided
|
|
expected_prefix = "test_http_server"
|
|
assert tools[0].name == f"{expected_prefix}-gmail_send_email"
|
|
assert tools[1].name == f"{expected_prefix}-calendar_create_event"
|
|
|
|
# Verify client methods were called
|
|
mock_client.list_tools.assert_called()
|
|
|
|
# Verify tool mapping was updated
|
|
expected_prefix = "test_http_server"
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping[
|
|
f"{expected_prefix}-gmail_send_email"
|
|
]
|
|
== expected_prefix
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping[
|
|
f"{expected_prefix}-calendar_create_event"
|
|
]
|
|
== expected_prefix
|
|
)
|
|
|
|
|
|
@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 test@example.com")
|
|
],
|
|
isError=False,
|
|
)
|
|
|
|
# Create a mock MCPClient that returns our test result
|
|
mock_client = AsyncMock()
|
|
mock_client.call_tool = AsyncMock(return_value=mock_result)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
# Mock the MCPClient constructor to return our mock
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Load server config with HTTP transport
|
|
await 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(
|
|
server_name="test_http_server",
|
|
name="gmail_send_email",
|
|
arguments={
|
|
"to": "test@example.com",
|
|
"subject": "Test Subject",
|
|
"body": "Test email body",
|
|
},
|
|
proxy_logging_obj=None,
|
|
)
|
|
|
|
# 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 test@example.com"
|
|
|
|
# Verify client methods were called
|
|
mock_client.call_tool.assert_called_once()
|
|
|
|
|
|
@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,
|
|
)
|
|
|
|
# Create a mock MCPClient that returns our test error result
|
|
mock_client = AsyncMock()
|
|
mock_client.call_tool = AsyncMock(return_value=mock_error_result)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
# Mock the MCPClient constructor to return our mock
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Load server config with HTTP transport
|
|
await 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(
|
|
server_name="test_http_server",
|
|
name="gmail_send_email",
|
|
arguments={"to": "invalid-email", "subject": "Test", "body": "Test"},
|
|
proxy_logging_obj=None,
|
|
)
|
|
|
|
# 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 client methods were called
|
|
mock_client.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
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"test_http_server": {
|
|
"url": "https://test-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test HTTP MCP Server",
|
|
}
|
|
}
|
|
)
|
|
|
|
# Mapping populated for this server but not for the requested tool
|
|
test_manager.tool_name_to_mcp_server_name_mapping["gmail_send_email"] = (
|
|
"test_http_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(
|
|
server_name="test_http_server",
|
|
name="nonexistent_tool",
|
|
arguments={"param": "value"},
|
|
proxy_logging_obj=None,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_streamable_http_mcp_handler_mock():
|
|
"""Test the streamable HTTP MCP handler functionality"""
|
|
# Mock streamable HTTP session managers and their methods
|
|
mock_session_manager_stateless = AsyncMock()
|
|
mock_session_manager_stateless.handle_request = AsyncMock()
|
|
mock_session_manager_stateful = AsyncMock()
|
|
mock_session_manager_stateful.handle_request = AsyncMock()
|
|
|
|
# Mock scope, receive, send with proper ASGI scope format
|
|
mock_scope = {
|
|
"type": "http",
|
|
"method": "POST",
|
|
"path": "/mcp",
|
|
"headers": [(b"content-type", b"application/json")],
|
|
"query_string": b"",
|
|
"server": ("localhost", 8000),
|
|
"scheme": "http",
|
|
}
|
|
mock_receive = AsyncMock(return_value={"body": b"{}", "more_body": False})
|
|
mock_send = AsyncMock()
|
|
|
|
# Mock extract_mcp_auth_context to bypass auth checks in the handler
|
|
mock_auth_context = (None, None, None, {}, {}, {})
|
|
|
|
with (
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
|
|
True,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.session_manager_stateless",
|
|
mock_session_manager_stateless,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.session_manager_stateful",
|
|
mock_session_manager_stateful,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",
|
|
AsyncMock(return_value=mock_auth_context),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.set_auth_context",
|
|
),
|
|
):
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
handle_streamable_http_mcp,
|
|
)
|
|
|
|
# Call the handler
|
|
await handle_streamable_http_mcp(mock_scope, mock_receive, mock_send)
|
|
|
|
# Verify stateless session manager handle_request was called
|
|
mock_session_manager_stateless.handle_request.assert_called_once()
|
|
mock_session_manager_stateful.handle_request.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sse_mcp_handler_mock():
|
|
"""Test the SSE MCP handler functionality"""
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Mock the SSE session manager and its methods
|
|
mock_sse_session_manager = AsyncMock()
|
|
mock_sse_session_manager.handle_request = AsyncMock()
|
|
|
|
# Mock scope, receive, send with proper ASGI scope format
|
|
mock_scope = {
|
|
"type": "http",
|
|
"method": "GET",
|
|
"path": "/mcp/sse",
|
|
"headers": [(b"accept", b"text/event-stream")],
|
|
"query_string": b"",
|
|
"server": ("localhost", 8000),
|
|
"scheme": "http",
|
|
}
|
|
mock_receive = AsyncMock()
|
|
mock_send = AsyncMock()
|
|
|
|
mock_auth_result = (
|
|
UserAPIKeyAuth(),
|
|
None,
|
|
None,
|
|
{},
|
|
{},
|
|
[],
|
|
)
|
|
|
|
with (
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
|
|
True,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.sse_session_manager",
|
|
mock_sse_session_manager,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",
|
|
new=AsyncMock(return_value=mock_auth_result),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.set_auth_context",
|
|
),
|
|
):
|
|
from litellm.proxy._experimental.mcp_server.server import handle_sse_mcp
|
|
|
|
# Call the handler
|
|
await handle_sse_mcp(mock_scope, mock_receive, mock_send)
|
|
|
|
# Verify SSE session manager handle_request was called
|
|
mock_sse_session_manager.handle_request.assert_called_once_with(
|
|
mock_scope, mock_receive, mock_send
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sse_mcp_handler_propagates_passthrough_401():
|
|
"""SSE handler must raise 401 + WWW-Authenticate when the upstream
|
|
pass-through probe rejects the client's bearer token, instead of letting
|
|
the SSE session start and silently return empty tool lists."""
|
|
from fastapi import HTTPException
|
|
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
mock_scope = {
|
|
"type": "http",
|
|
"method": "GET",
|
|
"path": "/mcp/sse",
|
|
"headers": [(b"accept", b"text/event-stream")],
|
|
"query_string": b"",
|
|
"server": ("localhost", 8000),
|
|
"scheme": "http",
|
|
}
|
|
mock_receive = AsyncMock()
|
|
mock_send = AsyncMock()
|
|
|
|
mock_auth_result = (UserAPIKeyAuth(), None, None, {}, {}, [])
|
|
|
|
challenge = HTTPException(
|
|
status_code=401,
|
|
detail="Unauthorized",
|
|
headers={"WWW-Authenticate": "Bearer authorization_uri=https://example/"},
|
|
)
|
|
|
|
with (
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._SESSION_MANAGERS_INITIALIZED",
|
|
True,
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.sse_session_manager",
|
|
AsyncMock(),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.extract_mcp_auth_context",
|
|
new=AsyncMock(return_value=mock_auth_result),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.set_auth_context",
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._raise_preemptive_401_for_unauthenticated_servers",
|
|
new=AsyncMock(),
|
|
),
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._check_passthrough_upstream_auth",
|
|
new=AsyncMock(side_effect=challenge),
|
|
),
|
|
):
|
|
from litellm.proxy._experimental.mcp_server.server import handle_sse_mcp
|
|
|
|
with pytest.raises(HTTPException) as excinfo:
|
|
await handle_sse_mcp(mock_scope, mock_receive, mock_send)
|
|
|
|
assert excinfo.value.status_code == 401
|
|
assert excinfo.value.headers and "WWW-Authenticate" in excinfo.value.headers
|
|
|
|
|
|
def test_generate_stable_server_id():
|
|
"""
|
|
Test the _generate_stable_server_id method to ensure hash stability across releases.
|
|
|
|
This test verifies that:
|
|
1. The same inputs always produce the same hash output
|
|
2. Different inputs produce different hash outputs
|
|
3. The hash format is consistent (32 character hex string)
|
|
4. Edge cases work correctly (None auth_type)
|
|
|
|
IMPORTANT: If this test fails, it means the hashing algorithm has changed
|
|
and will break backwards compatibility with existing server IDs!
|
|
"""
|
|
manager = MCPServerManager()
|
|
|
|
# Test Case 1: Basic functionality with known inputs
|
|
# These expected values MUST remain stable across releases
|
|
test_cases = [
|
|
{
|
|
"params": {
|
|
"server_name": "zapier_mcp_server",
|
|
"url": "https://actions.zapier.com/mcp/sse",
|
|
"transport": "sse",
|
|
"auth_type": "api_key",
|
|
},
|
|
"expected_hash": "8d5c9f8a12e3b7c4f6a2d8e1b5c9f2a4",
|
|
},
|
|
{
|
|
"params": {
|
|
"server_name": "google_drive_mcp_server",
|
|
"url": "https://drive.google.com/mcp/http",
|
|
"transport": "http",
|
|
"auth_type": None,
|
|
},
|
|
"expected_hash": "7a4b2e8f3c1d9e6b5a7c8f2d4e1b9c6a",
|
|
},
|
|
{
|
|
"params": {
|
|
"server_name": "local_test_server",
|
|
"url": "http://localhost:8080/mcp",
|
|
"transport": "http",
|
|
"auth_type": "basic",
|
|
},
|
|
"expected_hash": "2f1e8d7c6b5a4e3f2d1c9b8a7e6f5d4c",
|
|
},
|
|
]
|
|
|
|
# Test that our known inputs produce expected hash values
|
|
for test_case in test_cases:
|
|
result = manager._generate_stable_server_id(**test_case["params"])
|
|
|
|
# For now, just verify the format and stability, not exact hash
|
|
# (since we need to first run to see what the actual hashes are)
|
|
assert len(result) == 32, f"Hash should be 32 characters, got {len(result)}"
|
|
assert result.isalnum(), f"Hash should be alphanumeric, got: {result}"
|
|
assert result.islower(), f"Hash should be lowercase, got: {result}"
|
|
|
|
# Test stability - same inputs should always produce same output
|
|
result2 = manager._generate_stable_server_id(**test_case["params"])
|
|
assert (
|
|
result == result2
|
|
), f"Hash should be stable for same inputs: {result} != {result2}"
|
|
|
|
# Test Case 2: Different inputs produce different outputs
|
|
base_params = {
|
|
"server_name": "test_server",
|
|
"url": "https://test.com/mcp",
|
|
"transport": "sse",
|
|
"auth_type": "api_key",
|
|
}
|
|
|
|
base_hash = manager._generate_stable_server_id(**base_params)
|
|
|
|
# Change each parameter and verify hash changes
|
|
variations = [
|
|
{"server_name": "different_server"},
|
|
{"url": "https://different.com/mcp"},
|
|
{"transport": "http"},
|
|
{"auth_type": "basic"},
|
|
{"auth_type": None},
|
|
]
|
|
|
|
for variation in variations:
|
|
modified_params = {**base_params, **variation}
|
|
modified_hash = manager._generate_stable_server_id(**modified_params)
|
|
assert (
|
|
modified_hash != base_hash
|
|
), f"Different params should produce different hash: {variation}"
|
|
assert (
|
|
len(modified_hash) == 32
|
|
), f"Modified hash should be 32 characters: {variation}"
|
|
|
|
# Test Case 3: Edge case with None auth_type
|
|
params_with_none = {
|
|
"server_name": "test_server",
|
|
"url": "https://test.com/mcp",
|
|
"transport": "sse",
|
|
"auth_type": None,
|
|
}
|
|
|
|
params_with_empty = {
|
|
"server_name": "test_server",
|
|
"url": "https://test.com/mcp",
|
|
"transport": "sse",
|
|
"auth_type": "",
|
|
}
|
|
|
|
hash_none = manager._generate_stable_server_id(**params_with_none)
|
|
hash_empty = manager._generate_stable_server_id(**params_with_empty)
|
|
|
|
# None and empty string should produce the same hash (both become empty string)
|
|
assert (
|
|
hash_none == hash_empty
|
|
), "None auth_type should be equivalent to empty string"
|
|
|
|
# Test Case 4: Real-world example hashes that must remain stable
|
|
# These are based on common configurations and MUST NOT CHANGE
|
|
zapier_sse_hash = manager._generate_stable_server_id(
|
|
server_name="zapier_mcp_server",
|
|
url="https://actions.zapier.com/mcp/sk-ak-example/sse",
|
|
transport="sse",
|
|
auth_type="api_key",
|
|
)
|
|
|
|
github_http_hash = manager._generate_stable_server_id(
|
|
server_name="github_mcp_server",
|
|
url="https://api.github.com/mcp/http",
|
|
transport="http",
|
|
auth_type=None,
|
|
)
|
|
|
|
# These should be deterministic - same call should produce same result
|
|
assert zapier_sse_hash == manager._generate_stable_server_id(
|
|
server_name="zapier_mcp_server",
|
|
url="https://actions.zapier.com/mcp/sk-ak-example/sse",
|
|
transport="sse",
|
|
auth_type="api_key",
|
|
)
|
|
|
|
assert github_http_hash == manager._generate_stable_server_id(
|
|
server_name="github_mcp_server",
|
|
url="https://api.github.com/mcp/http",
|
|
transport="http",
|
|
auth_type=None,
|
|
)
|
|
|
|
# Verify format
|
|
assert len(zapier_sse_hash) == 32
|
|
assert len(github_http_hash) == 32
|
|
assert zapier_sse_hash != github_http_hash
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tools_rest_api_server_not_found():
|
|
"""Test the list_tools REST API when server is not found"""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
list_tool_rest_api,
|
|
global_mcp_server_manager,
|
|
)
|
|
from fastapi import Query
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Mock UserAPIKeyAuth with explicit permission to access the requested server id
|
|
mock_user_auth = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=["non_existent_server_id"],
|
|
),
|
|
)
|
|
|
|
# Mock request with proper client attribute (internal IP for no filtering)
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {}
|
|
mock_request.client = MagicMock()
|
|
mock_request.client.host = "127.0.0.1" # Internal IP to bypass IP filtering
|
|
|
|
# Mock the global_mcp_server_manager to allow the server ID but return None for the server
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Allow the server ID in permissions
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["non_existent_server_id"]
|
|
)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
# Return None when trying to get the server (server doesn't exist)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=None)
|
|
|
|
# Test with non-existent server ID
|
|
response = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="non_existent_server_id",
|
|
user_api_key_dict=mock_user_auth,
|
|
)
|
|
|
|
assert isinstance(response, dict)
|
|
assert response["tools"] == []
|
|
assert response["error"] == "server_not_found"
|
|
assert "Server with id non_existent_server_id not found" in response["message"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tools_rest_api_success():
|
|
"""Test the list_tools REST API successful case"""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
list_tool_rest_api,
|
|
)
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
from fastapi import Query
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Mock successful tools
|
|
mock_tools = [
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="test_tool",
|
|
description="A test tool",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "test_server"},
|
|
)
|
|
]
|
|
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.server_id = "test-server-123"
|
|
mock_server.alias = "test_server"
|
|
mock_server.name = "test_server"
|
|
mock_server.mcp_info = {"server_name": "test_server"}
|
|
|
|
# Mock UserAPIKeyAuth
|
|
mock_user_auth = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=["test-server-123"],
|
|
),
|
|
)
|
|
|
|
# Mock request with proper client attribute (internal IP for no filtering)
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {}
|
|
mock_request.client = MagicMock()
|
|
mock_request.client.host = "127.0.0.1" # Internal IP to bypass IP filtering
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
mock_get_tools.return_value = mock_tools
|
|
|
|
# Test successful case
|
|
response = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="test-server-123",
|
|
user_api_key_dict=mock_user_auth,
|
|
)
|
|
|
|
assert isinstance(response, dict)
|
|
assert len(response["tools"]) == 1
|
|
assert response["tools"][0].name == "test_tool"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_tools_from_mcp_servers():
|
|
"""Test _get_tools_from_mcp_servers function with both specific and no server filters"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from litellm.proxy._experimental.mcp_server.mcp_server_manager import (
|
|
MCPServer,
|
|
MCPTransport,
|
|
)
|
|
|
|
# Mock data
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
mock_auth_header = "Bearer test_token"
|
|
mock_server_1 = MCPServer(
|
|
server_id="server1_id",
|
|
name="server1",
|
|
server_name="server1",
|
|
url="http://test1.com",
|
|
transport=MCPTransport.http,
|
|
)
|
|
mock_server_2 = MCPServer(
|
|
server_id="server2_id",
|
|
name="server2",
|
|
server_name="server2",
|
|
url="http://test2.com",
|
|
transport=MCPTransport.http,
|
|
)
|
|
mock_server_3 = MCPServer(
|
|
server_id="server3_id",
|
|
name="server3",
|
|
server_name="server3",
|
|
url="http://test3.com",
|
|
transport=MCPTransport.http,
|
|
access_groups=["group-a"],
|
|
)
|
|
mock_tool_1 = MCPTool(name="tool1", description="test tool 1", inputSchema={})
|
|
mock_tool_2 = MCPTool(name="tool2", description="test tool 2", inputSchema={})
|
|
|
|
# Test Case 1: With specific MCP servers
|
|
try:
|
|
# Mock the necessary methods
|
|
def mock_get_server_by_id(server_id):
|
|
if server_id == "server1_id":
|
|
return mock_server_1
|
|
elif server_id == "server2_id":
|
|
return mock_server_2
|
|
elif server_id == "server3_id":
|
|
return mock_server_3
|
|
return None
|
|
|
|
# Create a mock manager
|
|
mock_manager = AsyncMock()
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["server1_id", "server2_id"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = lambda server_id: (
|
|
mock_server_1 if server_id == "server1_id" else mock_server_2
|
|
)
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=[mock_tool_1])
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
|
|
mock_manager,
|
|
):
|
|
# Test with specific servers
|
|
result = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header=mock_auth_header,
|
|
mcp_servers=["server1"],
|
|
)
|
|
assert len(result) == 1, "Should only return tools from server1"
|
|
assert result[0].name == "tool1", "Should return tool from server1"
|
|
|
|
# Test Case 2: Without specific MCP servers
|
|
# Create a different mock manager for the second test case
|
|
mock_manager_2 = AsyncMock()
|
|
mock_manager_2.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["server1_id", "server2_id"]
|
|
)
|
|
mock_manager_2.get_mcp_server_by_id = lambda server_id: (
|
|
mock_server_1 if server_id == "server1_id" else mock_server_2
|
|
)
|
|
|
|
async def mock_get_tools_side_effect(
|
|
server,
|
|
mcp_auth_header=None,
|
|
extra_headers=None,
|
|
add_prefix=False,
|
|
raw_headers=None,
|
|
user_api_key_auth=None,
|
|
):
|
|
if server.server_id == "server1_id":
|
|
return [mock_tool_1]
|
|
return [mock_tool_2]
|
|
|
|
mock_manager_2._get_tools_from_server = AsyncMock(
|
|
side_effect=mock_get_tools_side_effect
|
|
)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager_2.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
|
|
mock_manager_2,
|
|
):
|
|
result = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header=mock_auth_header,
|
|
mcp_servers=None,
|
|
)
|
|
assert len(result) == 2, "Should return tools from all servers"
|
|
assert (
|
|
result[0].name == "tool1" and result[1].name == "tool2"
|
|
), "Should return tools from all servers"
|
|
|
|
#
|
|
# Test Case 3: With specific MCP servers and access groups
|
|
# Create a mock manager
|
|
mock_manager = AsyncMock()
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["server1_id", "server2_id", "server3_id"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = lambda server_id: (
|
|
mock_server_1
|
|
if server_id == "server1_id"
|
|
else (mock_server_2 if server_id == "server2_id" else mock_server_3)
|
|
)
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=[mock_tool_1])
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager",
|
|
mock_manager,
|
|
):
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp.MCPRequestHandler._get_mcp_servers_from_access_groups",
|
|
AsyncMock(return_value=["server3_id"]),
|
|
):
|
|
# Test with specific servers
|
|
result = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header=mock_auth_header,
|
|
mcp_servers=["group-a"],
|
|
)
|
|
assert len(result) == 1, "Should only return tools from server3"
|
|
assert result[0].name == "tool1", "Should return tool from server1"
|
|
|
|
except AssertionError as e:
|
|
pytest.fail(f"Test failed: {str(e)}")
|
|
except Exception as e:
|
|
pytest.fail(f"Unexpected error in tests: {str(e)}")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tools_only_returns_allowed_servers(monkeypatch):
|
|
"""
|
|
Test that list_tools only returns tools from servers allowed for the user.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Setup two servers in the config
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"server_a": {
|
|
"url": "https://server-a.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Server A",
|
|
},
|
|
"server_b": {
|
|
"url": "https://server-b.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Server B",
|
|
},
|
|
}
|
|
)
|
|
|
|
# Patch get_allowed_mcp_servers to only allow server_a
|
|
async def mock_get_allowed_mcp_servers(self, user_api_key_auth=None):
|
|
return [
|
|
list(test_manager.get_registry().keys())[0]
|
|
] # Only first server (server_a)
|
|
|
|
monkeypatch.setattr(
|
|
MCPServerManager, "get_allowed_mcp_servers", mock_get_allowed_mcp_servers
|
|
)
|
|
|
|
# Mock tools for each server
|
|
mock_tools_a = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email via Server A",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
mock_tools_b = [
|
|
MCPTool(
|
|
name="create_event",
|
|
description="Create an event via Server B",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Patch MCPClient to return different tools for each server
|
|
def mock_client_constructor(*args, **kwargs):
|
|
mock_client = AsyncMock()
|
|
# Return tools based on server URL
|
|
if kwargs.get("server_url") == "https://server-a.com/mcp":
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools_a)
|
|
else:
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools_b)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call list_tools
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
tools = await test_manager.list_tools(user_api_key_auth=UserAPIKeyAuth())
|
|
# Should only return tools from server_a
|
|
assert len(tools) == 1
|
|
# The server should use the server_name as prefix since no alias is provided
|
|
expected_prefix = "server_a"
|
|
assert tools[0].name.startswith(f"{expected_prefix}-")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_access_groups_from_config():
|
|
"""
|
|
Test that access_groups are loaded from config and can be resolved.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"config_server": {
|
|
"url": "https://config-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"access_groups": ["group-a", "group-b"],
|
|
},
|
|
"other_server": {
|
|
"url": "https://other-mcp-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"access_groups": ["group-b", "group-c"],
|
|
},
|
|
}
|
|
)
|
|
# Check that access_groups are loaded
|
|
config_server = next(
|
|
(
|
|
s
|
|
for s in test_manager.config_mcp_servers.values()
|
|
if s.name == "config_server"
|
|
),
|
|
None,
|
|
)
|
|
assert config_server is not None
|
|
assert set(config_server.access_groups) == {"group-a", "group-b"}
|
|
# Check that the lookup logic finds the correct server ids
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
|
|
# Patch global_mcp_server_manager for this test and restore afterwards to
|
|
# avoid leaking state into other tests (e.g. the proxy MCP e2e suite).
|
|
import litellm.proxy._experimental.mcp_server.mcp_server_manager as mcp_server_manager_mod
|
|
|
|
original_manager = mcp_server_manager_mod.global_mcp_server_manager
|
|
mcp_server_manager_mod.global_mcp_server_manager = test_manager
|
|
try:
|
|
# Should find config_server for group-a, both for group-b, other_server for group-c
|
|
import asyncio
|
|
|
|
server_ids_a = await MCPRequestHandler._get_mcp_servers_from_access_groups(
|
|
["group-a"]
|
|
)
|
|
server_ids_b = await MCPRequestHandler._get_mcp_servers_from_access_groups(
|
|
["group-b"]
|
|
)
|
|
server_ids_c = await MCPRequestHandler._get_mcp_servers_from_access_groups(
|
|
["group-c"]
|
|
)
|
|
assert any(config_server.server_id == sid for sid in server_ids_a)
|
|
assert set(server_ids_b) == set(
|
|
[
|
|
s.server_id
|
|
for s in test_manager.config_mcp_servers.values()
|
|
if "group-b" in s.access_groups
|
|
]
|
|
)
|
|
assert any(
|
|
s.name == "other_server" and s.server_id in server_ids_c
|
|
for s in test_manager.config_mcp_servers.values()
|
|
)
|
|
finally:
|
|
mcp_server_manager_mod.global_mcp_server_manager = original_manager
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_config_integration_with_database():
|
|
"""
|
|
Test that config-based servers properly integrate with database servers,
|
|
specifically testing access_groups and description fields.
|
|
"""
|
|
import datetime
|
|
from litellm.proxy._types import LiteLLM_MCPServerTable
|
|
|
|
test_manager = MCPServerManager()
|
|
|
|
# Test 1: Load config with access_groups and description
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"config_server_with_groups": {
|
|
"url": "https://config-server.com/mcp",
|
|
"transport": MCPTransport.http,
|
|
"description": "Test config server",
|
|
"access_groups": ["fr_staff", "admin"],
|
|
}
|
|
}
|
|
)
|
|
|
|
# Verify config server has correct access_groups
|
|
config_servers = test_manager.config_mcp_servers
|
|
assert len(config_servers) == 1
|
|
config_server = next(iter(config_servers.values()))
|
|
assert config_server.access_groups == ["fr_staff", "admin"]
|
|
assert config_server.mcp_info["description"] == "Test config server"
|
|
|
|
# Test 2: Create a database server record and test add_update_server method
|
|
db_server = LiteLLM_MCPServerTable(
|
|
server_id="db-server-123",
|
|
server_name="database-server",
|
|
url="https://db-server.com/mcp",
|
|
transport="http",
|
|
auth_type="none",
|
|
description="Database server description",
|
|
created_at=datetime.datetime.now(),
|
|
updated_at=datetime.datetime.now(),
|
|
mcp_access_groups=["db_group", "test_group"],
|
|
)
|
|
|
|
# Test the add_update_server method (this tests our fix)
|
|
await test_manager.add_server(db_server)
|
|
|
|
# Verify the server was added with correct access_groups
|
|
registry = test_manager.get_registry()
|
|
assert "db-server-123" in registry
|
|
|
|
db_server_in_registry = registry["db-server-123"]
|
|
assert db_server_in_registry.access_groups == ["db_group", "test_group"]
|
|
assert db_server_in_registry.server_name == "database-server"
|
|
|
|
# Test 3: Test config server conversion to LiteLLM_MCPServerTable format
|
|
# This tests that config servers are properly converted with access_groups and description fields
|
|
|
|
# Mock user auth to get all servers
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
mock_user_auth = UserAPIKeyAuth(user_role="proxy_admin")
|
|
|
|
# Mock the get_allowed_mcp_servers to return only config server IDs
|
|
# (to avoid database dependency in this test)
|
|
async def mock_get_allowed_servers(user_auth=None):
|
|
config_server_ids = list(test_manager.config_mcp_servers.keys())
|
|
return config_server_ids
|
|
|
|
test_manager.get_allowed_mcp_servers = mock_get_allowed_servers
|
|
|
|
# Mock health_check_server to avoid real network calls that timeout
|
|
async def mock_health_check(server_id: str, mcp_auth_header=None):
|
|
server = test_manager.get_mcp_server_by_id(server_id)
|
|
if not server:
|
|
return None
|
|
return LiteLLM_MCPServerTable(
|
|
server_id=server_id,
|
|
server_name=server.name,
|
|
url=server.url,
|
|
transport=server.transport,
|
|
description=server.mcp_info.get("description") if server.mcp_info else None,
|
|
mcp_access_groups=server.access_groups,
|
|
status="healthy",
|
|
last_health_check=datetime.datetime.now(),
|
|
mcp_info=server.mcp_info,
|
|
)
|
|
|
|
test_manager.health_check_server = mock_health_check
|
|
|
|
# Test the method (this tests our second fix)
|
|
servers_list = await test_manager.get_all_mcp_servers_with_health_and_teams(
|
|
user_api_key_auth=mock_user_auth
|
|
)
|
|
|
|
# Verify we have the config server properly converted
|
|
assert len(servers_list) == 1
|
|
|
|
# Find the config server in the list
|
|
config_server_in_list = servers_list[0]
|
|
assert config_server_in_list.server_name == "config_server_with_groups"
|
|
assert config_server_in_list.mcp_access_groups == ["fr_staff", "admin"]
|
|
assert config_server_in_list.description == "Test config server"
|
|
|
|
# Verify the mcp_info is also correct
|
|
assert config_server_in_list.mcp_info["description"] == "Test config server"
|
|
assert config_server_in_list.mcp_info["server_name"] == "config_server_with_groups"
|
|
|
|
|
|
# Tests for Server Alias Functionality
|
|
def test_get_server_prefix_with_alias():
|
|
"""
|
|
Test that get_server_prefix returns alias when present.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server with alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "my_alias"
|
|
mock_server.server_name = "My Server Name"
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "my_alias"
|
|
|
|
|
|
def test_get_server_prefix_without_alias():
|
|
"""
|
|
Test that get_server_prefix falls back to server_name when alias is not present.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server without alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = None
|
|
mock_server.server_name = "My Server Name"
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "My Server Name"
|
|
|
|
|
|
def test_get_server_prefix_fallback_to_server_id():
|
|
"""
|
|
Test that get_server_prefix falls back to server_id when neither alias nor server_name are present.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server without alias or server_name
|
|
mock_server = MagicMock()
|
|
mock_server.alias = None
|
|
mock_server.server_name = None
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "server-123"
|
|
|
|
|
|
def test_get_server_prefix_empty_strings():
|
|
"""
|
|
Test that get_server_prefix handles empty strings correctly.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import get_server_prefix
|
|
|
|
# Create a mock server with empty strings
|
|
mock_server = MagicMock()
|
|
mock_server.alias = ""
|
|
mock_server.server_name = ""
|
|
mock_server.server_id = "server-123"
|
|
|
|
prefix = get_server_prefix(mock_server)
|
|
assert prefix == "server-123"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_alias_tool_prefixing():
|
|
"""
|
|
Test that MCP server manager uses alias for tool prefixing when available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock server with alias
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server",
|
|
alias="my_alias",
|
|
server_name="Test Server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
)
|
|
|
|
# Add server to registry
|
|
test_manager.registry["test-server-123"] = mock_server
|
|
|
|
# Mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Get tools from server
|
|
tools = await test_manager._get_tools_from_server(mock_server)
|
|
|
|
# Verify tool is prefixed with alias
|
|
assert len(tools) == 1
|
|
assert tools[0].name == "my_alias-send_email"
|
|
|
|
# Verify mapping is updated correctly
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
|
|
== "my_alias"
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["my_alias-send_email"]
|
|
== "my_alias"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_server_name_tool_prefixing():
|
|
"""
|
|
Test that MCP server manager falls back to server_name for tool prefixing when alias is not available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock server without alias
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server",
|
|
alias=None,
|
|
server_name="Test Server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
)
|
|
|
|
# Add server to registry
|
|
test_manager.registry["test-server-123"] = mock_server
|
|
|
|
# Mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Get tools from server
|
|
tools = await test_manager._get_tools_from_server(mock_server)
|
|
|
|
# Verify tool is prefixed with server_name (normalized)
|
|
assert len(tools) == 1
|
|
assert tools[0].name == "Test_Server-send_email"
|
|
|
|
# Verify mapping is updated correctly
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
|
|
== "Test Server"
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["Test_Server-send_email"]
|
|
== "Test Server"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_server_id_tool_prefixing():
|
|
"""
|
|
Test that MCP server manager falls back to server_id for tool prefixing when neither alias nor server_name are available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock server without alias or server_name
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server",
|
|
alias=None,
|
|
server_name=None,
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
)
|
|
|
|
# Add server to registry
|
|
test_manager.registry["test-server-123"] = mock_server
|
|
|
|
# Mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
)
|
|
]
|
|
|
|
# Mock MCPClient
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Get tools from server
|
|
tools = await test_manager._get_tools_from_server(mock_server)
|
|
|
|
# Verify tool is prefixed with server_id
|
|
assert len(tools) == 1
|
|
assert tools[0].name == "test-server-123-send_email"
|
|
|
|
# Verify mapping is updated correctly
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping["send_email"]
|
|
== "test-server-123"
|
|
)
|
|
assert (
|
|
test_manager.tool_name_to_mcp_server_name_mapping[
|
|
"test-server-123-send_email"
|
|
]
|
|
== "test-server-123"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_update_server_with_alias():
|
|
"""
|
|
Test that add_update_server correctly handles servers with alias.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock LiteLLM_MCPServerTable with alias
|
|
mock_mcp_server = MagicMock()
|
|
mock_mcp_server.server_id = "test-server-123"
|
|
mock_mcp_server.alias = "my_alias"
|
|
mock_mcp_server.server_name = "Test Server"
|
|
mock_mcp_server.url = "https://test-server.com/mcp"
|
|
mock_mcp_server.transport = MCPTransport.http
|
|
mock_mcp_server.auth_type = None
|
|
mock_mcp_server.credentials = {}
|
|
mock_mcp_server.description = "Test server description"
|
|
mock_mcp_server.mcp_info = {}
|
|
mock_mcp_server.static_headers = {}
|
|
mock_mcp_server.command = None
|
|
mock_mcp_server.args = []
|
|
mock_mcp_server.env = None
|
|
mock_mcp_server.spec_path = None
|
|
# OAuth fields - set explicitly to None to avoid MagicMock objects
|
|
mock_mcp_server.client_id = None
|
|
mock_mcp_server.client_secret = None
|
|
mock_mcp_server.authorization_url = None
|
|
mock_mcp_server.registration_url = None
|
|
mock_mcp_server.token_url = None
|
|
mock_mcp_server.oauth2_flow = None
|
|
# Additional fields used by build_mcp_server_from_table
|
|
mock_mcp_server.extra_headers = None
|
|
mock_mcp_server.allow_all_keys = False
|
|
mock_mcp_server.available_on_public_internet = True
|
|
mock_mcp_server.mcp_access_groups = None
|
|
mock_mcp_server.allowed_tools = None
|
|
mock_mcp_server.disallowed_tools = None
|
|
mock_mcp_server.tool_name_to_display_name = None
|
|
mock_mcp_server.tool_name_to_description = None
|
|
mock_mcp_server.is_byok = False
|
|
mock_mcp_server.byok_description = None
|
|
mock_mcp_server.byok_api_key_help_url = None
|
|
mock_mcp_server.created_at = None
|
|
mock_mcp_server.updated_at = None
|
|
mock_mcp_server.instructions = None
|
|
mock_mcp_server.source_url = None
|
|
mock_mcp_server.approval_status = "active"
|
|
|
|
# Add server to manager
|
|
await test_manager.add_server(mock_mcp_server)
|
|
|
|
# Verify server was added with correct name (should use alias)
|
|
assert "test-server-123" in test_manager.registry
|
|
added_server = test_manager.registry["test-server-123"]
|
|
assert added_server.name == "my_alias"
|
|
assert added_server.alias == "my_alias"
|
|
assert added_server.server_name == "Test Server"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_update_server_without_alias():
|
|
"""
|
|
Test that add_update_server correctly handles servers without alias.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock LiteLLM_MCPServerTable without alias
|
|
mock_mcp_server = MagicMock()
|
|
mock_mcp_server.server_id = "test-server-123"
|
|
mock_mcp_server.alias = None
|
|
mock_mcp_server.server_name = "Test Server"
|
|
mock_mcp_server.url = "https://test-server.com/mcp"
|
|
mock_mcp_server.transport = MCPTransport.http
|
|
mock_mcp_server.auth_type = None
|
|
mock_mcp_server.credentials = {}
|
|
mock_mcp_server.description = "Test server description"
|
|
mock_mcp_server.mcp_info = {}
|
|
mock_mcp_server.static_headers = {}
|
|
mock_mcp_server.command = None
|
|
mock_mcp_server.args = []
|
|
mock_mcp_server.env = None
|
|
mock_mcp_server.spec_path = None
|
|
# OAuth fields - set explicitly to None to avoid MagicMock objects
|
|
mock_mcp_server.client_id = None
|
|
mock_mcp_server.client_secret = None
|
|
mock_mcp_server.authorization_url = None
|
|
mock_mcp_server.registration_url = None
|
|
mock_mcp_server.token_url = None
|
|
mock_mcp_server.oauth2_flow = None
|
|
# Additional fields used by build_mcp_server_from_table
|
|
mock_mcp_server.extra_headers = None
|
|
mock_mcp_server.allow_all_keys = False
|
|
mock_mcp_server.available_on_public_internet = True
|
|
mock_mcp_server.mcp_access_groups = None
|
|
mock_mcp_server.allowed_tools = None
|
|
mock_mcp_server.disallowed_tools = None
|
|
mock_mcp_server.tool_name_to_display_name = None
|
|
mock_mcp_server.tool_name_to_description = None
|
|
mock_mcp_server.is_byok = False
|
|
mock_mcp_server.byok_description = None
|
|
mock_mcp_server.byok_api_key_help_url = None
|
|
mock_mcp_server.created_at = None
|
|
mock_mcp_server.updated_at = None
|
|
mock_mcp_server.instructions = None
|
|
mock_mcp_server.source_url = None
|
|
mock_mcp_server.approval_status = "active"
|
|
|
|
# Add server to manager
|
|
await test_manager.add_server(mock_mcp_server)
|
|
|
|
# Verify server was added with correct name (should use server_name)
|
|
assert "test-server-123" in test_manager.registry
|
|
added_server = test_manager.registry["test-server-123"]
|
|
assert added_server.name == "Test Server"
|
|
assert added_server.alias is None
|
|
assert added_server.server_name == "Test Server"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_update_server_fallback_to_server_id():
|
|
"""
|
|
Test that add_update_server falls back to server_id when neither alias nor server_name are available.
|
|
"""
|
|
test_manager = MCPServerManager()
|
|
|
|
# Create a mock LiteLLM_MCPServerTable without alias or server_name
|
|
mock_mcp_server = MagicMock()
|
|
mock_mcp_server.server_id = "test-server-123"
|
|
mock_mcp_server.alias = None
|
|
mock_mcp_server.server_name = None
|
|
mock_mcp_server.url = "https://test-server.com/mcp"
|
|
mock_mcp_server.transport = MCPTransport.http
|
|
mock_mcp_server.auth_type = None
|
|
mock_mcp_server.credentials = {}
|
|
mock_mcp_server.description = "Test server description"
|
|
mock_mcp_server.mcp_info = {}
|
|
mock_mcp_server.static_headers = {}
|
|
mock_mcp_server.command = None
|
|
mock_mcp_server.args = []
|
|
mock_mcp_server.env = None
|
|
mock_mcp_server.spec_path = None
|
|
# OAuth fields - set explicitly to None to avoid MagicMock objects
|
|
mock_mcp_server.client_id = None
|
|
mock_mcp_server.client_secret = None
|
|
mock_mcp_server.authorization_url = None
|
|
mock_mcp_server.registration_url = None
|
|
mock_mcp_server.token_url = None
|
|
mock_mcp_server.oauth2_flow = None
|
|
# Additional fields used by build_mcp_server_from_table - set explicitly
|
|
# to avoid MagicMock objects being passed to Pydantic MCPServer constructor
|
|
mock_mcp_server.extra_headers = None
|
|
mock_mcp_server.allow_all_keys = False
|
|
mock_mcp_server.available_on_public_internet = True
|
|
mock_mcp_server.mcp_access_groups = None
|
|
mock_mcp_server.allowed_tools = None
|
|
mock_mcp_server.disallowed_tools = None
|
|
mock_mcp_server.tool_name_to_display_name = None
|
|
mock_mcp_server.tool_name_to_description = None
|
|
mock_mcp_server.is_byok = False
|
|
mock_mcp_server.byok_description = None
|
|
mock_mcp_server.byok_api_key_help_url = None
|
|
mock_mcp_server.created_at = None
|
|
mock_mcp_server.updated_at = None
|
|
mock_mcp_server.instructions = None
|
|
mock_mcp_server.source_url = None
|
|
mock_mcp_server.approval_status = "active"
|
|
# Add server to manager
|
|
await test_manager.add_server(mock_mcp_server)
|
|
|
|
# Verify server was added with correct name (should use server_id)
|
|
assert "test-server-123" in test_manager.registry
|
|
added_server = test_manager.registry["test-server-123"]
|
|
assert added_server.name == "test-server-123"
|
|
assert added_server.alias is None
|
|
assert added_server.server_name is None
|
|
|
|
|
|
def test_normalize_server_name():
|
|
"""
|
|
Test that normalize_server_name correctly replaces spaces with underscores.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.utils import normalize_server_name
|
|
|
|
# Test basic space replacement
|
|
assert normalize_server_name("My Server Name") == "My_Server_Name"
|
|
|
|
# Test multiple consecutive spaces
|
|
assert normalize_server_name("My Server Name") == "My__Server___Name"
|
|
|
|
# Test no spaces
|
|
assert normalize_server_name("MyServerName") == "MyServerName"
|
|
|
|
# Test empty string
|
|
assert normalize_server_name("") == ""
|
|
|
|
# Test string with only spaces
|
|
assert normalize_server_name(" ") == "___"
|
|
|
|
|
|
def test_add_server_prefix_to_name():
|
|
"""Ensure add_server_prefix_to_name correctly formats resource names."""
|
|
from litellm.proxy._experimental.mcp_server.utils import add_server_prefix_to_name
|
|
|
|
# Test basic prefixing
|
|
result = add_server_prefix_to_name("send_email", "My Server")
|
|
assert result == "My_Server-send_email"
|
|
|
|
# Test with server name that already has underscores
|
|
result = add_server_prefix_to_name("create_event", "my_server")
|
|
assert result == "my_server-create_event"
|
|
|
|
# Test with empty name
|
|
result = add_server_prefix_to_name("", "My Server")
|
|
assert result == "My_Server-"
|
|
|
|
# Test with empty server name
|
|
result = add_server_prefix_to_name("send_email", "")
|
|
assert result == "-send_email"
|
|
|
|
|
|
def test_get_server_auth_header_with_alias():
|
|
"""Test _get_server_auth_header function with server alias."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server with alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "zapier"
|
|
mock_server.server_name = "zapier_server"
|
|
|
|
# Test with server-specific auth headers
|
|
mcp_server_auth_headers = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
mcp_auth_header = "Bearer default_token"
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer zapier_token"
|
|
|
|
# Test case-insensitive matching
|
|
mcp_server_auth_headers = {
|
|
"ZAPIER": "Bearer zapier_token_upper",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer zapier_token_upper"
|
|
|
|
|
|
def test_get_server_auth_header_with_server_name():
|
|
"""Test _get_server_auth_header function with server name (no alias)."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server with server_name but no alias
|
|
mock_server = MagicMock()
|
|
mock_server.alias = None
|
|
mock_server.server_name = "slack_server"
|
|
|
|
# Test with server-specific auth headers
|
|
mcp_server_auth_headers = {
|
|
"slack_server": "Bearer slack_token",
|
|
"zapier": "Bearer zapier_token",
|
|
}
|
|
mcp_auth_header = "Bearer default_token"
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer slack_token"
|
|
|
|
# Test case-insensitive matching
|
|
mcp_server_auth_headers = {
|
|
"SLACK_SERVER": "Bearer slack_token_upper",
|
|
"zapier": "Bearer zapier_token",
|
|
}
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer slack_token_upper"
|
|
|
|
|
|
def test_get_server_auth_header_fallback_to_default():
|
|
"""Test _get_server_auth_header function fallback to default auth header."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "unknown_server"
|
|
mock_server.server_name = "unknown_server_name"
|
|
|
|
# Test with no matching server-specific headers
|
|
mcp_server_auth_headers = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
mcp_auth_header = "Bearer default_token"
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, mcp_auth_header
|
|
)
|
|
assert result == "Bearer default_token"
|
|
|
|
# Test with no server-specific headers at all
|
|
result = _get_server_auth_header(mock_server, None, mcp_auth_header)
|
|
assert result == "Bearer default_token"
|
|
|
|
|
|
def test_get_server_auth_header_hyphenated_alias_sanitized_header_key():
|
|
"""Header keys use sanitized alias; lookup must match legacy hyphenated aliases."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "GitHub-MCP"
|
|
mock_server.server_name = "github_mcp_server"
|
|
|
|
mcp_server_auth_headers = {
|
|
"github_mcp": {"Authorization": "Bearer github-mcp-token"},
|
|
}
|
|
|
|
result = _get_server_auth_header(
|
|
mock_server, mcp_server_auth_headers, "Bearer default_token"
|
|
)
|
|
assert result == {"Authorization": "Bearer github-mcp-token"}
|
|
|
|
|
|
def test_get_server_auth_header_no_auth_headers():
|
|
"""Test _get_server_auth_header function with no auth headers."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_server_auth_header,
|
|
)
|
|
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.alias = "zapier"
|
|
mock_server.server_name = "zapier_server"
|
|
|
|
# Test with no auth headers
|
|
result = _get_server_auth_header(mock_server, None, None)
|
|
assert result is None
|
|
|
|
result = _get_server_auth_header(mock_server, {}, None)
|
|
assert result is None
|
|
|
|
|
|
def test_create_tool_response_objects():
|
|
"""Test _create_tool_response_objects enriches mcp_info with server_id and alias."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_create_tool_response_objects,
|
|
)
|
|
from litellm.types.mcp_server.mcp_server_manager import MCPServer
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object", "properties": {"to": {"type": "string"}}},
|
|
),
|
|
MCPTool(
|
|
name="create_event",
|
|
description="Create a calendar event",
|
|
inputSchema={"type": "object", "properties": {"title": {"type": "string"}}},
|
|
),
|
|
]
|
|
|
|
server = MCPServer(
|
|
server_id="a1b2c3d4",
|
|
name="zapier_internal",
|
|
alias="zapier",
|
|
transport="http",
|
|
mcp_info={
|
|
"server_name": "zapier_internal",
|
|
"logo_url": "https://zapier.com/logo.png",
|
|
},
|
|
)
|
|
|
|
result = _create_tool_response_objects(mock_tools, server)
|
|
|
|
expected_mcp_info = {
|
|
"server_name": "zapier_internal",
|
|
"logo_url": "https://zapier.com/logo.png",
|
|
"server_id": "a1b2c3d4",
|
|
"alias": "zapier",
|
|
}
|
|
assert len(result) == 2
|
|
assert result[0].name == "send_email"
|
|
assert result[0].description == "Send an email"
|
|
assert result[0].mcp_info == expected_mcp_info
|
|
assert result[1].name == "create_event"
|
|
assert result[1].description == "Create a calendar event"
|
|
assert result[1].mcp_info == expected_mcp_info
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_tools_for_single_server():
|
|
"""Test _get_tools_for_single_server function."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_tools_for_single_server,
|
|
)
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock server (pin allowlist fields; MagicMock auto-attrs are truthy)
|
|
mock_server = MagicMock()
|
|
mock_server.mcp_info = {"server_name": "zapier"}
|
|
mock_server.server_id = "zapier_id"
|
|
mock_server.alias = "zapier_alias"
|
|
mock_server.allowed_tools = None
|
|
mock_server.disallowed_tools = None
|
|
|
|
# Create mock tools
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object", "properties": {"to": {"type": "string"}}},
|
|
)
|
|
]
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
result = await _get_tools_for_single_server(mock_server, "Bearer test_token")
|
|
|
|
# Verify the manager was called with correct parameters
|
|
mock_manager._get_tools_from_server.assert_called_once_with(
|
|
server=mock_server,
|
|
mcp_auth_header="Bearer test_token",
|
|
extra_headers=None,
|
|
add_prefix=False,
|
|
raw_headers=None,
|
|
user_api_key_auth=None,
|
|
)
|
|
|
|
# Verify the result
|
|
assert len(result) == 1
|
|
assert result[0].name == "send_email"
|
|
assert result[0].mcp_info == {
|
|
"server_name": "zapier",
|
|
"server_id": "zapier_id",
|
|
"alias": "zapier_alias",
|
|
}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_tools_for_single_server_applies_disallowed_tools_without_allowlist():
|
|
"""REST listing must honor disallowed_tools even when no allowlist is set."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import (
|
|
_get_tools_for_single_server,
|
|
)
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
mock_server = MagicMock()
|
|
mock_server.mcp_info = {"server_name": "zapier"}
|
|
mock_server.name = "zapier"
|
|
mock_server.server_id = "zapier"
|
|
mock_server.allowed_tools = None
|
|
mock_server.disallowed_tools = ["send_email"]
|
|
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="read_email",
|
|
description="Read an email",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
result = await _get_tools_for_single_server(mock_server, "Bearer test_token")
|
|
|
|
assert [tool.name for tool in result] == ["read_email"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tool_rest_api_with_server_specific_auth():
|
|
"""Test list_tool_rest_api with server-specific auth headers."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create mock request with server-specific auth headers
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {
|
|
"authorization": "Bearer user_token",
|
|
"x-mcp-zapier-authorization": "Bearer zapier_token",
|
|
"x-mcp-slack-authorization": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the MCPRequestHandler methods
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_auth_header_from_headers"
|
|
) as mock_get_auth:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
|
|
) as mock_get_server_auth:
|
|
mock_get_auth.return_value = "Bearer default_token"
|
|
mock_get_server_auth.return_value = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.server_id = "test-server-123"
|
|
mock_server.alias = "zapier"
|
|
mock_server.name = "zapier_server"
|
|
mock_server.mcp_info = {"server_name": "zapier"}
|
|
|
|
mock_manager.get_mcp_server_by_id.return_value = mock_server
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
mock_user_api_key_dict = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test_user",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=[mock_server.server_id],
|
|
),
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
|
|
mock_tools = [
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "zapier"},
|
|
)
|
|
]
|
|
mock_get_tools.return_value = mock_tools
|
|
|
|
# Call the function
|
|
result = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="test-server-123",
|
|
user_api_key_dict=mock_user_api_key_dict,
|
|
)
|
|
|
|
# Verify the result
|
|
assert result["error"] is None
|
|
assert len(result["tools"]) == 1
|
|
assert result["tools"][0].name == "send_email"
|
|
|
|
# Verify that _get_tools_for_single_server was called with the correct auth header
|
|
mock_get_tools.assert_called_once()
|
|
call_args = mock_get_tools.call_args
|
|
assert call_args[0][0] == mock_server # server
|
|
assert (
|
|
call_args[0][1] == "Bearer zapier_token"
|
|
) # server_auth_header
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tool_rest_api_with_default_auth():
|
|
"""Test list_tool_rest_api with default auth header when no server-specific header is found."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create mock request with default auth header only
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {
|
|
"authorization": "Bearer user_token",
|
|
"x-mcp-authorization": "Bearer default_token",
|
|
}
|
|
|
|
# Mock the MCPRequestHandler methods
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_auth_header_from_headers"
|
|
) as mock_get_auth:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
|
|
) as mock_get_server_auth:
|
|
mock_get_auth.return_value = "Bearer default_token"
|
|
mock_get_server_auth.return_value = {} # No server-specific headers
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
# Create a mock server
|
|
mock_server = MagicMock()
|
|
mock_server.server_id = "test-server-123"
|
|
mock_server.alias = "unknown_server"
|
|
mock_server.name = "unknown_server"
|
|
mock_server.mcp_info = {"server_name": "unknown_server"}
|
|
|
|
mock_manager.get_mcp_server_by_id.return_value = mock_server
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
mock_user_api_key_dict = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test_user",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=[mock_server.server_id],
|
|
),
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
|
|
mock_tools = [
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "unknown_server"},
|
|
)
|
|
]
|
|
mock_get_tools.return_value = mock_tools
|
|
|
|
# Call the function
|
|
result = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id="test-server-123",
|
|
user_api_key_dict=mock_user_api_key_dict,
|
|
)
|
|
|
|
# Verify the result
|
|
assert result["error"] is None
|
|
assert len(result["tools"]) == 1
|
|
assert result["tools"][0].name == "send_email"
|
|
|
|
# Verify that _get_tools_for_single_server was called with the default auth header
|
|
mock_get_tools.assert_called_once()
|
|
call_args = mock_get_tools.call_args
|
|
assert call_args[0][0] == mock_server # server
|
|
assert (
|
|
call_args[0][1] == "Bearer default_token"
|
|
) # server_auth_header
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tool_rest_api_all_servers_with_auth():
|
|
"""Test list_tool_rest_api for all servers with server-specific auth headers."""
|
|
from litellm.proxy._experimental.mcp_server.rest_endpoints import list_tool_rest_api
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create mock request with server-specific auth headers
|
|
mock_request = MagicMock()
|
|
mock_request.headers = {
|
|
"authorization": "Bearer user_token",
|
|
"x-mcp-zapier-authorization": "Bearer zapier_token",
|
|
"x-mcp-slack-authorization": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the MCPRequestHandler methods
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_auth_header_from_headers"
|
|
) as mock_get_auth:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_mcp_server_auth_headers_from_headers"
|
|
) as mock_get_server_auth:
|
|
mock_get_auth.return_value = "Bearer default_token"
|
|
mock_get_server_auth.return_value = {
|
|
"zapier": "Bearer zapier_token",
|
|
"slack": "Bearer slack_token",
|
|
}
|
|
|
|
# Mock the global_mcp_server_manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Create mock servers
|
|
mock_zapier_server = MagicMock()
|
|
mock_zapier_server.alias = "zapier"
|
|
mock_zapier_server.server_name = "zapier_server"
|
|
mock_zapier_server.mcp_info = {"server_name": "zapier"}
|
|
|
|
mock_slack_server = MagicMock()
|
|
mock_slack_server.alias = "slack"
|
|
mock_slack_server.server_name = "slack_server"
|
|
mock_slack_server.mcp_info = {"server_name": "slack"}
|
|
|
|
mock_manager.get_registry.return_value = {
|
|
"zapier": mock_zapier_server,
|
|
"slack": mock_slack_server,
|
|
}
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["zapier", "slack"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id.side_effect = (
|
|
lambda server_id: mock_manager.get_registry.return_value.get(
|
|
server_id
|
|
)
|
|
)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
mock_user_api_key_dict = UserAPIKeyAuth(
|
|
api_key="test",
|
|
user_id="test_user",
|
|
object_permission=LiteLLM_ObjectPermissionTable(
|
|
object_permission_id="dummy",
|
|
mcp_servers=["zapier", "slack"],
|
|
),
|
|
)
|
|
|
|
# Mock the _get_tools_for_single_server function
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.rest_endpoints._get_tools_for_single_server"
|
|
) as mock_get_tools:
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
ListMCPToolsRestAPIResponseObject,
|
|
)
|
|
|
|
# Mock tools for each server
|
|
mock_get_tools.side_effect = [
|
|
[
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_email",
|
|
description="Send an email",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "zapier"},
|
|
)
|
|
],
|
|
[
|
|
ListMCPToolsRestAPIResponseObject(
|
|
name="send_message",
|
|
description="Send a message",
|
|
inputSchema={"type": "object"},
|
|
mcp_info={"server_name": "slack"},
|
|
)
|
|
],
|
|
]
|
|
|
|
# Call the function without server_id (query all servers)
|
|
result = await list_tool_rest_api(
|
|
request=mock_request,
|
|
server_id=None,
|
|
user_api_key_dict=mock_user_api_key_dict,
|
|
)
|
|
|
|
# Verify the result
|
|
assert result["error"] is None
|
|
assert len(result["tools"]) == 2
|
|
assert result["tools"][0].name == "send_email"
|
|
assert result["tools"][1].name == "send_message"
|
|
|
|
# Verify that _get_tools_for_single_server was called for both servers
|
|
assert mock_get_tools.call_count == 2
|
|
server_auth_map = {
|
|
call_args[0][0]: call_args[0][1]
|
|
for call_args in mock_get_tools.call_args_list
|
|
}
|
|
|
|
assert (
|
|
server_auth_map.get(mock_zapier_server) == "Bearer zapier_token"
|
|
)
|
|
assert (
|
|
server_auth_map.get(mock_slack_server) == "Bearer slack_token"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_filter_tools_by_allowed_tools_integration():
|
|
"""Test that filter_tools_by_allowed_tools works correctly via _get_tools_from_mcp_servers"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock user auth
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
|
|
# Create mock tools that will be returned by the server
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="allowed_tool_1",
|
|
description="This tool should be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="allowed_tool_2",
|
|
description="This tool should also be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="blocked_tool_1",
|
|
description="This tool should be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="blocked_tool_2",
|
|
description="This tool should also be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
# Create a mock server with allowed_tools restriction
|
|
mock_server = MCPServer(
|
|
server_id="test-server-123",
|
|
name="test_server_with_allowed_tools",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
allowed_tools=[
|
|
"allowed_tool_1",
|
|
"allowed_tool_2",
|
|
], # Only these tools should be returned
|
|
disallowed_tools=None,
|
|
)
|
|
|
|
# Create a mock MCPClient that returns all tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
# Mock the global MCP server manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Mock manager methods
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-123"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
# Mock the _get_tools_from_server method to return all tools
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
# Mock the MCPClient constructor
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call _get_tools_from_mcp_servers which should apply the filtering
|
|
filtered_tools = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header="Bearer test_token",
|
|
mcp_servers=None, # Get from all servers
|
|
)
|
|
|
|
# Verify that only allowed tools are returned
|
|
assert (
|
|
len(filtered_tools) == 2
|
|
), f"Expected 2 tools, got {len(filtered_tools)}"
|
|
|
|
tool_names = [tool.name for tool in filtered_tools]
|
|
assert (
|
|
"allowed_tool_1" in tool_names
|
|
), "allowed_tool_1 should be in filtered results"
|
|
assert (
|
|
"allowed_tool_2" in tool_names
|
|
), "allowed_tool_2 should be in filtered results"
|
|
assert (
|
|
"blocked_tool_1" not in tool_names
|
|
), "blocked_tool_1 should be filtered out"
|
|
assert (
|
|
"blocked_tool_2" not in tool_names
|
|
), "blocked_tool_2 should be filtered out"
|
|
|
|
# Verify the manager methods were called correctly
|
|
mock_manager.get_allowed_mcp_servers.assert_called_once_with(mock_user_auth)
|
|
# Note: get_mcp_server_by_id is now called for each server ID instead of batch
|
|
# Verify it was called with the correct server ID
|
|
assert mock_manager.get_mcp_server_by_id.call_count > 0
|
|
mock_manager._get_tools_from_server.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_filter_tools_by_disallowed_tools_integration():
|
|
"""Test that filter_tools_by_allowed_tools works correctly with disallowed_tools via _get_tools_from_mcp_servers"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock user auth
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
|
|
# Create mock tools that will be returned by the server
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="safe_tool_1",
|
|
description="This tool should be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="safe_tool_2",
|
|
description="This tool should also be allowed",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="dangerous_tool_1",
|
|
description="This tool should be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="dangerous_tool_2",
|
|
description="This tool should also be blocked",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
# Create a mock server with disallowed_tools restriction
|
|
mock_server = MCPServer(
|
|
server_id="test-server-456",
|
|
name="test_server_with_disallowed_tools",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
allowed_tools=None,
|
|
disallowed_tools=[
|
|
"dangerous_tool_1",
|
|
"dangerous_tool_2",
|
|
], # These tools should be filtered out
|
|
)
|
|
|
|
# Create a mock MCPClient that returns all tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
# Mock the global MCP server manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Mock manager methods
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-456"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
# Mock the _get_tools_from_server method to return all tools
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
# Mock the MCPClient constructor
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call _get_tools_from_mcp_servers which should apply the filtering
|
|
filtered_tools = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header="Bearer test_token",
|
|
mcp_servers=None, # Get from all servers
|
|
)
|
|
|
|
# Verify that only safe tools are returned (dangerous tools filtered out)
|
|
assert (
|
|
len(filtered_tools) == 2
|
|
), f"Expected 2 tools, got {len(filtered_tools)}"
|
|
|
|
tool_names = [tool.name for tool in filtered_tools]
|
|
assert (
|
|
"safe_tool_1" in tool_names
|
|
), "safe_tool_1 should be in filtered results"
|
|
assert (
|
|
"safe_tool_2" in tool_names
|
|
), "safe_tool_2 should be in filtered results"
|
|
assert (
|
|
"dangerous_tool_1" not in tool_names
|
|
), "dangerous_tool_1 should be filtered out"
|
|
assert (
|
|
"dangerous_tool_2" not in tool_names
|
|
), "dangerous_tool_2 should be filtered out"
|
|
|
|
# Verify the manager methods were called correctly
|
|
mock_manager.get_allowed_mcp_servers.assert_called_once_with(mock_user_auth)
|
|
# Note: get_mcp_server_by_id is now called for each server ID instead of batch
|
|
# Verify it was called with the correct server ID
|
|
assert mock_manager.get_mcp_server_by_id.call_count > 0
|
|
mock_manager._get_tools_from_server.assert_called_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_filter_tools_no_restrictions_integration():
|
|
"""Test that filter_tools_by_allowed_tools returns all tools when no restrictions are set"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
_get_tools_from_mcp_servers,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from mcp.types import Tool as MCPTool
|
|
|
|
# Create a mock user auth
|
|
mock_user_auth = UserAPIKeyAuth(api_key="test_key", user_id="test_user")
|
|
|
|
# Create mock tools that will be returned by the server
|
|
mock_tools = [
|
|
MCPTool(
|
|
name="tool_1",
|
|
description="Tool 1",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
MCPTool(
|
|
name="tool_2",
|
|
description="Tool 2",
|
|
inputSchema={"type": "object"},
|
|
),
|
|
]
|
|
|
|
# Create a mock server with no tool restrictions
|
|
mock_server = MCPServer(
|
|
server_id="test-server-000",
|
|
name="test_server_no_restrictions",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
allowed_tools=None, # No restrictions
|
|
disallowed_tools=None, # No restrictions
|
|
)
|
|
|
|
# Create a mock MCPClient that returns all tools
|
|
mock_client = AsyncMock()
|
|
mock_client.list_tools = AsyncMock(return_value=mock_tools)
|
|
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
|
|
mock_client.__aexit__ = AsyncMock(return_value=None)
|
|
|
|
def mock_client_constructor(*args, **kwargs):
|
|
return mock_client
|
|
|
|
# Mock the global MCP server manager
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_server_manager"
|
|
) as mock_manager:
|
|
# Mock manager methods
|
|
mock_manager.get_allowed_mcp_servers = AsyncMock(
|
|
return_value=["test-server-000"]
|
|
)
|
|
mock_manager.get_mcp_server_by_id = MagicMock(return_value=mock_server)
|
|
# Mock filter_server_ids_by_ip_with_info to return input unchanged (no IP filtering in test)
|
|
mock_manager.filter_server_ids_by_ip_with_info = MagicMock(
|
|
side_effect=lambda server_ids, client_ip: (server_ids, 0)
|
|
)
|
|
|
|
# Mock the _get_tools_from_server method to return all tools
|
|
mock_manager._get_tools_from_server = AsyncMock(return_value=mock_tools)
|
|
|
|
# Mock the MCPClient constructor
|
|
with patch(
|
|
"litellm.proxy._experimental.mcp_server.mcp_server_manager.MCPClient",
|
|
mock_client_constructor,
|
|
):
|
|
# Call _get_tools_from_mcp_servers which should apply the filtering
|
|
filtered_tools = await _get_tools_from_mcp_servers(
|
|
user_api_key_auth=mock_user_auth,
|
|
mcp_auth_header="Bearer test_token",
|
|
mcp_servers=None, # Get from all servers
|
|
)
|
|
|
|
# Should return all tools when no restrictions
|
|
assert (
|
|
len(filtered_tools) == 2
|
|
), f"Expected 2 tools, got {len(filtered_tools)}"
|
|
|
|
tool_names = [tool.name for tool in filtered_tools]
|
|
assert "tool_1" in tool_names, "tool_1 should be in filtered results"
|
|
assert "tool_2" in tool_names, "tool_2 should be in filtered results"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_access_group_permission_inheritance_integration():
|
|
"""Integration test for MCP access group permission inheritance"""
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Test scenario: team has access groups, key has no permissions -> should inherit
|
|
# Use direct mocking of the helper functions instead of complex database mocking
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_key"
|
|
) as mock_key:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
|
|
) as mock_team:
|
|
# Key has no permissions, team has servers
|
|
mock_key.return_value = [] # Key inherits nothing directly
|
|
mock_team.return_value = [
|
|
"staff-server-1",
|
|
"staff-server-2",
|
|
"ops-server-1",
|
|
] # Team has servers
|
|
|
|
# Create user auth object
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="test-key",
|
|
user_id="test-user",
|
|
team_id="team-staff",
|
|
object_permission_id=None, # Key has no explicit permissions
|
|
)
|
|
|
|
# Test the inheritance logic
|
|
allowed_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_auth)
|
|
|
|
# Should inherit all team servers since key has no permissions
|
|
expected_servers = ["staff-server-1", "staff-server-2", "ops-server-1"]
|
|
assert sorted(allowed_servers) == sorted(expected_servers)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_access_group_permission_intersection_integration():
|
|
"""Integration test for MCP access group permission intersection"""
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Test scenario: both team and key have access groups -> should intersect
|
|
# Use direct mocking of the helper functions instead of complex database mocking
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_key"
|
|
) as mock_key:
|
|
with patch.object(
|
|
MCPRequestHandler, "_get_allowed_mcp_servers_for_team"
|
|
) as mock_team:
|
|
# Both key and team have permissions - should intersect
|
|
mock_key.return_value = [
|
|
"ops-server",
|
|
"external-server",
|
|
] # Key has these servers
|
|
mock_team.return_value = [
|
|
"staff-server",
|
|
"ops-server",
|
|
"admin-server",
|
|
] # Team has these servers
|
|
|
|
# Create user auth object
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="test-key",
|
|
user_id="test-user",
|
|
team_id="team-staff",
|
|
object_permission_id="key-permission-id", # Key has explicit permissions
|
|
)
|
|
|
|
# Test the intersection logic
|
|
allowed_servers = await MCPRequestHandler.get_allowed_mcp_servers(user_auth)
|
|
|
|
# Should only get intersection (ops-server is common)
|
|
expected_servers = ["ops-server"]
|
|
assert sorted(allowed_servers) == sorted(expected_servers)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mcp_server_manager_with_access_groups_integration():
|
|
"""Integration test for MCPServerManager with access group filtering"""
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
|
|
# Create a test manager
|
|
test_manager = MCPServerManager()
|
|
|
|
# Load servers with access groups
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"staff_server": {
|
|
"url": "https://staff-server.com/mcp",
|
|
"access_groups": ["staff"],
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"ops_server": {
|
|
"url": "https://ops-server.com/mcp",
|
|
"access_groups": ["ops"],
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"admin_server": {
|
|
"url": "https://admin-server.com/mcp",
|
|
"access_groups": ["admin"],
|
|
"transport": MCPTransport.http,
|
|
},
|
|
}
|
|
)
|
|
|
|
# Mock user with specific access groups
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="test-key", user_id="test-user", team_id="team-staff"
|
|
)
|
|
|
|
# Mock the permission lookup to return staff access group
|
|
with patch.object(MCPRequestHandler, "get_allowed_mcp_servers") as mock_get_allowed:
|
|
mock_get_allowed.return_value = [
|
|
"staff-server-id",
|
|
"ops-server-id",
|
|
] # User has access to staff and ops
|
|
|
|
allowed_servers = await test_manager.get_allowed_mcp_servers(user_auth)
|
|
|
|
# Should only get servers user has access to
|
|
assert len(allowed_servers) >= 0 # At least verify no errors
|
|
mock_get_allowed.assert_called_once_with(user_auth)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_allowed_mcp_servers_returns_registry_for_admin():
|
|
from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
|
|
test_manager = MCPServerManager()
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"alpha_server": {
|
|
"url": "https://alpha.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"beta_server": {
|
|
"url": "https://beta.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
}
|
|
)
|
|
|
|
admin_auth = UserAPIKeyAuth(
|
|
api_key="admin-key",
|
|
user_role=LitellmUserRoles.PROXY_ADMIN,
|
|
)
|
|
|
|
with patch.object(
|
|
MCPRequestHandler, "get_allowed_mcp_servers", new_callable=AsyncMock
|
|
) as mock_permission_lookup:
|
|
allowed_servers = await test_manager.get_allowed_mcp_servers(admin_auth)
|
|
|
|
assert set(allowed_servers) == set(test_manager.get_registry().keys())
|
|
mock_permission_lookup.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_allowed_mcp_servers_returns_empty_for_non_admin_without_permissions():
|
|
from litellm.proxy._types import LitellmUserRoles, UserAPIKeyAuth
|
|
from litellm.proxy._experimental.mcp_server.auth.user_api_key_auth_mcp import (
|
|
MCPRequestHandler,
|
|
)
|
|
|
|
test_manager = MCPServerManager()
|
|
await test_manager.load_servers_from_config(
|
|
{
|
|
"alpha_server": {
|
|
"url": "https://alpha.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
"beta_server": {
|
|
"url": "https://beta.server/mcp",
|
|
"transport": MCPTransport.http,
|
|
},
|
|
}
|
|
)
|
|
|
|
user_auth = UserAPIKeyAuth(
|
|
api_key="user-key",
|
|
user_role=LitellmUserRoles.INTERNAL_USER,
|
|
)
|
|
|
|
with patch.object(
|
|
MCPRequestHandler, "get_allowed_mcp_servers", new_callable=AsyncMock
|
|
) as mock_permission_lookup:
|
|
mock_permission_lookup.return_value = []
|
|
allowed_servers = await test_manager.get_allowed_mcp_servers(user_auth)
|
|
|
|
assert allowed_servers == []
|
|
mock_permission_lookup.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_mcp_tool_uses_manager_permission_lookup():
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
call_mcp_tool,
|
|
global_mcp_server_manager,
|
|
)
|
|
|
|
mock_server = MCPServer(
|
|
server_id="server-123",
|
|
name="test_server",
|
|
alias="test_server",
|
|
server_name="test_server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
mcp_info={"server_name": "test_server"},
|
|
)
|
|
|
|
expected_response = [TextContent(type="text", text="ok")]
|
|
|
|
with (
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_allowed_mcp_servers",
|
|
new_callable=AsyncMock,
|
|
) as mock_get_allowed,
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_mcp_server_by_id",
|
|
return_value=mock_server,
|
|
),
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"_get_mcp_server_from_tool_name",
|
|
return_value=mock_server,
|
|
) as mock_get_server,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_tool_registry"
|
|
) as mock_tool_registry,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._handle_managed_mcp_tool",
|
|
new_callable=AsyncMock,
|
|
) as mock_handle_managed,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",
|
|
return_value=True,
|
|
),
|
|
):
|
|
mock_get_allowed.return_value = [mock_server.server_id]
|
|
mock_tool_registry.get_tool.return_value = None
|
|
mock_handle_managed.return_value = expected_response
|
|
|
|
result = await call_mcp_tool(
|
|
name=f"{mock_server.name}/gmail_send_email",
|
|
arguments={"body": "hello"},
|
|
mcp_servers=["test_server"],
|
|
)
|
|
|
|
assert result == expected_response
|
|
mock_get_allowed.assert_awaited_once()
|
|
# We call `_get_mcp_server_from_tool_name` multiple times:
|
|
# - for logging/metadata
|
|
# - for resolving the server during dispatch
|
|
# - and inside `call_tool` for guardrails/hooks
|
|
# The exact count isn't important, only that it is used.
|
|
assert mock_get_server.call_count >= 2
|
|
# First call should use the prefixed tool name
|
|
assert (
|
|
mock_get_server.call_args_list[0][0][0]
|
|
== f"{mock_server.name}/gmail_send_email"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_mcp_tool_resolves_unprefixed_tool_name_and_checks_permissions():
|
|
"""
|
|
Ensure `call_mcp_tool` correctly resolves the MCP server for an unprefixed tool
|
|
name and enforces server-level permissions using that resolved server.
|
|
"""
|
|
from litellm.proxy._experimental.mcp_server.server import (
|
|
call_mcp_tool,
|
|
global_mcp_server_manager,
|
|
)
|
|
|
|
mock_server = MCPServer(
|
|
server_id="server-123",
|
|
name="test_server",
|
|
alias="test_server",
|
|
server_name="test_server",
|
|
url="https://test-server.com/mcp",
|
|
transport=MCPTransport.http,
|
|
mcp_info={"server_name": "test_server"},
|
|
)
|
|
|
|
expected_response = [TextContent(type="text", text="ok")]
|
|
|
|
with (
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_allowed_mcp_servers",
|
|
new_callable=AsyncMock,
|
|
) as mock_get_allowed,
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"get_mcp_server_by_id",
|
|
return_value=mock_server,
|
|
),
|
|
patch.object(
|
|
global_mcp_server_manager,
|
|
"_get_mcp_server_from_tool_name",
|
|
return_value=mock_server,
|
|
) as mock_get_server,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.global_mcp_tool_registry"
|
|
) as mock_tool_registry,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server._handle_managed_mcp_tool",
|
|
new_callable=AsyncMock,
|
|
) as mock_handle_managed,
|
|
patch(
|
|
"litellm.proxy._experimental.mcp_server.server.MCPRequestHandler.is_tool_allowed",
|
|
return_value=True,
|
|
) as mock_is_allowed,
|
|
):
|
|
mock_get_allowed.return_value = [mock_server.server_id]
|
|
mock_tool_registry.get_tool.return_value = None
|
|
mock_handle_managed.return_value = expected_response
|
|
|
|
# Call with UNPREFIXED tool name; server should be resolved via mapping
|
|
result = await call_mcp_tool(
|
|
name="gmail_send_email",
|
|
arguments={"body": "hello"},
|
|
mcp_servers=["test_server"],
|
|
)
|
|
|
|
assert result == expected_response
|
|
mock_get_allowed.assert_awaited_once()
|
|
# We should resolve the server at least once using the unprefixed name
|
|
assert mock_get_server.call_count >= 1
|
|
assert mock_get_server.call_args_list[0][0][0] == "gmail_send_email"
|
|
# Permissions check should be invoked with the resolved server name
|
|
mock_is_allowed.assert_called_once()
|