Files
opencode-chrome/host/mcp-server.js
T

225 lines
8.2 KiB
JavaScript

#!/usr/bin/env node
// stdio MCP server for opencode (or any MCP client). Advertises the official
// Claude in Chrome tool surface and runs it against the user's browser via
// the native host bridge (tool-runtime.js).
//
// Most tools are forwarded to the extension unchanged. The server itself
// handles what needs more than one browser, more than one tool, or the local
// filesystem: browser_batch, navigate without a tabId, the browser selection
// tools, file_upload's path checks, and save_to_disk.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import { TOOLS, TOOL_NAMES } from "./tool-definitions.js";
import { APP_DIR } from "./endpoint.js";
import {
callTool,
coerceArgs,
listBrowsers,
selectBrowser,
switchBrowser,
shutdown
} from "./tool-runtime.js";
import { watchParent } from "./parent-watch.js";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const MAX_UPLOAD_BYTES = 10 * 1024 * 1024;
function exitClean(code = 0) {
try {
shutdown();
} catch {}
process.exit(code);
}
process.on("SIGTERM", () => exitClean());
process.on("SIGINT", () => exitClean());
process.on("SIGHUP", () => exitClean());
process.stdin.on("end", () => exitClean());
watchParent(() => exitClean());
const text = (t, isError = false) => ({ content: [{ type: "text", text: t }], ...(isError ? { isError: true } : {}) });
const isErrorResult = (r) => !!r?.isError;
// --- Server-side tool logic ---
// navigate with no tabId: create/find the session's group and use its first
// tab, then append the group context so the agent has the tab ids.
async function navigateStandalone(args) {
if (args.url === "back" || args.url === "forward") {
return text(`tabId is required for url:"${args.url}".`, true);
}
const ctx = await callTool("tabs_context_mcp", { createIfEmpty: true });
if (isErrorResult(ctx)) return ctx;
let tabId;
try {
tabId = JSON.parse(ctx.content.find((c) => c.type === "text")?.text || "").availableTabs?.[0]?.tabId;
} catch {}
if (tabId === undefined) return text("Couldn't determine which page this action targets. Re-read tabs_context_mcp and try again.", true);
// The result's Tab Context lists the group's tabs and their ids.
return callTool("navigate", { ...args, tabId });
}
function checkUploadPaths(paths) {
if (!Array.isArray(paths) || paths.length === 0) return "paths must be a non-empty array of absolute file paths.";
let total = 0;
for (const p of paths) {
if (typeof p !== "string" || !path.isAbsolute(p)) return `Not an absolute path: ${JSON.stringify(p)}`;
let st;
try {
st = fs.statSync(p);
} catch {
return `File not found: ${p}`;
}
if (!st.isFile()) return `Not a regular file: ${p}`;
total += st.size;
}
if (total >= MAX_UPLOAD_BYTES) {
return `The files total ${(total / 1048576).toFixed(1)} MB; a single upload must stay under 10 MB.`;
}
return null;
}
function saveImages(result) {
const dir = path.join(APP_DIR, "screenshots");
fs.mkdirSync(dir, { recursive: true });
const saved = [];
for (const c of result.content) {
if (c.type !== "image") continue;
const ext = c.mimeType === "image/png" ? "png" : "jpg";
const file = path.join(dir, `${new Date().toISOString().replace(/[:.]/g, "-")}.${ext}`);
fs.writeFileSync(file, Buffer.from(c.data, "base64"));
saved.push(file);
}
return saved;
}
async function runTool(name, rawArgs, { inBatch = false } = {}) {
if (!TOOL_NAMES.has(name)) return text(`Unknown tool: ${name}`, true);
const args = coerceArgs({ ...(rawArgs || {}) });
switch (name) {
case "browser_batch":
if (inBatch) return text("browser_batch cannot be nested.", true);
return runBatch(args.actions);
case "list_connected_browsers":
return listBrowsers();
case "select_browser":
return selectBrowser(args.deviceId);
case "switch_browser":
return switchBrowser();
case "navigate":
if (args.tabId === undefined || args.tabId === null) {
if (inBatch) return text("Inside browser_batch, navigate requires an explicit tabId.", true);
return navigateStandalone(args);
}
return callTool(name, args);
case "file_upload": {
const problem = checkUploadPaths(args.paths);
if (problem) return text(problem, true);
return callTool(name, args);
}
case "computer": {
const save = !!args.save_to_disk;
delete args.save_to_disk;
const result = await callTool(name, args);
if (save && !isErrorResult(result) && (args.action === "screenshot" || args.action === "zoom")) {
try {
const files = saveImages(result);
if (files.length) result.content.push({ type: "text", text: `Saved to disk: ${files.join(", ")}` });
} catch (e) {
result.content.push({ type: "text", text: `(Unable to save to disk: ${e.message})` });
}
}
return result;
}
default:
return callTool(name, args);
}
}
// Batch output in the official extension's format: each result labelled
// "[tool]" or "[tool:action]", one Tab Context block at the end; on a failure
// everything so far is folded into one text with the images left out.
const batchLabel = (item) => `${item.name}${item.name === "computer" && item.input?.action ? `:${item.input.action}` : ""}`;
async function runBatch(actions) {
if (!Array.isArray(actions) || actions.length === 0) {
return text("actions must be a non-empty array of {name, input}.", true);
}
const content = [];
let context;
const n = actions.length;
const fail = (i, label, msg) => {
const done = [];
for (const c of content) {
if (c.type === "text") done.push(c.text);
else if (done.length) done[done.length - 1] += " [Image omitted due to error]";
}
const head = done.length ? `${done.join("\n")}\n\n` : "";
return text(`${head}actions[${i}] (${label}) failed: ${msg} (${i} completed, ${n - i - 1} remaining)`, true);
};
for (let i = 0; i < n; i++) {
const item = actions[i] || {};
if (typeof item.name !== "string" || typeof item.input !== "object" || item.input === null) {
return fail(i, String(item.name), "each action must be {name, input}.");
}
const label = batchLabel(item);
const result = await runTool(item.name, item.input, { inBatch: true });
if (isErrorResult(result)) {
const msg = (result.content || []).filter((c) => c.type === "text").map((c) => c.text).join("\n").replace(/^Error: /, "");
return fail(i, label, msg);
}
if (result.context) context = result.context;
const [first, ...rest] = result.content || [];
if (first?.type === "text") content.push({ type: "text", text: `[${label}] ${first.text}` }, ...rest);
else content.push({ type: "text", text: `[${label}]` }, ...(result.content || []));
}
if (context) content.push({ type: "text", text: context });
return { content };
}
// A standalone result gets its Tab Context right after the first text,
// before any image.
function finish(result) {
if (!result?.context) return result;
const { context, ...rest } = result;
const content = [...(rest.content || [])];
const i = content.findIndex((c) => c.type === "text");
content.splice(i + 1, 0, { type: "text", text: context });
return { ...rest, content };
}
// --- MCP plumbing ---
let instructions = "";
try {
instructions = fs.readFileSync(path.join(HERE, "instructions.md"), "utf-8");
} catch {}
const server = new Server(
{ name: "opencode-browser", version: "1.0.0" },
{ capabilities: { tools: {} }, instructions }
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))
}));
server.setRequestHandler(CallToolRequestSchema, async (req) => {
const { name, arguments: args } = req.params;
try {
return finish(await runTool(name, args));
} catch (e) {
return text(`Error: ${e?.message || e}`, true);
}
});
await server.connect(new StdioServerTransport());