litellm/tests/mcp_tests/test_mcp_litellm_client.py
yuneng-jiang 6a0d03914c
test: drop the cwd-relative sys.path.insert calls from the test suite (#37802)
* test: drop the cwd-relative sys.path.insert calls from the test suite

TQ003 stands at 1,077 across 1,058 files, and 1,015 of them are the same shape:
sys.path.insert(0, os.path.abspath("../..")) and its deeper siblings. The
argument resolves against the working directory rather than the file, so from
the repo root, where every job runs pytest, it inserts the directory two levels
above the checkout. It has never pointed at litellm. The package is installed
into the environment anyway, which is what actually makes the import work, and
what the rule's message has said all along.

Removing them leaves 1,634 imports of sys and os with no remaining reference,
and those go too, except where another test module imports the name back out of
the file. The rest of TQ003 is 62 call sites that resolve against __file__ or a
variable, which are a different question and are left alone.

Collection is identical either way: 45,871 tests and the same 51 pre-existing
collection errors before and after, and ruff reports no new undefined name.

* test: drop the duplicate imports the sys.path sweep exposed to F811

* test(pre-call-utils): restore the os import the new bedrock tests need
2026-08-22 09:25:58 -07:00

108 lines
4.1 KiB
Python

# Create server parameters for stdio connection
import os
import pytest
import asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from litellm import experimental_mcp_client
import litellm
import json
@pytest.mark.xfail(
reason="Fails due to missing 'mcp' package and connection issues in CI/local env."
)
@pytest.mark.asyncio
async def test_mcp_agent():
"""Test MCP agent functionality with a simple math server"""
try:
local_server_path = "./mcp_server.py"
ci_cd_server_path = "tests/mcp_tests/mcp_server.py"
# Use the correct path for the server
server_path = (
ci_cd_server_path
if os.path.exists(ci_cd_server_path)
else local_server_path
)
if not os.path.exists(server_path):
pytest.skip(f"MCP server file not found at {server_path}")
server_params = StdioServerParameters(
command="python3",
args=[server_path],
)
# Add timeout to prevent hanging
async with asyncio.timeout(30): # 30 second timeout
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
# Get tools
tools = await experimental_mcp_client.load_mcp_tools(
session=session, format="openai"
)
print("MCP TOOLS: ", tools)
# Create and run the agent
messages = [{"role": "user", "content": "what's (3 + 5)"}]
llm_response = await litellm.acompletion(
model="gpt-4o",
api_key=os.getenv("OPENAI_API_KEY"),
messages=messages,
tools=tools,
tool_choice="required",
)
print(
"LLM RESPONSE: ",
json.dumps(llm_response, indent=4, default=str),
)
# Add assertions to verify the response
assert (
llm_response["choices"][0]["message"]["tool_calls"] is not None
)
assert (
llm_response["choices"][0]["message"]["tool_calls"][0][
"function"
]["name"]
== "add"
)
openai_tool = llm_response["choices"][0]["message"]["tool_calls"][0]
# Call the tool using MCP client
call_result = await experimental_mcp_client.call_openai_tool(
session=session,
openai_tool=openai_tool,
)
print("CALL RESULT: ", call_result)
# send the tool result to the LLM
messages.append(llm_response["choices"][0]["message"])
messages.append(
{
"role": "tool",
"content": str(call_result.content[0].text),
"tool_call_id": openai_tool["id"],
}
)
print("final messages: ", messages)
llm_response = await litellm.acompletion(
model="gpt-4o",
api_key=os.getenv("OPENAI_API_KEY"),
messages=messages,
tools=tools,
)
print(
"FINAL LLM RESPONSE: ",
json.dumps(llm_response, indent=4, default=str),
)
except asyncio.TimeoutError:
pytest.skip("MCP server connection timed out - skipping test")
except Exception as e:
pytest.skip(f"MCP test failed with error: {str(e)} - skipping test")