Skip to content

Commit 4748050

Browse files

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

backend/api/routers/mcps.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
from contextlib import asynccontextmanager
2+
from typing import Iterable
3+
4+
from config import settings
5+
from fastapi import APIRouter
6+
from mcp import ClientSession, types
7+
from mcp.client.sse import sse_client
8+
9+
from shared_mcp.models import ToolRequest
10+
11+
router = APIRouter(prefix="/mcps", tags=["mcps"])
12+
13+
14+
@asynccontextmanager
15+
async def mcp_sse_client():
16+
async with sse_client(f"http://mcp:{settings.mcp_server_port}/sse") as (
17+
read_stream,
18+
write_stream,
19+
):
20+
async with ClientSession(read_stream, write_stream) as session:
21+
await session.initialize()
22+
yield session
23+
24+
25+
@router.get("/list-tools")
26+
async def list_tools() -> Iterable[types.Tool]:
27+
"""
28+
Lists tools available from MCP server
29+
30+
This endpoint establishes a Server-Sent Events connection with the client
31+
and forwards communication to the Model Context Protocol server.
32+
"""
33+
async with mcp_sse_client() as session:
34+
response = await session.list_tools()
35+
return response.tools
36+
37+
38+
@router.post("/call-tool")
39+
async def call_tool(request: ToolRequest) -> str:
40+
"""
41+
Calls tool available from MCP server
42+
43+
This endpoint establishes a Server-Sent Events connection with the client
44+
and forwards communication to the Model Context Protocol server.
45+
"""
46+
async with mcp_sse_client() as session:
47+
response = await session.call_tool(
48+
request.tool_name,
49+
arguments=request.model_dump(exclude=["tool_name"]),
50+
)
51+
return response.content[0].text

0 commit comments

Comments
 (0)