// MCP-side runtime: finds connected browsers, keeps one link per browser, and // routes each tool call to the browser this session uses. // // Browser choice follows the official extension: with exactly one browser // connected, tools just work; with several and none chosen, calls fail with a // message that sends the agent to list_connected_browsers / select_browser (or // switch_browser, which lets the user click Connect inside the browser). import net from "node:net"; import { randomUUID } from "node:crypto"; import { endpointPath, listDescriptors } from "./endpoint.js"; import { noteActivity } from "./parent-watch.js"; // One id per MCP server process = one opencode session. The extension keys // the session's tab group on it. export const SESSION_ID = randomUUID(); const REQUEST_TIMEOUT_MS = 90_000; // The host is respawned whenever Chrome recycles the service worker; a call // that lands in that gap should wait for it rather than fail. const LINK_GRACE_MS = 5_000; const CONNECT_TIMEOUT_MS = 120_000; const NO_BROWSER_ERROR = "No browser is connected. Make sure Chrome (or another Chromium browser) is running with the " + "opencode extension installed and enabled, then try again."; const HOST_DROPPED_ERROR = "Browser connection dropped after the request was sent, so its result is unknown. " + "The action may have ALREADY taken effect in the browser. Do not blindly retry: " + "check the current page state first (e.g. take a screenshot or read the page), " + "then repeat the action only if it did not happen."; const PLATFORM_OF_HOST = { darwin: "mac", win32: "win", linux: "linux" }[process.platform] || process.platform; class BrowserLink { constructor(info) { this.info = info; this.deviceId = info.deviceId; this.socket = null; this.ready = null; this.buffer = Buffer.alloc(0); this.pending = new Map(); this.seq = 0; this.closed = false; } connect() { if (this.ready) return this.ready; this.ready = new Promise((resolve, reject) => { const sock = net.createConnection(endpointPath(this.deviceId)); this.socket = sock; const fail = (err) => { this.close(); reject(err); }; sock.once("error", fail); sock.on("connect", () => { sock.removeListener("error", fail); sock.on("error", () => {}); sock.write(JSON.stringify({ type: "client_hello", session: SESSION_ID }) + "\n"); resolve(this); }); sock.on("data", (chunk) => this.onData(chunk)); sock.on("close", () => this.close()); }); return this.ready; } onData(chunk) { this.buffer = Buffer.concat([this.buffer, chunk]); let idx; while ((idx = this.buffer.indexOf(10)) !== -1) { const line = this.buffer.subarray(0, idx).toString("utf-8").trim(); this.buffer = this.buffer.subarray(idx + 1); if (!line) continue; let msg; try { msg = JSON.parse(line); } catch { continue; } if (msg.type === "client_ack") { if (msg.browser) this.info = { ...this.info, ...msg.browser }; continue; } const entry = msg.id && this.pending.get(msg.id); if (!entry) continue; clearTimeout(entry.timer); this.pending.delete(msg.id); entry.resolve(msg); } } request(msg, timeoutMs = REQUEST_TIMEOUT_MS) { return new Promise((resolve, reject) => { if (this.closed || !this.socket || this.socket.destroyed) { reject(new Error(NO_BROWSER_ERROR)); return; } const id = String(++this.seq); const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Browser did not answer within ${Math.round(timeoutMs / 1000)}s`)); }, timeoutMs); this.pending.set(id, { resolve, reject, timer }); this.socket.write(JSON.stringify({ ...msg, id, session: SESSION_ID }) + "\n"); }); } notify(msg) { try { if (this.socket && !this.socket.destroyed) { this.socket.write(JSON.stringify({ ...msg, session: SESSION_ID }) + "\n"); } } catch {} } close() { if (this.closed) return; this.closed = true; links.delete(this.deviceId); try { this.socket?.destroy(); } catch {} for (const [, e] of this.pending) { clearTimeout(e.timer); e.reject(new Error(HOST_DROPPED_ERROR)); } this.pending.clear(); } } const links = new Map(); // deviceId -> BrowserLink let selectedDeviceId = null; // Reconcile links with the descriptors on disk and connect to any new ones. async function refresh() { const infos = listDescriptors(); const seen = new Set(); await Promise.all( infos.map(async (info) => { seen.add(info.deviceId); let link = links.get(info.deviceId); if (!link) { link = new BrowserLink(info); links.set(info.deviceId, link); } else { link.info = { ...link.info, ...info }; } try { await link.connect(); } catch { link.close(); } }) ); for (const [id, link] of links) if (!seen.has(id)) link.close(); return [...links.values()]; } async function liveLinks(graceMs) { let live = await refresh(); const deadline = Date.now() + graceMs; while (live.length === 0 && Date.now() < deadline) { await new Promise((r) => setTimeout(r, 250)); live = await refresh(); } return live; } // The browser this session's actions go to, or an error message saying why // there isn't one. async function resolveTarget() { const live = await liveLinks(LINK_GRACE_MS); if (live.length === 0) return { error: NO_BROWSER_ERROR }; if (selectedDeviceId) { const chosen = live.find((l) => l.deviceId === selectedDeviceId); if (chosen) return { link: chosen }; if (live.length > 1) { return { error: `The browser selected for this session (${selectedDeviceId}) is no longer connected, and ` + `${live.length} other browsers are. Call list_connected_browsers, ask the user which one to ` + `use, then call select_browser.` }; } } if (live.length === 1) return { link: live[0] }; return { error: `${live.length} browsers are connected and none is selected for this session. Call ` + `list_connected_browsers, ask the user which one to use, then call select_browser ` + `(or switch_browser to let them pick inside Chrome).` }; } const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...(isError ? { isError: true } : {}) }); // Some MCP clients serialize numbers and arrays as strings. export function coerceArgs(args) { if (!args || typeof args !== "object") return args ?? {}; for (const k of ["tabId", "duration", "scroll_amount", "repeat", "scale", "depth", "max_chars", "limit", "width", "height"]) { if (typeof args[k] === "string" && args[k].trim() !== "" && !isNaN(Number(args[k]))) args[k] = Number(args[k]); } for (const k of ["coordinate", "start_coordinate", "region", "paths", "actions"]) { if (typeof args[k] === "string") { try { args[k] = JSON.parse(args[k]); } catch {} } } for (const k of ["createIfEmpty", "save_to_disk", "clear", "onlyErrors", "download"]) { if (args[k] === "true") args[k] = true; if (args[k] === "false") args[k] = false; } return args; } /** Forward one tool call to the session's browser. Returns a CallToolResult. */ export async function callTool(tool, args) { noteActivity(); const { link, error } = await resolveTarget(); if (error) return text(error, true); selectedDeviceId = link.deviceId; try { const msg = await link.request({ type: "tool_request", tool, args: coerceArgs(args ?? {}) }); if (msg.type === "tool_error") return text(`Error: ${msg.error || "Tool execution failed"}`, true); const result = msg.result; if (typeof result === "string") return text(result); if (result && Array.isArray(result.content)) return result; return text(JSON.stringify(result, null, 2)); } catch (err) { return text(`Error: ${err.message}`, true); } } export async function listBrowsers() { const live = await liveLinks(1000); const browsers = live .map((l) => ({ deviceId: l.deviceId, name: l.info.name, browser: l.info.browser, platform: l.info.platform, isLocal: l.info.platform === PLATFORM_OF_HOST, // Endpoints are local sockets, so every browser reachable here runs on // this computer. onThisComputer: true, inUse: selectedDeviceId ? l.deviceId === selectedDeviceId : live.length === 1 })) .sort((a, b) => a.name.localeCompare(b.name)); if (browsers.length === 0) return text(NO_BROWSER_ERROR, true); return text(JSON.stringify({ browsers }, null, 2)); } export async function selectBrowser(deviceId) { const live = await liveLinks(1000); const link = live.find((l) => l.deviceId === deviceId); if (!link) { const ids = live.map((l) => `${l.info.name} (${l.deviceId})`).join(", ") || "none"; return text(`No connected browser has deviceId "${deviceId}". Connected: ${ids}.`, true); } selectedDeviceId = deviceId; return text(`Selected ${link.info.name} (${deviceId}) for this session's browser automation.`); } export async function switchBrowser() { const live = await liveLinks(LINK_GRACE_MS); if (live.length === 0) return text(NO_BROWSER_ERROR, true); const requestId = randomUUID(); const attempts = live.map((link) => link .request({ type: "connect_request", requestId }, CONNECT_TIMEOUT_MS) .then((msg) => (msg.accepted ? { link, name: msg.name } : Promise.reject(new Error("declined")))) ); let winner; try { winner = await Promise.any(attempts); } catch { for (const link of live) link.notify({ type: "connect_cancel", requestId }); return text( "No browser accepted the connection request within 2 minutes (or the user declined in every browser).", true ); } for (const link of live) if (link !== winner.link) link.notify({ type: "connect_cancel", requestId }); selectedDeviceId = winner.link.deviceId; if (winner.name) winner.link.info.name = winner.name; return text(`Connected to ${winner.link.info.name} (${winner.link.deviceId}). Browser tools now act in this browser.`); } export function shutdown() { for (const link of [...links.values()]) link.close(); }