Files
2026-11-22 04:45:52 -08:00

163 lines
5.8 KiB
Python

import asyncio
import uuid
import json
from typing import Any, Dict, Union, List, Optional
from starlette.responses import Response
from starlette.websockets import WebSocket
from tools.utils import ToolError
class MCPBridge:
"""
The Bridge between MCP clients (LLMs) and the Firefox Extension.
Manages:
- SSE sessions for MCP clients
- WebSocket connection from the Firefox extension
- Correlation of MCP tool calls with extension responses
"""
def __init__(self):
# SSE sessions: session_id -> asyncio.Queue
self.sessions: Dict[str, asyncio.Queue] = {}
self.running = True
# WebSocket connection from the Firefox extension
self.extension_ws: Optional[WebSocket] = None
# Pending requests: request_id -> asyncio.Future
self.pending_requests: Dict[str, asyncio.Future] = {}
# ------------------------------------------------------------------
# SSE session management
# ------------------------------------------------------------------
def create_session(self) -> str:
sid = str(uuid.uuid4())
self.sessions[sid] = asyncio.Queue()
return sid
async def send_to_session(self, sid: str, message: Dict[str, Any]):
if sid in self.sessions:
await self.sessions[sid].put(json.dumps(message))
# ------------------------------------------------------------------
# Extension WebSocket management
# ------------------------------------------------------------------
def set_extension_websocket(self, ws: WebSocket):
self.extension_ws = ws
def remove_extension_websocket(self):
self.extension_ws = None
# Cancel all pending requests since the extension is gone
for fut in self.pending_requests.values():
if not fut.done():
fut.set_exception(Exception("Firefox extension disconnected"))
self.pending_requests.clear()
# ------------------------------------------------------------------
# Send a request to the extension and wait for its response
# ------------------------------------------------------------------
async def send_to_extension(
self,
request_id: str,
action: str,
params: Dict[str, Any],
timeout: float = 30.0,
) -> Any:
if not self.extension_ws:
raise ToolError(
"Firefox extension is not connected. "
"Load the extension in Firefox (about:debugging) and ensure it connects to ws://127.0.0.1:8008/ws"
)
loop = asyncio.get_event_loop()
future: asyncio.Future = loop.create_future()
self.pending_requests[request_id] = future
message = json.dumps({
"type": "request",
"request_id": request_id,
"action": action,
"params": params,
})
try:
await self.extension_ws.send_text(message)
result = await asyncio.wait_for(future, timeout=timeout)
return result
except asyncio.TimeoutError:
raise ToolError(f"Extension did not respond to '{action}' within {timeout:.0f} seconds")
finally:
self.pending_requests.pop(request_id, None)
# ------------------------------------------------------------------
# Called by the WebSocket handler when the extension responds
# ------------------------------------------------------------------
def handle_extension_response(self, request_id: str, result: Any = None, error: Optional[str] = None):
future = self.pending_requests.get(request_id)
if future and not future.done():
if error:
future.set_exception(Exception(error))
else:
future.set_result(result)
# ------------------------------------------------------------------
# MCP protocol request handling
# ------------------------------------------------------------------
async def handle_request(
self,
method: str,
params: Dict[str, Any],
req_id: Any,
tool_registry: List[Any],
) -> Union[Dict[str, Any], Response]:
if method == "initialize":
return {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "FirefoxMCP", "version": "0.1.0"},
}
if method == "tools/list":
return {"tools": [t.to_mcp_dict() for t in tool_registry]}
if method == "tools/call":
name = params.get("name")
args = params.get("arguments", {})
tool = next((t for t in tool_registry if t.name == name), None)
if not tool:
return Response(
content=json.dumps(
{
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32601, "message": f"Tool {name} not found"},
}
),
media_type="application/json",
)
try:
# Pass the bridge instance as the second argument so tools can
# send commands to the Firefox extension.
content = await tool.handler(args, self)
except ToolError as e:
content = [{"type": "text", "text": str(e)}]
except Exception as e:
content = [{"type": "text", "text": f"Unexpected internal error: {str(e)}"}]
return {"content": content}
return Response(
content=json.dumps(
{
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32601, "message": f"Method {method} not found"},
}
),
media_type="application/json",
)