Files
2026-11-22 17:32:59 -08:00

327 lines
9.5 KiB
JavaScript

/*
* Firefox MCP Bridge - Background Script
*
* Connects to the Python bridge via WebSocket and relays commands
* between the bridge and the content scripts running in web pages.
*/
const WS_URL = "ws://127.0.0.1:8008/ws";
let ws = null;
let reconnectTimer = null;
let heartbeatTimer = null;
const RECONNECT_DELAY = 2000;
const HEARTBEAT_INTERVAL = 30000;
// ------------------------------------------------------------------
// WebSocket connection to the Python bridge
// ------------------------------------------------------------------
function connect() {
if (ws && ws.readyState === WebSocket.OPEN) {
return;
}
ws = new WebSocket(WS_URL);
ws.onopen = () => {
console.log("[MCP Bridge] WebSocket connected to Python bridge");
if (reconnectTimer) {
clearInterval(reconnectTimer);
reconnectTimer = null;
}
startHeartbeat();
};
ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data);
if (msg.type === "request") {
handleRequest(msg);
} else if (msg.type === "pong") {
// Heartbeat response
}
} catch (err) {
console.error("[MCP Bridge] Failed to parse message from bridge:", err);
}
};
ws.onclose = () => {
console.log("[MCP Bridge] WebSocket disconnected");
ws = null;
stopHeartbeat();
scheduleReconnect();
};
ws.onerror = (err) => {
console.error("[MCP Bridge] WebSocket error:", err);
ws.close();
};
}
function scheduleReconnect() {
if (reconnectTimer) return;
console.log("[MCP Bridge] Reconnecting in " + RECONNECT_DELAY + "ms...");
reconnectTimer = setInterval(() => {
connect();
if (ws && ws.readyState === WebSocket.OPEN) {
clearInterval(reconnectTimer);
reconnectTimer = null;
}
}, RECONNECT_DELAY);
}
// ------------------------------------------------------------------
// Heartbeat
// ------------------------------------------------------------------
function startHeartbeat() {
stopHeartbeat();
heartbeatTimer = setInterval(() => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: "ping" }));
}
}, HEARTBEAT_INTERVAL);
}
function stopHeartbeat() {
if (heartbeatTimer) {
clearInterval(heartbeatTimer);
heartbeatTimer = null;
}
}
// ------------------------------------------------------------------
// Send response back to Python bridge
// ------------------------------------------------------------------
function sendResponse(requestId, payload) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
type: "response",
request_id: requestId,
...payload,
}));
}
}
// ------------------------------------------------------------------
// Resolve a target tab: by tab_id, or by window_id + active, or focused window
// ------------------------------------------------------------------
async function resolveTarget(tabId, windowId) {
let tab;
if (tabId) {
tab = await browser.tabs.get(tabId);
if (!tab) throw new Error(`Tab ${tabId} not found`);
} else if (windowId) {
const tabs = await browser.tabs.query({ windowId, active: true });
if (!tabs || tabs.length === 0) {
throw new Error(`No active tab in window ${windowId}`);
}
tab = tabs[0];
} else {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
if (!tabs || tabs.length === 0) {
throw new Error("No active tab found");
}
tab = tabs[0];
}
return tab;
}
// ------------------------------------------------------------------
// Execute a function in a specific tab's content script
// ------------------------------------------------------------------
async function execInTab(tabId, windowId, functionName, args) {
const tab = await resolveTarget(tabId, windowId);
try {
const response = await browser.tabs.sendMessage(tab.id, {
type: "mcp_call",
function: functionName,
args: args,
});
if (response && response.error) {
throw new Error(response.error);
}
return response && response.result;
} catch (err) {
if (err.message && err.message.includes("Could not establish connection")) {
throw new Error(
"Content script not available in this tab. Try refreshing the page."
);
}
throw err;
}
}
// ------------------------------------------------------------------
// Route incoming requests from the Python bridge
// ------------------------------------------------------------------
async function handleRequest(msg) {
const { request_id, action, params } = msg;
try {
let result;
switch (action) {
// --- DOM / content script actions ---
case "get_page_summary":
result = await execInTab(params.tab_id, params.window_id, "getPageSummary", {});
break;
case "get_element_details":
result = await execInTab(params.tab_id, params.window_id, "getElementDetails", { id: params.id });
break;
case "click_element":
result = await execInTab(params.tab_id, params.window_id, "clickElement", { id: params.id });
break;
case "type_text":
result = await execInTab(params.tab_id, params.window_id, "typeText", { id: params.id, text: params.text });
break;
case "press_key":
result = await execInTab(params.tab_id, params.window_id, "pressKey", { key: params.key });
break;
case "scroll_page":
result = await execInTab(params.tab_id, params.window_id, "scrollPage", {
direction: params.direction,
amount: params.amount,
});
break;
case "execute_script":
result = await execInTab(params.tab_id, params.window_id, "executeScript", { js_code: params.js_code });
break;
case "read_page_text":
result = await execInTab(params.tab_id, params.window_id, "readPageText", {});
break;
// --- Background-only actions ---
case "take_screenshot":
result = await takeScreenshot(params.tab_id, params.window_id);
break;
case "get_page_cookies":
result = await getPageCookies(params.tab_id, params.window_id);
break;
case "get_current_url":
result = await getCurrentUrl(params.tab_id, params.window_id);
break;
case "list_tabs":
result = await listTabs();
break;
case "switch_tab":
result = await switchTab(params.tab_id, params.window_id);
break;
case "navigate_to":
result = await navigateTo(params.url, params.tab_id, params.window_id);
break;
case "open_new_tab":
result = await openNewTab(params.url, params.window_id);
break;
case "open_new_window":
result = await openNewWindow(params.url);
break;
default:
throw new Error(`Unknown action: ${action}`);
}
sendResponse(request_id, { success: true, result: result });
} catch (err) {
console.error(`[MCP Bridge] Error handling ${action}:`, err);
sendResponse(request_id, { success: false, error: err.message });
}
}
// ------------------------------------------------------------------
// Background-only implementations
// ------------------------------------------------------------------
async function takeScreenshot(tabId, windowId) {
const tab = await resolveTarget(tabId, windowId);
const dataUrl = await browser.tabs.captureVisibleTab(tab.windowId, { format: "png" });
return { screenshot: dataUrl };
}
async function getPageCookies(tabId, windowId) {
const tab = await resolveTarget(tabId, windowId);
const url = tab.url;
console.log("[MCP Bridge] getPageCookies for URL:", url);
const cookies = await browser.cookies.getAll({ url: url });
console.log("[MCP Bridge] getPageCookies result:", cookies);
return cookies;
}
async function getCurrentUrl(tabId, windowId) {
const tab = await resolveTarget(tabId, windowId);
return { url: tab.url };
}
async function listTabs() {
const tabs = await browser.tabs.query({});
return tabs.map((t) => ({
id: t.id,
title: t.title || "",
url: t.url || "",
active: t.active || false,
windowId: t.windowId,
}));
}
async function switchTab(tabId, windowId) {
let tab;
if (tabId) {
tab = await browser.tabs.get(tabId);
if (!tab) throw new Error(`Tab ${tabId} not found`);
} else if (windowId) {
const tabs = await browser.tabs.query({ windowId, active: true });
if (!tabs || tabs.length === 0) {
throw new Error(`No active tab in window ${windowId}`);
}
tab = tabs[0];
} else {
throw new Error("Either tab_id or window_id is required");
}
await browser.windows.update(tab.windowId, { focused: true });
await browser.tabs.update(tab.id, { active: true });
const updated = await browser.tabs.get(tab.id);
return { success: true, tabId: updated.id, windowId: updated.windowId, url: updated.url };
}
async function navigateTo(url, tabId, windowId) {
const tab = await resolveTarget(tabId, windowId);
await browser.tabs.update(tab.id, { url: url });
return { success: true };
}
async function openNewTab(url, windowId) {
const createProps = { url: url };
if (windowId) {
createProps.windowId = windowId;
}
await browser.tabs.create(createProps);
return { success: true };
}
async function openNewWindow(url) {
await browser.windows.create({
url: url,
width: 1280,
height: 960
});
return { success: true };
}
// ------------------------------------------------------------------
// Initialize connection
// ------------------------------------------------------------------
connect();