Compost / backend /routers /mcp.py
abc1181's picture
Refactor: use Composio Core SDK as backend engine
dc0fe62
Raw
History Blame Contribute Delete
2.99 kB
from fastapi import APIRouter, Request, HTTPException, Depends
from sqlalchemy.orm import Session
from backend.database import get_db
from backend.composio_client import get_composio
import os
router = APIRouter()
@router.post("/v1/endpoint")
async def mcp_endpoint(request: Request):
composio = get_composio()
body = await request.json()
method = body.get("method")
params = body.get("params", {})
if method == "initialize":
return {
"jsonrpc": "2.0", "id": body.get("id"),
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "Compost MCP Server", "version": "1.0.0"}
}
}
if method == "tools/list":
tools = []
if composio:
try:
raw = composio.toolkits.get()
for tk in raw:
slug = tk.slug if hasattr(tk, "slug") else (tk.get("slug") if isinstance(tk, dict) else "")
if not slug:
continue
try:
tls = composio.tools.get_raw_composio_tools(toolkits=[slug], limit=100)
for t in tls:
t_d = t.model_dump(mode="json") if hasattr(t, "model_dump") else {}
tools.append({
"name": t_d.get("slug", ""),
"description": t_d.get("description", ""),
"inputSchema": t_d.get("input_parameters", {"type": "object", "properties": {}})
})
except Exception:
pass
except Exception:
pass
return {"jsonrpc": "2.0", "id": body.get("id"), "result": {"tools": tools}}
if method == "tools/call":
tool_name = params.get("name")
arguments = params.get("arguments", {})
if composio:
try:
resp = composio.tools.execute(
slug=tool_name, arguments=arguments,
dangerously_skip_version_check=True,
)
data = resp.get("data", resp) if isinstance(resp, dict) else {}
return {"jsonrpc": "2.0", "id": body.get("id"), "result": {"content": [{"type": "text", "text": str(data)}]}}
except Exception as e:
return {"jsonrpc": "2.0", "id": body.get("id"), "error": {"code": -32603, "message": str(e)}}
return {"jsonrpc": "2.0", "id": body.get("id"), "result": {"content": [{"type": "text", "text": f"Executed {tool_name}"}]}}
return {"jsonrpc": "2.0", "id": body.get("id"), "error": {"code": -32601, "message": "Method not found"}}
@router.get("/v1/discovery")
async def mcp_discovery():
host = os.environ.get("MCP_HOST", "localhost:7860")
return {"mcpServers": {"compost": {"url": f"http://{host}/mcp/v1/endpoint"}}}