opendia init

This commit is contained in:
Aaron Elijah Mars
2025-06-13 23:21:32 +02:00
parent c6c6394543
commit e26dc768fe
10 changed files with 2540 additions and 799 deletions

View File

@@ -0,0 +1,438 @@
// MCP Server connection configuration
const MCP_SERVER_URL = 'ws://localhost:3000';
let mcpSocket = null;
let reconnectInterval = null;
let reconnectAttempts = 0;
// Initialize WebSocket connection to MCP server
function connectToMCPServer() {
if (mcpSocket && mcpSocket.readyState === WebSocket.OPEN) return;
mcpSocket = new WebSocket(MCP_SERVER_URL);
mcpSocket.onopen = () => {
clearInterval(reconnectInterval);
// Register available browser functions
mcpSocket.send(JSON.stringify({
type: 'register',
tools: getAvailableTools()
}));
};
mcpSocket.onmessage = async (event) => {
const message = JSON.parse(event.data);
await handleMCPRequest(message);
};
mcpSocket.onclose = () => {
// Attempt to reconnect every 5 seconds
reconnectInterval = setInterval(connectToMCPServer, 5000);
};
mcpSocket.onerror = (error) => {
// Handle error silently in production
};
}
// Define available browser tools for MCP
function getAvailableTools() {
return [
{
name: "browser_navigate",
description: "Navigate to a URL in the active tab",
inputSchema: {
type: "object",
properties: {
url: { type: "string", description: "URL to navigate to" },
},
required: ["url"],
},
},
{
name: "browser_get_tabs",
description: "Get all open tabs",
inputSchema: {
type: "object",
properties: {},
},
},
{
name: "browser_create_tab",
description: "Create a new tab",
inputSchema: {
type: "object",
properties: {
url: { type: "string", description: "URL for the new tab" },
active: {
type: "boolean",
description: "Whether to make the tab active",
},
},
},
},
{
name: "browser_close_tab",
description: "Close a tab by ID",
inputSchema: {
type: "object",
properties: {
tabId: { type: "number", description: "ID of the tab to close" },
},
required: ["tabId"],
},
},
{
name: "browser_execute_script",
description: "Execute JavaScript in the active tab",
inputSchema: {
type: "object",
properties: {
code: { type: "string", description: "JavaScript code to execute" },
},
required: ["code"],
},
},
{
name: "browser_get_page_content",
description: "Get the content of the active page",
inputSchema: {
type: "object",
properties: {
selector: {
type: "string",
description: "CSS selector to get specific content",
},
},
},
},
{
name: "browser_take_screenshot",
description: "Take a screenshot of the active tab",
inputSchema: {
type: "object",
properties: {
format: {
type: "string",
enum: ["png", "jpeg"],
description: "Image format",
},
},
},
},
{
name: "browser_get_bookmarks",
description: "Get browser bookmarks",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search query for bookmarks" },
},
},
},
{
name: "browser_add_bookmark",
description: "Add a bookmark",
inputSchema: {
type: "object",
properties: {
title: { type: "string", description: "Bookmark title" },
url: { type: "string", description: "Bookmark URL" },
},
required: ["title", "url"],
},
},
{
name: "browser_get_history",
description: "Search browser history",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "Search query" },
maxResults: {
type: "number",
description: "Maximum number of results",
},
},
},
},
{
name: "browser_get_cookies",
description: "Get cookies for a domain",
inputSchema: {
type: "object",
properties: {
domain: { type: "string", description: "Domain to get cookies for" },
},
},
},
{
name: "browser_fill_form",
description: "Fill a form on the current page",
inputSchema: {
type: "object",
properties: {
formData: {
type: "object",
description: "Key-value pairs of form field names/IDs and values",
},
},
required: ["formData"],
},
},
{
name: "browser_click_element",
description: "Click an element on the page",
inputSchema: {
type: "object",
properties: {
selector: {
type: "string",
description: "CSS selector of element to click",
},
},
required: ["selector"],
},
},
];
}
// Handle MCP requests
async function handleMCPRequest(message) {
const { id, method, params } = message;
try {
let result;
switch (method) {
case "browser_navigate":
result = await navigateToUrl(params.url);
break;
case "browser_get_tabs":
result = await getTabs();
break;
case "browser_create_tab":
result = await createTab(params);
break;
case "browser_close_tab":
result = await closeTab(params.tabId);
break;
case "browser_execute_script":
result = await executeScript(params.code);
break;
case "browser_get_page_content":
result = await getPageContent(params.selector);
break;
case "browser_take_screenshot":
result = await takeScreenshot(params.format);
break;
case "browser_get_bookmarks":
result = await getBookmarks(params.query);
break;
case "browser_add_bookmark":
result = await addBookmark(params);
break;
case "browser_get_history":
result = await getHistory(params);
break;
case "browser_get_cookies":
result = await getCookies(params.domain);
break;
case "browser_fill_form":
result = await fillForm(params.formData);
break;
case "browser_click_element":
result = await clickElement(params.selector);
break;
default:
throw new Error(`Unknown method: ${method}`);
}
// Send success response
mcpSocket.send(
JSON.stringify({
id,
result,
})
);
} catch (error) {
// Send error response
mcpSocket.send(
JSON.stringify({
id,
error: {
message: error.message,
code: -32603,
},
})
);
}
}
// Browser function implementations
async function navigateToUrl(url) {
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
await chrome.tabs.update(activeTab.id, { url });
return { success: true, tabId: activeTab.id };
}
async function getTabs() {
const tabs = await chrome.tabs.query({});
return tabs.map((tab) => ({
id: tab.id,
title: tab.title,
url: tab.url,
active: tab.active,
windowId: tab.windowId,
}));
}
async function createTab(params) {
const tab = await chrome.tabs.create({
url: params.url || "about:blank",
active: params.active !== false,
});
return { id: tab.id, windowId: tab.windowId };
}
async function closeTab(tabId) {
await chrome.tabs.remove(tabId);
return { success: true };
}
async function executeScript(code) {
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const results = await chrome.scripting.executeScript({
target: { tabId: activeTab.id },
func: new Function(code),
});
return results[0].result;
}
async function getPageContent(selector) {
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const results = await chrome.scripting.executeScript({
target: { tabId: activeTab.id },
func: (sel) => {
if (sel) {
const element = document.querySelector(sel);
return element ? element.innerText : null;
}
return document.body.innerText;
},
args: [selector],
});
return results[0].result;
}
async function takeScreenshot(format = "png") {
const dataUrl = await chrome.tabs.captureVisibleTab(null, { format });
return { dataUrl, format };
}
async function getBookmarks(query) {
if (query) {
return await chrome.bookmarks.search(query);
}
return await chrome.bookmarks.getTree();
}
async function addBookmark(params) {
const bookmark = await chrome.bookmarks.create({
title: params.title,
url: params.url,
});
return bookmark;
}
async function getHistory(params) {
const historyItems = await chrome.history.search({
text: params.query || "",
maxResults: params.maxResults || 100,
});
return historyItems;
}
async function getCookies(domain) {
const cookies = await chrome.cookies.getAll({ domain });
return cookies;
}
async function fillForm(formData) {
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const results = await chrome.scripting.executeScript({
target: { tabId: activeTab.id },
func: (data) => {
for (const [key, value] of Object.entries(data)) {
const element = document.querySelector(`[name="${key}"], #${key}`);
if (element) {
element.value = value;
element.dispatchEvent(new Event("input", { bubbles: true }));
}
}
return { success: true, filled: Object.keys(data).length };
},
args: [formData],
});
return results[0].result;
}
async function clickElement(selector) {
const [activeTab] = await chrome.tabs.query({
active: true,
currentWindow: true,
});
const results = await chrome.scripting.executeScript({
target: { tabId: activeTab.id },
func: (sel) => {
const element = document.querySelector(sel);
if (element) {
element.click();
return { success: true, clicked: sel };
}
throw new Error(`Element not found: ${sel}`);
},
args: [selector],
});
return results[0].result;
}
// Initialize connection when extension loads
connectToMCPServer();
// Heartbeat to keep connection alive
setInterval(() => {
if (mcpSocket && mcpSocket.readyState === WebSocket.OPEN) {
mcpSocket.send(JSON.stringify({ type: "ping", timestamp: Date.now() }));
}
}, 30000); // Every 30 seconds
// Handle messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getStatus") {
sendResponse({
connected: mcpSocket && mcpSocket.readyState === WebSocket.OPEN,
});
} else if (request.action === "reconnect") {
connectToMCPServer();
sendResponse({ success: true });
} else if (request.action === "test") {
if (mcpSocket && mcpSocket.readyState === WebSocket.OPEN) {
mcpSocket.send(JSON.stringify({ type: "test", timestamp: Date.now() }));
}
sendResponse({ success: true });
}
return true; // Keep the message channel open
});

View File

@@ -0,0 +1,13 @@
// Content script for interacting with web pages
console.log('MCP Browser Bridge content script loaded');
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'getPageInfo') {
sendResponse({
title: document.title,
url: window.location.href,
content: document.body.innerText
});
}
});

View File

@@ -0,0 +1,44 @@
{
"manifest_version": 3,
"name": "OpenDia Browser Bridge",
"version": "1.0.0",
"description": "Exposes browser functions through Model Context Protocol",
"permissions": [
"tabs",
"activeTab",
"storage",
"bookmarks",
"history",
"downloads",
"cookies",
"webNavigation",
"scripting",
"nativeMessaging",
"contextMenus",
"notifications",
"alarms",
"clipboardRead",
"clipboardWrite"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html",
"default_title": "OpenDia Browser Bridge"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_idle"
}
],
"externally_connectable": {
"ids": ["*"],
"matches": ["http://localhost/*"]
}
}

View File

@@ -0,0 +1,191 @@
<!DOCTYPE html>
<html>
<head>
<title>OpenDia Browser Bridge</title>
<style>
:root {
--primary-color: #2563eb;
--success-color: #22c55e;
--error-color: #ef4444;
--bg-color: #ffffff;
--text-color: #1f2937;
--border-color: #e5e7eb;
--hover-color: #1d4ed8;
}
body {
width: 380px;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
color: var(--text-color);
background: var(--bg-color);
margin: 0;
}
.header {
display: flex;
align-items: center;
margin-bottom: 20px;
}
.logo {
width: 32px;
height: 32px;
margin-right: 12px;
background: var(--primary-color);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
}
h2 {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
}
.status {
display: flex;
align-items: center;
margin-bottom: 20px;
padding: 12px;
background: #f8fafc;
border-radius: 8px;
border: 1px solid var(--border-color);
}
.status-indicator {
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 12px;
transition: background-color 0.3s ease;
}
.connected {
background-color: var(--success-color);
box-shadow: 0 0 0 4px rgba(34, 197, 94, 0.1);
}
.disconnected {
background-color: var(--error-color);
box-shadow: 0 0 0 4px rgba(239, 68, 68, 0.1);
}
.info {
background-color: #f8fafc;
padding: 16px;
border-radius: 8px;
margin-bottom: 16px;
border: 1px solid var(--border-color);
}
.info-row {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}
.info-row:last-child {
margin-bottom: 0;
}
.info-label {
color: #6b7280;
font-size: 0.875rem;
}
.info-value {
font-weight: 500;
}
.button-group {
display: flex;
gap: 8px;
margin-bottom: 16px;
}
button {
background-color: var(--primary-color);
color: white;
border: none;
padding: 10px 16px;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
font-size: 0.875rem;
transition: background-color 0.2s ease;
flex: 1;
}
button:hover {
background-color: var(--hover-color);
}
.log {
background-color: #f8fafc;
border: 1px solid var(--border-color);
padding: 12px;
border-radius: 8px;
max-height: 200px;
overflow-y: auto;
font-size: 0.75rem;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
.log-entry {
margin-bottom: 4px;
padding: 4px 0;
border-bottom: 1px solid var(--border-color);
}
.log-entry:last-child {
border-bottom: none;
}
.log-time {
color: #6b7280;
margin-right: 8px;
}
</style>
</head>
<body>
<div class="header">
<div class="logo">OD</div>
<h2>OpenDia Browser Bridge</h2>
</div>
<div class="status">
<div class="status-indicator" id="statusIndicator"></div>
<span id="statusText">Checking connection...</span>
</div>
<div class="info">
<div class="info-row">
<span class="info-label">Server</span>
<span class="info-value" id="serverUrl">ws://localhost:3000</span>
</div>
<div class="info-row">
<span class="info-label">Available Tools</span>
<span class="info-value" id="toolCount">0</span>
</div>
</div>
<div class="button-group">
<button id="reconnectBtn">Reconnect</button>
<button id="testBtn">Test Connection</button>
</div>
<div class="log" id="log">
<div class="log-entry">
<span class="log-time">[System]</span>
<span>Waiting for activity...</span>
</div>
</div>
<script src="popup.js"></script>
</body>
</html>

112
opendia-extension/popup.js Normal file
View File

@@ -0,0 +1,112 @@
// Popup script for status display
let logContainer = document.getElementById("log");
let statusIndicator = document.getElementById("statusIndicator");
let statusText = document.getElementById("statusText");
let toolCount = document.getElementById("toolCount");
// Get initial tool count
const tools = 13; // Number of tools we expose
toolCount.textContent = tools;
// Check connection status
function checkStatus() {
if (chrome.runtime?.id) {
chrome.runtime.sendMessage({ action: "getStatus" }, (response) => {
if (chrome.runtime.lastError) {
updateStatus(false);
addLog("Extension background script not responding", "error");
} else {
updateStatus(response?.connected || false);
}
});
} else {
updateStatus(false);
addLog("Extension context invalid", "error");
}
}
// Check status on load and periodically
checkStatus();
setInterval(checkStatus, 2000);
// Update UI based on connection status
function updateStatus(connected) {
if (connected) {
statusIndicator.className = "status-indicator connected";
statusText.textContent = "Connected to MCP server";
} else {
statusIndicator.className = "status-indicator disconnected";
statusText.textContent = "Disconnected from MCP server";
}
}
// Reconnect button
document.getElementById("reconnectBtn").addEventListener("click", () => {
if (chrome.runtime?.id) {
chrome.runtime.sendMessage({ action: "reconnect" }, (response) => {
if (chrome.runtime.lastError) {
addLog(chrome.runtime.lastError.message, "error");
} else {
addLog("Attempting to reconnect...", "info");
setTimeout(checkStatus, 1000);
}
});
}
});
// Test button
document.getElementById("testBtn").addEventListener("click", () => {
if (chrome.runtime?.id) {
chrome.runtime.sendMessage({ action: "test" }, (response) => {
if (chrome.runtime.lastError) {
addLog(chrome.runtime.lastError.message, "error");
} else {
addLog("Sending test message...", "info");
}
});
}
});
// Add log entry
function addLog(message, type = "info") {
const entry = document.createElement("div");
entry.className = "log-entry";
const time = document.createElement("span");
time.className = "log-time";
time.textContent = `[${new Date().toLocaleTimeString()}]`;
const content = document.createElement("span");
content.textContent = message;
if (type === "error") {
content.style.color = "var(--error-color)";
} else if (type === "success") {
content.style.color = "var(--success-color)";
}
entry.appendChild(time);
entry.appendChild(content);
logContainer.appendChild(entry);
// Keep only last 20 entries
while (logContainer.children.length > 20) {
logContainer.removeChild(logContainer.firstChild);
}
logContainer.scrollTop = logContainer.scrollHeight;
}
// Listen for updates from background script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "statusUpdate") {
updateStatus(message.connected);
if (message.connected) {
addLog("Connected to MCP server", "success");
} else {
addLog("Disconnected from MCP server", "error");
}
} else if (message.type === "log") {
addLog(message.message, message.type || "info");
}
});