Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test: MCP E2E streamable_http

Yuta Saitoc2b5e9c6697e
diff --git a/tests/mcp_tests/mcp_server.py b/tests/mcp_tests/mcp_server.py
index 99a67edd021..c4daff4ab1c 100644
--- a/tests/mcp_tests/mcp_server.py
+++ b/tests/mcp_tests/mcp_server.py
@@ -1,9 +1,35 @@
# math_server.py
+from __future__ import annotations
+
+import argparse
+import os
+
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Math")
+def _parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description="MCP math test server")
+ parser.add_argument(
+ "--transport",
+ default=os.getenv("MCP_TRANSPORT", "stdio"),
+ help="Transport to use (stdio or http)",
+ )
+ parser.add_argument(
+ "--host",
+ default=os.getenv("MCP_HOST", "127.0.0.1"),
+ help="Host to bind when serving over HTTP",
+ )
+ parser.add_argument(
+ "--port",
+ type=int,
+ default=int(os.getenv("MCP_PORT", "0")),
+ help="Port to bind when serving over HTTP",
+ )
+ return parser.parse_args()
+
+
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers"""
@@ -16,5 +42,24 @@ def multiply(a: int, b: int) -> int:
return a * b
+def main() -> None:
+ args = _parse_args()
+ transport = (args.transport or "stdio").lower()
+
+ if transport == "stdio":
+ mcp.run(transport="stdio")
+ return
+
+ if transport in {"http", "streamable_http", "streamable-http"}:
+ if args.port <= 0:
+ raise ValueError("HTTP transport requires a valid --port value")
+ mcp.settings.host = args.host
+ mcp.settings.port = args.port
+ mcp.run(transport="streamable-http")
+ return
+
+ raise ValueError(f"Unsupported transport: {transport}")
+
+
if __name__ == "__main__":
- mcp.run(transport="stdio")
+ main()
diff --git a/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml b/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
index 06d0878f788..37d5359e3ce 100644
--- a/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
+++ b/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
@@ -18,3 +18,6 @@ mcp_servers:
command: python3
args:
- tests/mcp_tests/mcp_server.py
+ math_streamable_http:
+ transport: http
+ url: http://127.0.0.1:0/mcp
diff --git a/tests/mcp_tests/test_proxy_mcp_e2e.py b/tests/mcp_tests/test_proxy_mcp_e2e.py
index 44d340dbcb7..8fbd80b8d62 100644
--- a/tests/mcp_tests/test_proxy_mcp_e2e.py
+++ b/tests/mcp_tests/test_proxy_mcp_e2e.py
@@ -1,11 +1,16 @@
import asyncio
+import os
import socket
+import subprocess
+import sys
import threading
import time
+import typing
from pathlib import Path
import pytest
import uvicorn
+import yaml
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
@@ -17,11 +22,28 @@ from litellm.proxy.proxy_server import (
CONFIG_TEMPLATE_PATH = Path("tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml")
+MCP_SERVER_SCRIPT = Path("tests/mcp_tests/mcp_server.py")
+PROJECT_ROOT = Path(__file__).resolve().parents[2]
PROXY_START_TIMEOUT = 30
MCP_HEADERS = {
"Authorization": "Bearer sk-1234",
"x-mcp-servers": "math_stdio",
}
+STREAMABLE_HTTP_HEADERS = {
+ "Authorization": "Bearer sk-1234",
+ "x-mcp-servers": "math_streamable_http",
+}
+
+
[email protected](scope="session", autouse=True)
+def _clear_proxy_database_env() -> typing.Iterator[None]:
+ """Ensure local proxy DB settings don't leak into tests."""
+ mp = pytest.MonkeyPatch()
+ mp.delenv("DATABASE_URL", raising=False)
+ try:
+ yield
+ finally:
+ mp.undo()
def _initialize_proxy(config_path: str) -> None:
@@ -60,10 +82,67 @@ def _start_proxy_server(config_path: str) -> tuple[str, uvicorn.Server, threadin
@pytest.fixture(scope="session")
-def proxy_server_url(tmp_path_factory: pytest.TempPathFactory):
+def math_streamable_http_server() -> str:
+ host = "127.0.0.1"
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+ sock.bind((host, 0))
+ _, port = sock.getsockname()
+
+ cmd = [
+ sys.executable,
+ str(MCP_SERVER_SCRIPT),
+ "--transport",
+ "http",
+ "--host",
+ host,
+ "--port",
+ str(port),
+ ]
+
+ env = os.environ.copy()
+ server_process = subprocess.Popen(
+ cmd,
+ cwd=str(PROJECT_ROOT),
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ start_time = time.time()
+ while True:
+ if server_process.poll() is not None:
+ stdout, stderr = server_process.communicate()
+ raise RuntimeError(
+ f"Streamable HTTP MCP server exited early.\nSTDOUT: {stdout.decode()}\nSTDERR: {stderr.decode()}"
+ )
+ try:
+ with socket.create_connection((host, port), timeout=0.1):
+ break
+ except OSError:
+ if time.time() - start_time > PROXY_START_TIMEOUT:
+ server_process.terminate()
+ raise TimeoutError("Streamable HTTP MCP server did not start in time")
+ time.sleep(0.05)
+
+ yield f"http://{host}:{port}"
+
+ server_process.terminate()
+ try:
+ server_process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ server_process.kill()
+
+
[email protected](scope="session")
+def proxy_server_url(
+ tmp_path_factory: pytest.TempPathFactory, math_streamable_http_server: str
+):
config_dir = tmp_path_factory.mktemp("mcp_e2e")
config_path = config_dir / "config.yaml"
- config_path.write_text(CONFIG_TEMPLATE_PATH.read_text())
+ config = yaml.safe_load(CONFIG_TEMPLATE_PATH.read_text())
+ config["mcp_servers"]["math_streamable_http"][
+ "url"
+ ] = f"{math_streamable_http_server}/mcp"
+ config_path.write_text(yaml.safe_dump(config))
server_url, server, thread, sock = _start_proxy_server(str(config_path))
@@ -74,21 +153,81 @@ def proxy_server_url(tmp_path_factory: pytest.TempPathFactory):
sock.close()
-async def test_proxy_mcp_stdio_roundtrip(proxy_server_url: str) -> None:
- async with asyncio.timeout(20):
- async with streamablehttp_client(
- url=f"{proxy_server_url}/mcp", headers=MCP_HEADERS
- ) as (read, write, _get_session_id):
- async with ClientSession(read, write) as session:
- await session.initialize()
- tools_result = await session.list_tools()
- assert any(tool.name.endswith("add") for tool in tools_result.tools)
-
- result = await session.call_tool(
- "add", arguments={"a": 3, "b": 4}
- )
- assert result.content
- first_content = result.content[0]
- text = getattr(first_content, "text", None)
- assert text == "7"
+class TestProxyMcpSimpleConnections:
+ @pytest.mark.asyncio
+ async def test_proxy_mcp_stdio_roundtrip(self, proxy_server_url: str) -> None:
+ async with asyncio.timeout(20):
+ async with streamablehttp_client(
+ url=f"{proxy_server_url}/mcp", headers=MCP_HEADERS
+ ) as (read, write, _get_session_id):
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ tools_result = await session.list_tools()
+ assert any(tool.name.endswith("add") for tool in tools_result.tools)
+
+ result = await session.call_tool(
+ "add", arguments={"a": 3, "b": 4}
+ )
+ assert result.content
+ first_content = result.content[0]
+ text = getattr(first_content, "text", None)
+ assert text == "7"
+
+ @pytest.mark.asyncio
+ async def test_proxy_mcp_streamable_http_roundtrip(
+ self, proxy_server_url: str
+ ) -> None:
+ async with asyncio.timeout(20):
+ async with streamablehttp_client(
+ url=f"{proxy_server_url}/mcp", headers=STREAMABLE_HTTP_HEADERS
+ ) as (read, write, _get_session_id):
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ tools_result = await session.list_tools()
+ assert any(tool.name.endswith("add") for tool in tools_result.tools)
+
+ result = await session.call_tool(
+ "add", arguments={"a": 5, "b": 6}
+ )
+ assert result.content
+ first_content = result.content[0]
+ text = getattr(first_content, "text", None)
+ assert text == "11"
+
+ @pytest.mark.asyncio
+ async def test_proxy_mcp_lists_all_servers_without_header(
+ self, proxy_server_url: str
+ ) -> None:
+ async with asyncio.timeout(20):
+ async with streamablehttp_client(
+ url=f"{proxy_server_url}/mcp",
+ headers={"Authorization": "Bearer sk-1234"},
+ ) as (read, write, _get_session_id):
+ async with ClientSession(read, write) as session:
+ await session.initialize()
+ tools_result = await session.list_tools()
+ tool_names = {tool.name for tool in tools_result.tools}
+ expected_tool_names = {
+ "math_stdio-add",
+ "math_stdio-multiply",
+ "math_streamable_http-add",
+ "math_streamable_http-multiply",
+ }
+ assert expected_tool_names <= tool_names
+
+ async def _call_and_get_text(
+ tool_name: str, *, a: int, b: int
+ ) -> str | None:
+ result = await session.call_tool(tool_name, arguments={"a": a, "b": b})
+ assert result.content
+ first_content = result.content[0]
+ return getattr(first_content, "text", None)
+
+ stdio_result = await _call_and_get_text(
+ "math_stdio-add", a=2, b=3
+ )
+ streamable_result = await _call_and_get_text(
+ "math_streamable_http-add", a=4, b=5
+ )
+ assert stdio_result == "5"
+ assert streamable_result == "9"