Initial commit

This commit is contained in:
moosecrap committed 2026-11-22 04:45:52 -08:00
commit 52ddc6ba9a
27 files changed
+2166

No files matched your search

+313
View File
@@ -0,0 +1,313 @@
/*
* 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;
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 };
}
// ------------------------------------------------------------------
// Initialize connection
// ------------------------------------------------------------------
connect();
+282
View File
@@ -0,0 +1,282 @@
/*
* Firefox MCP Bridge - Content Script
*
* Runs in the context of web pages. Provides DOM-level access
* to the background script via browser.runtime.onMessage.
*/
let mcpIdCounter = 0;
// ------------------------------------------------------------------
// Element indexing helpers
// ------------------------------------------------------------------
function getNextId() {
return ++mcpIdCounter;
}
function isInteractiveElement(el) {
const tag = el.tagName.toLowerCase();
const interactiveTags = [
"button",
"a",
"input",
"select",
"textarea",
];
if (interactiveTags.includes(tag)) return true;
const role = el.getAttribute("role");
if (role === "button" || role === "link" || role === "checkbox" || role === "radio" || role === "switch") {
return true;
}
if (el.onclick || el.getAttribute("onclick")) return true;
if (el.isContentEditable) return true;
return false;
}
function getBasicInfo(el) {
const tag = el.tagName.toLowerCase();
const ariaRole = el.getAttribute("role");
const role = ariaRole || tag;
let text = "";
if (tag === "input") {
text = el.value || el.getAttribute("placeholder") || el.getAttribute("type") || "";
} else if (tag === "img") {
text = el.alt || el.getAttribute("src") || "";
} else {
const tc = el.textContent || el.innerText || "";
text = tc.trim().substring(0, 200);
}
const label =
el.getAttribute("aria-label") ||
el.getAttribute("alt") ||
el.getAttribute("title") ||
"";
const href = el.href || "";
const src = el.src || "";
return {
role: role,
text: text,
label: label,
tag: tag,
type: el.type || "",
name: el.name || "",
id_attr: el.id || "",
class: el.className || "",
href: href,
src: src,
};
}
function scanPage() {
const elements = [];
const selector =
"button, a, input, select, textarea, " +
"[role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch'], " +
"[onclick], [contenteditable='true']";
const interactive = document.querySelectorAll(selector);
interactive.forEach((el) => {
// Assign a stable mcp-id if not already present
let mcpId = el.getAttribute("data-mcp-id");
if (!mcpId) {
mcpId = getNextId().toString();
el.setAttribute("data-mcp-id", mcpId);
}
const info = getBasicInfo(el);
info.id = parseInt(mcpId, 10);
elements.push(info);
});
return elements;
}
function getElementByMcpId(id) {
return document.querySelector(`[data-mcp-id="${id}"]`);
}
function getElementDetails(id) {
const el = getElementByMcpId(id);
if (!el) {
throw new Error(`Element with mcp-id ${id} not found in the DOM`);
}
const rect = el.getBoundingClientRect();
const computed = window.getComputedStyle(el);
const attributes = {};
for (let i = 0; i < el.attributes.length; i++) {
const attr = el.attributes[i];
attributes[attr.name] = attr.value;
}
return {
id: parseInt(el.getAttribute("data-mcp-id"), 10),
tag: el.tagName.toLowerCase(),
text: el.textContent ? el.textContent.trim() : "",
value: el.value || "",
html: el.outerHTML.substring(0, 2000),
attributes: attributes,
bounding_box: {
x: Math.round(rect.x),
y: Math.round(rect.y),
width: Math.round(rect.width),
height: Math.round(rect.height),
},
visible: computed.visibility !== "hidden" && computed.display !== "none",
disabled: el.disabled === true,
readonly: el.readOnly === true,
};
}
// ------------------------------------------------------------------
// Action implementations
// ------------------------------------------------------------------
function clickElement(id) {
const el = getElementByMcpId(id);
if (!el) {
throw new Error(`Element with mcp-id ${id} not found`);
}
el.click();
return { success: true };
}
function typeText(id, text) {
const el = getElementByMcpId(id);
if (!el) {
throw new Error(`Element with mcp-id ${id} not found`);
}
el.focus();
el.value = text;
// Dispatch input and change events so frameworks (React, Vue, etc.) notice
el.dispatchEvent(new Event("input", { bubbles: true }));
el.dispatchEvent(new Event("change", { bubbles: true }));
return { success: true };
}
function pressKey(key) {
const active = document.activeElement || document.body;
const event = new KeyboardEvent("keydown", {
key: key,
code: key,
bubbles: true,
cancelable: true,
});
active.dispatchEvent(event);
return { success: true };
}
function scrollPage(direction, amount) {
let pixels = amount;
if (amount > 0 && amount <= 100) {
// Treat as percentage of viewport
const viewportSize =
direction === "up" || direction === "down"
? window.innerHeight
: window.innerWidth;
pixels = (amount / 100) * viewportSize;
}
if (direction === "up") {
window.scrollBy(0, -pixels);
} else if (direction === "down") {
window.scrollBy(0, pixels);
} else if (direction === "left") {
window.scrollBy(-pixels, 0);
} else if (direction === "right") {
window.scrollBy(pixels, 0);
}
return { success: true };
}
function executeScript(jsCode) {
try {
const result = window.eval(jsCode);
return {
result: result !== undefined ? String(result) : "",
};
} catch (err) {
throw new Error(`Script error: ${err.message}`);
}
}
function readPageText() {
// Build a "reader mode" version by cloning the document and stripping noise
const clone = document.cloneNode(true);
const removeTags = [
"script",
"style",
"nav",
"header",
"footer",
"aside",
"iframe",
"noscript",
];
removeTags.forEach((tag) => {
clone.querySelectorAll(tag).forEach((el) => el.remove());
});
let text = clone.textContent || clone.innerText || "";
// Normalize whitespace
text = text.replace(/\n\s*\n/g, "\n").replace(/\s+/g, " ").trim();
return text.substring(0, 10000); // Cap size for token budget
}
// ------------------------------------------------------------------
// Message listener: receives requests from the background script
// ------------------------------------------------------------------
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type !== "mcp_call") {
return;
}
(async () => {
try {
let result;
switch (message.function) {
case "getPageSummary":
result = scanPage();
break;
case "getElementDetails":
result = getElementDetails(message.args.id);
break;
case "clickElement":
result = clickElement(message.args.id);
break;
case "typeText":
result = typeText(message.args.id, message.args.text);
break;
case "pressKey":
result = pressKey(message.args.key);
break;
case "scrollPage":
result = scrollPage(message.args.direction, message.args.amount);
break;
case "executeScript":
result = executeScript(message.args.js_code);
break;
case "readPageText":
result = readPageText();
break;
default:
throw new Error(`Unknown content function: ${message.function}`);
}
sendResponse({ result: result });
} catch (err) {
sendResponse({ error: err.message });
}
})();
return true; // Keep the message channel open for async response
});
+32
View File
@@ -0,0 +1,32 @@
{
"manifest_version": 2,
"name": "Firefox MCP Bridge",
"version": "0.1.0",
"description": "Allows an LLM to control Firefox via the Model Context Protocol (MCP).",
"permissions": [
"tabs",
"activeTab",
"storage",
"cookies",
"<all_urls>"
],
"background": {
"scripts": ["background.js"],
"persistent": true
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end",
"all_frames": false
}
],
"web_accessible_resources": [],
"browser_specific_settings": {
"gecko": {
"id": "mcp-firefox-bridge@local",
"strict_min_version": "109.0"
}
}
}