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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
add litellm mcp endpoints
Ishaan Jaff7826c9bd218f
diff --git a/litellm/proxy/_experimental/mcp_server/mcp_routes.py b/litellm/proxy/_experimental/mcp_server/mcp_routes.pyindex 4b6c1581151..29041eab97c 100644--- a/litellm/proxy/_experimental/mcp_server/mcp_routes.py+++ b/litellm/proxy/_experimental/mcp_server/mcp_routes.py@@ -2,75 +2,106 @@LiteLLM MCP Server Routes"""-from typing import Optional+import asyncio-from fastapi import APIRouter, HTTPException+import mcp.types as types+from anyio import BrokenResourceError+from fastapi import APIRouter, HTTPException, Request+from fastapi.responses import StreamingResponse+from mcp.server import NotificationOptions, Server+from mcp.server.models import InitializationOptions+from pydantic import ValidationError+from litellm._logging import verbose_loggerfrom litellm.proxy._experimental.mcp_server.tool_registry import (global_mcp_tool_registry,)from litellm.types.mcp_server.tool_registry import *+from .sse_transport import SseServerTransport++########################################################+############ Initialize the MCP Server #################+########################################################router = APIRouter(prefix="/mcp",tags=["mcp"],)+server = Server("litellm-mcp-server")+sse = SseServerTransport("/mcp/sse/messages")-[email protected]("/")-async def root():- return {"message": "MCP Server is running"}+########################################################+############### MCP Server Routes #######################+########################################################[email protected]("/tools/list", response_model=ListToolsResponse)-async def list_tools(cursor: Optional[str] = None):[email protected]_tools()+async def list_tools() -> list[types.Tool]:"""List all available tools"""tools = []for tool in global_mcp_tool_registry.list_tools():tools.append(- ToolSchema(+ types.Tool(name=tool.name,description=tool.description,inputSchema=tool.input_schema,))- return ListToolsResponse(tools=tools)+ return tools[email protected]("/tools/call", response_model=CallToolResponse)-async def call_tool(request: CallToolRequest):[email protected]_tool()+async def handle_call_tool(+ name: str, arguments: dict | None+) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:"""Call a specific tool with the provided arguments"""- if request.method != "tools/call":- raise HTTPException(status_code=400, detail="Invalid method")-- if "name" not in request.params:- raise HTTPException(status_code=400, detail="Tool name is required")-- tool_name = request.params["name"]- arguments = request.params.get("arguments", {})-- tool = global_mcp_tool_registry.get_tool(tool_name)+ tool = global_mcp_tool_registry.get_tool(name)if not tool:- raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")+ raise HTTPException(status_code=404, detail=f"Tool '{name}' not found")+ if arguments is None:+ raise HTTPException(status_code=400, detail="Request arguments are required")try:result = tool.handler(**arguments)-- # Convert result to text content- if isinstance(result, str):- content = [ContentItem(type="text", text=result)]- elif isinstance(result, dict):- content = [ContentItem(type="text", text=str(result))]- else:- content = [ContentItem(type="text", text=str(result))]-- return CallToolResponse(content=content)+ return [types.TextContent(text=str(result), type="text")]except Exception as e:- return CallToolResponse(- content=[ContentItem(type="text", text=f"Error: {str(e)}")], isError=True- )+ return [types.TextContent(text=f"Error: {str(e)}", type="text")]++[email protected]("/", response_class=StreamingResponse)+async def handle_sse(request: Request):+ verbose_logger.info("new incoming SSE connection established")+ async with sse.connect_sse(request) as streams:+ try:+ await server.run(streams[0], streams[1], options)+ except BrokenResourceError:+ pass+ except asyncio.CancelledError:+ pass+ except ValidationError:+ pass+ except Exception:+ raise+ await request.close()++[email protected]("/sse/messages")+async def handle_messages(request: Request):+ verbose_logger.info("incoming SSE message received")+ await sse.handle_post_message(request.scope, request.receive, request._send)+ await request.close()+++options = InitializationOptions(+ server_name="litellm-mcp-server",+ server_version="0.1.0",+ capabilities=server.get_capabilities(+ notification_options=NotificationOptions(),+ experimental_capabilities={},+ ),+)diff --git a/litellm/proxy/_experimental/mcp_server/sse_transport.py b/litellm/proxy/_experimental/mcp_server/sse_transport.pynew file mode 100644index 00000000000..05a75b3b8a9--- /dev/null+++ b/litellm/proxy/_experimental/mcp_server/sse_transport.py@@ -0,0 +1,148 @@+"""+This is a modification of code from: https://github.com/SecretiveShell/MCP-Bridge/blob/master/mcp_bridge/mcp_server/sse_transport.py++Credit to the maintainers of SecretiveShell for their SSE Transport implementation++"""++from contextlib import asynccontextmanager+from typing import Any+from urllib.parse import quote+from uuid import UUID, uuid4++import anyio+import mcp.types as types+from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream+from fastapi.requests import Request+from fastapi.responses import Response+from pydantic import ValidationError+from sse_starlette import EventSourceResponse+from starlette.types import Receive, Scope, Send++from litellm._logging import verbose_logger+++class SseServerTransport:+ """+ SSE server transport for MCP. This class provides _two_ ASGI applications,+ suitable to be used with a framework like Starlette and a server like Hypercorn:++ 1. connect_sse() is an ASGI application which receives incoming GET requests,+ and sets up a new SSE stream to send server messages to the client.+ 2. handle_post_message() is an ASGI application which receives incoming POST+ requests, which should contain client messages that link to a+ previously-established SSE session.+ """++ _endpoint: str+ _read_stream_writers: dict[+ UUID, MemoryObjectSendStream[types.JSONRPCMessage | Exception]+ ]++ def __init__(self, endpoint: str) -> None:+ """+ Creates a new SSE server transport, which will direct the client to POST+ messages to the relative or absolute URL given.+ """++ super().__init__()+ self._endpoint = endpoint+ self._read_stream_writers = {}+ verbose_logger.debug(+ f"SseServerTransport initialized with endpoint: {endpoint}"+ )++ @asynccontextmanager+ async def connect_sse(self, request: Request):+ if request.scope["type"] != "http":+ verbose_logger.error("connect_sse received non-HTTP request")+ raise ValueError("connect_sse can only handle HTTP requests")++ verbose_logger.debug("Setting up SSE connection")+ read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception]+ read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception]++ write_stream: MemoryObjectSendStream[types.JSONRPCMessage]+ write_stream_reader: MemoryObjectReceiveStream[types.JSONRPCMessage]++ read_stream_writer, read_stream = anyio.create_memory_object_stream(0)+ write_stream, write_stream_reader = anyio.create_memory_object_stream(0)++ session_id = uuid4()+ session_uri = f"{quote(self._endpoint)}?session_id={session_id.hex}"+ self._read_stream_writers[session_id] = read_stream_writer+ verbose_logger.debug(f"Created new session with ID: {session_id}")++ sse_stream_writer, sse_stream_reader = anyio.create_memory_object_stream(+ 0, dict[str, Any]+ )++ async def sse_writer():+ verbose_logger.debug("Starting SSE writer")+ async with sse_stream_writer, write_stream_reader:+ await sse_stream_writer.send({"event": "endpoint", "data": session_uri})+ verbose_logger.debug(f"Sent endpoint event: {session_uri}")++ async for message in write_stream_reader:+ verbose_logger.debug(f"Sending message via SSE: {message}")+ await sse_stream_writer.send(+ {+ "event": "message",+ "data": message.model_dump_json(+ by_alias=True, exclude_none=True+ ),+ }+ )++ async with anyio.create_task_group() as tg:+ response = EventSourceResponse(+ content=sse_stream_reader, data_sender_callable=sse_writer+ )+ verbose_logger.debug("Starting SSE response task")+ tg.start_soon(response, request.scope, request.receive, request._send)++ verbose_logger.debug("Yielding read and write streams")+ yield (read_stream, write_stream)++ async def handle_post_message(+ self, scope: Scope, receive: Receive, send: Send+ ) -> Response:+ verbose_logger.debug("Handling POST message")+ request = Request(scope, receive)++ session_id_param = request.query_params.get("session_id")+ if session_id_param is None:+ verbose_logger.warning("Received request without session_id")+ response = Response("session_id is required", status_code=400)+ return response++ try:+ session_id = UUID(hex=session_id_param)+ verbose_logger.debug(f"Parsed session ID: {session_id}")+ except ValueError:+ verbose_logger.warning(f"Received invalid session ID: {session_id_param}")+ response = Response("Invalid session ID", status_code=400)+ return response++ writer = self._read_stream_writers.get(session_id)+ if not writer:+ verbose_logger.warning(f"Could not find session for ID: {session_id}")+ response = Response("Could not find session", status_code=404)+ return response++ json = await request.json()+ verbose_logger.debug(f"Received JSON: {json}")++ try:+ message = types.JSONRPCMessage.model_validate(json)+ verbose_logger.debug(f"Validated client message: {message}")+ except ValidationError as err:+ verbose_logger.error(f"Failed to parse message: {err}")+ response = Response("Could not parse message", status_code=400)+ await writer.send(err)+ return response++ verbose_logger.debug(f"Sending message to writer: {message}")+ response = Response("Accepted", status_code=202)+ await writer.send(message)+ return responsediff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex bca2b96cb49..26ce6cb8f84 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -7,8 +7,6 @@ model_list:api_key: os.environ/AZURE_API_KEY-litellm_settings:- callbacks: ["custom_prompt_management.x42_prompt_management"]mcp_tools:- name: "get_current_time"diff --git a/litellm/types/mcp_server/tool_registry.py b/litellm/types/mcp_server/tool_registry.pyindex 266159343df..9ff06ec3514 100644--- a/litellm/types/mcp_server/tool_registry.py+++ b/litellm/types/mcp_server/tool_registry.py@@ -30,9 +30,3 @@ class CallToolRequest(BaseModel):class ContentItem(BaseModel):type: strtext: Optional[str] = None---class CallToolResponse(BaseModel):- content: List[ContentItem]- isError: Optional[bool] = None- _meta: Optional[Dict[str, Any]] = Nonediff --git a/tests/pass_through_tests/test_mcp_routes.py b/tests/pass_through_tests/test_mcp_routes.pyindex 69ae1b85227..687efe6195d 100644--- a/tests/pass_through_tests/test_mcp_routes.py+++ b/tests/pass_through_tests/test_mcp_routes.py@@ -12,13 +12,17 @@ from mcp.client.sse import sse_clientasync def main():model = ChatOpenAI(model="gpt-4o", api_key="sk-12")- async with sse_client(url="http://localhost:8000/mcp/") as (read, write):+ async with sse_client(url="http://localhost:4000/mcp/") as (read, write):async with ClientSession(read, write) as session:# Initialize the connection+ print("Initializing session")await session.initialize()+ print("Session initialized")# Get tools+ print("Loading tools")tools = await load_mcp_tools(session)+ print("Tools loaded")print(tools)# # Create and run the agent