diff --git a/browser-tools-mcp/package.json b/browser-tools-mcp/package.json index 2dd3ff49..fd22b42c 100644 --- a/browser-tools-mcp/package.json +++ b/browser-tools-mcp/package.json @@ -7,7 +7,8 @@ "main": "dist/index.js", "bin": { "browser-tools-mcp": "dist/index.js", - "browser-tools-connector": "dist/connector-bin.js" + "browser-tools-connector": "dist/connector-bin.js", + "browser-tools": "dist/tools-cli-bin.js" }, "files": [ "dist", diff --git a/browser-tools-mcp/src/cli.ts b/browser-tools-mcp/src/cli.ts index 41d586c9..f734b435 100644 --- a/browser-tools-mcp/src/cli.ts +++ b/browser-tools-mcp/src/cli.ts @@ -20,10 +20,6 @@ export interface CliOptions { auditAllowedOrigins?: string[]; /** Let audits reach any loopback/private address but the audits' own ports (not recommended). */ auditAllowPrivateNetwork: boolean; - /** State-changing local API calls, without a panel confirmation. */ - allowActions: boolean; - /** Only this extension may pair. Bare id or full origin. */ - extensionId?: string; /** * Script evaluation. Argv only — not read from the environment — and off * unless this flag is present. @@ -38,6 +34,8 @@ export interface CliOptions { allowInputOrigins?: string[]; /** http(s) origins that are never acted on. Empty unless set. */ excludeOrigins?: string[]; + /** Only this extension may pair. Bare id or full origin. */ + extensionId?: string; } export function readPackageVersion(): string { @@ -80,15 +78,11 @@ export function parseCli(argv: string[], env: NodeJS.ProcessEnv = process.env): auditAllowPrivateNetwork: env["BROWSER_TOOLS_AUDIT_ALLOW_PRIVATE_NETWORK"] === "true" || env["BROWSER_TOOLS_AUDIT_ALLOW_PRIVATE_NETWORK"] === "1", - allowActions: - env["BROWSER_TOOLS_ALLOW_ACTIONS"] === "true" || env["BROWSER_TOOLS_ALLOW_ACTIONS"] === "1", + allowEval: false, + allowInput: false, ...(env["BROWSER_TOOLS_EXTENSION_ID"] ? { extensionId: env["BROWSER_TOOLS_EXTENSION_ID"] } : {}), - // Capability flags are argv only. They are intentionally not read from the - // environment, so an inherited variable cannot turn them on. - allowEval: false, - allowInput: false, ...(splitList(env["BROWSER_TOOLS_AUDIT_ALLOW_ORIGINS"]) ? { auditAllowedOrigins: splitList(env["BROWSER_TOOLS_AUDIT_ALLOW_ORIGINS"]) } : {}), @@ -108,7 +102,6 @@ export function parseCli(argv: string[], env: NodeJS.ProcessEnv = process.env): : {}), }; - // Both spellings of the flag, and the variable, add to the same list. const addAuditOrigins = (value: string | undefined) => { options.auditAllowedOrigins = [...(options.auditAllowedOrigins ?? []), ...(splitList(value) ?? [])]; }; @@ -151,12 +144,6 @@ export function parseCli(argv: string[], env: NodeJS.ProcessEnv = process.env): case "--audit-allow-private-network": options.auditAllowPrivateNetwork = true; break; - case "--allow-actions": - options.allowActions = true; - break; - case "--extension-id": - options.extensionId = next(); - break; case "--allow-eval": options.allowEval = true; break; @@ -169,6 +156,9 @@ export function parseCli(argv: string[], env: NodeJS.ProcessEnv = process.env): case "--exclude-origins": addExcludeOrigins(next()); break; + case "--extension-id": + options.extensionId = next(); + break; case "--port": options.port = numberOrUndefined(next()); break; @@ -199,9 +189,11 @@ export function parseCli(argv: string[], env: NodeJS.ProcessEnv = process.env): else if (arg.startsWith("--token=")) options.token = arg.slice(8); else if (arg.startsWith("--screenshot-dir=")) options.screenshotDir = arg.slice(17); else if (arg.startsWith("--audit-allow-origin=")) addAuditOrigins(arg.slice(21)); + else if (arg.startsWith("--allow-input-origins=")) + addInputOrigins(arg.slice("--allow-input-origins=".length)); + else if (arg.startsWith("--exclude-origins=")) + addExcludeOrigins(arg.slice("--exclude-origins=".length)); else if (arg.startsWith("--extension-id=")) options.extensionId = arg.slice(15); - else if (arg.startsWith("--allow-input-origins=")) addInputOrigins(arg.slice("--allow-input-origins=".length)); - else if (arg.startsWith("--exclude-origins=")) addExcludeOrigins(arg.slice("--exclude-origins=".length)); break; } } @@ -228,7 +220,6 @@ Options: --screenshot-dir

Where screenshots are written --only Expose only these tools --exclude Hide these tools (also on the local API) - --allow-actions Let the local API reload, capture, wipe and change settings --extension-id Only this extension may connect --connect Attach to a connector already running at this URL --token Auth token to use with --connect @@ -255,8 +246,7 @@ Environment: BROWSER_TOOLS_TOOLS, BROWSER_TOOLS_EXCLUDE_TOOLS, BROWSER_TOOLS_TOKEN, BROWSER_TOOLS_STATE_DIR, BROWSER_TOOLS_LOG_LEVEL, BROWSER_TOOLS_REDACT, BROWSER_TOOLS_VERBOSE, BROWSER_TOOLS_AUDIT_ALLOW_ORIGINS, - BROWSER_TOOLS_AUDIT_ALLOW_PRIVATE_NETWORK, BROWSER_TOOLS_ALLOW_ACTIONS, - BROWSER_TOOLS_EXTENSION_ID + BROWSER_TOOLS_AUDIT_ALLOW_PRIVATE_NETWORK, BROWSER_TOOLS_EXTENSION_ID Available tools: ${ALL_TOOL_NAMES.join(", ")} diff --git a/browser-tools-mcp/src/connector-bin.ts b/browser-tools-mcp/src/connector-bin.ts index 539ad31f..10955bba 100644 --- a/browser-tools-mcp/src/connector-bin.ts +++ b/browser-tools-mcp/src/connector-bin.ts @@ -42,10 +42,6 @@ async function main(): Promise { ` Let audits reach any loopback or private address, except the\n` + ` audits' own ports (not recommended). Also needed behind a\n` + ` fake-IP proxy (198.18.0.0/15 answers are refused otherwise)\n` + - ` --only Serve only these tools on the local API\n` + - ` --exclude Do not serve these tools on the local API\n` + - ` --allow-actions Allow reload, screenshot, wipe, settings and tab select\n` + - ` --extension-id Only this extension may connect\n` + ` --allow-eval Allow script evaluation. Off unless passed. No environment variable.\n` + ` --allow-input Allow click, type, navigation, and soft input. Off unless passed.\n` + ` No environment variable.\n` + @@ -53,8 +49,7 @@ async function main(): Promise { ` http(s) origins where input and navigation are allowed besides local addresses\n` + ` --exclude-origins \n` + ` http(s) origins that are never acted on. Empty unless set.\n\n` + - `Audit settings, tool filters, --allow-actions and capability flags apply to every MCP\n` + - `client that attaches to this connector.\n` + `Audit and capability settings apply to every MCP client that attaches to this connector.\n` ); return; } @@ -68,14 +63,13 @@ async function main(): Promise { verbose: options.verbose, ...(options.auditAllowedOrigins ? { auditAllowedOrigins: options.auditAllowedOrigins } : {}), auditAllowPrivateNetwork: options.auditAllowPrivateNetwork, - ...(options.enabledTools ? { enabledTools: options.enabledTools } : {}), - ...(options.disabledTools ? { disabledTools: options.disabledTools } : {}), - allowActions: options.allowActions, - ...(options.extensionId ? { extensionId: options.extensionId } : {}), allowEval: options.allowEval, allowInput: options.allowInput, ...(options.allowInputOrigins ? { allowInputOrigins: options.allowInputOrigins } : {}), ...(options.excludeOrigins ? { excludeOrigins: options.excludeOrigins } : {}), + ...(options.enabledTools ? { enabledTools: options.enabledTools } : {}), + ...(options.disabledTools ? { disabledTools: options.disabledTools } : {}), + ...(options.extensionId ? { extensionId: options.extensionId } : {}), }); writeSessionFile({ diff --git a/browser-tools-mcp/src/connector/api-policy.ts b/browser-tools-mcp/src/connector/api-policy.ts index 73e90c56..83137184 100644 --- a/browser-tools-mcp/src/connector/api-policy.ts +++ b/browser-tools-mcp/src/connector/api-policy.ts @@ -44,6 +44,7 @@ export const API_TOOL_NAMES: readonly string[] = [ "getConnectionStatus", "takeScreenshot", "refreshBrowser", + "navigateBrowser", "getBrowserStorage", "wipeLogs", ...AUDIT_CATEGORIES.map((category) => AUDIT_TOOL[category]), @@ -59,7 +60,8 @@ export interface ApiDecision { const TOOL_DISABLED = "This call is not enabled (--only / --exclude)."; const ACTION_NOT_CONFIRMED = - "State-changing calls need --allow-actions, or confirmation in the BrowserTools panel."; + "State-changing calls need --allow-input on the connector (browser-tools CLI: --allow-actions), " + + "or confirmation in the BrowserTools panel."; function truthyFlag(value: unknown): boolean { if (value === true) return true; @@ -97,6 +99,7 @@ function toolsForRequest(method: string, path: string, query: Record Promise; /** Injectable DNS for tests of the audit destination policy. */ auditLookup?: (host: string) => Promise; - /** - * When set, the local API serves only these tools. Same meaning as the MCP - * `--only` flag. Unknown names are ignored. - */ - enabledTools?: string[]; - /** Tools the local API will not serve. Applied after `enabledTools`. */ - disabledTools?: string[]; - /** - * Lets the local API perform state-changing calls without a panel - * confirmation. Off by default. - */ - allowActions?: boolean; - /** - * When set, only this extension (bare id or full origin) may pair and - * open the extension socket. Other extension origins are refused. - */ - extensionId?: string; /** Script evaluation. Off unless the process was started with --allow-eval. */ allowEval?: boolean; /** Click, type, navigation, and soft input. Off unless started with --allow-input. */ @@ -170,6 +153,11 @@ export interface ConnectorConfig { allowInputOrigins?: string[]; /** http(s) origins that are never acted on. Empty unless set. */ excludeOrigins?: string[]; + /** Same meaning as MCP `--only` / `--exclude`. Unknown names are ignored. */ + enabledTools?: string[]; + disabledTools?: string[]; + /** When set, only this extension (bare id or full origin) may pair. */ + extensionId?: string; } export interface TabView { @@ -238,6 +226,12 @@ export interface Connector { readArtifact(kind: "screenshot" | "audit", name: string): Promise; captureScreenshot(options?: { name?: string; tabId?: TabId }): Promise; refreshTab(options?: { tabId?: TabId }): Promise; + navigateTab(options: { url: string; tabId?: TabId }): Promise<{ + tabId: TabId; + requestedUrl: string; + finalUrl: string; + wasDiscarded: boolean; + }>; readStorage(kinds: string[], options?: { tabId?: TabId }): Promise>; runAudit( category: AuditCategory, @@ -271,8 +265,6 @@ interface ExtensionConnection { tabId: number | string | null; /** The page an extension that never named its tab last reported. */ pageUrl?: string; - /** Set by the DevTools panel. Dies with the socket. */ - actionsConfirmed: boolean; /** Worker sockets answer capability probes. They are not DevTools tabs. */ role: "devtools" | "worker"; /** True when the browser set an extension Origin on the upgrade. */ @@ -310,7 +302,6 @@ export async function createConnector(config: ConnectorConfig = {}): Promise 0) { log.warn(`Ignoring unknown tool name(s) in filter: ${toolFilter.unknown.join(", ")}`); } @@ -390,10 +381,6 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { const origin = typeof req.headers.origin === "string" ? req.headers.origin : undefined; if (!extensionOriginAllowed(origin, extensionId)) { @@ -415,7 +402,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise, enabled: toolFilter.enabled, - actionsAllowed: allowActions || actionsConfirmed(), + actionsAllowed: capabilityPolicy.allowInput || panelEnabled, }); if (!decision.ok) { res.status(403).json({ error: decision.error, code: decision.code }); @@ -573,6 +560,24 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { + try { + const url = typeof req.body?.url === "string" ? req.body.url.trim() : ""; + if (!url) { + res.status(400).json({ error: "url is required" }); + return; + } + const tabId = req.body?.tabId; + const result = await navigateTab({ + url, + ...(tabId !== undefined ? { tabId } : {}), + }); + res.json(result); + } catch (error) { + respondWithError(res, error); + } + }); + api.post("/storage", async (req: Request, res: Response) => { try { const kinds = parseList(req.body?.kinds) ?? ["localStorage", "sessionStorage"]; @@ -625,10 +630,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise log.error("HTTP server error:", error)); - const wss = new WebSocketServer({ - noServer: true, - handleProtocols: (protocols) => (protocols.has(WEBSOCKET_PROTOCOL) ? WEBSOCKET_PROTOCOL : false), - }); + const wss = new WebSocketServer({ noServer: true }); wss.on("error", (error) => log.error("WebSocket server error:", error)); server.on("upgrade", (req, socket: Duplex, head) => { @@ -638,30 +640,32 @@ export async function createConnector(config: ConnectorConfig = {}): Promise presented && tokensMatch(presented, token))) { - return rejectUpgrade(socket, 401, "Unauthorized"); + + const origin = req.headers.origin; + if (origin) { + // A browser sets Origin itself, so a page origin here means a web page is + // trying to impersonate the extension. + if (!isExtensionOrigin(origin)) { + log.warn(`Rejected websocket upgrade from origin ${origin}`); + return rejectUpgrade(socket, 403, "Forbidden origin"); + } + if (!extensionOriginAllowed(origin, extensionId)) { + log.warn("Rejected websocket upgrade from a non-matching extension id"); + return rejectUpgrade(socket, 403, "Forbidden origin"); + } + } else { + // No Origin means a non-browser client; it must prove it knows the token. + const authorization = typeof req.headers.authorization === "string" ? req.headers.authorization : ""; + const candidates = [ + bearerToken(authorization), + ...websocketProtocolTokens(req.headers["sec-websocket-protocol"]), + ]; + if (!candidates.some((presented) => presented && tokensMatch(presented, token))) { + return rejectUpgrade(socket, 401, "Unauthorized"); + } } wss.handleUpgrade(req, socket, head, (ws) => wss.emit("connection", ws, req)); @@ -678,7 +682,6 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { + const requestedUrl = parseHttpUrl(options.url.trim()).href; + const tabId = resolveTabId(options.tabId); + if (tabId === null) { + throw new ExtensionRequestError( + "No tab is selected. Call listBrowserTabs and pass tabId, or open DevTools on the tab you mean." + ); + } + const gate = await checkCapability("navigate", { tabId, destinationUrl: requestedUrl }); + if (!gate.allowed) { + throw new ExtensionRequestError(gate.reason); + } + const worker = workerConnection(); + if (!worker) { + throw new ExtensionRequestError( + "The extension service worker is not connected. Reload the extension or restart the browser, then try again." + ); + } + const response = await requestFromExtension(worker, "navigate-tab", { + tabId, + url: requestedUrl, + }); + const finalUrl = + typeof response["finalUrl"] === "string" ? response["finalUrl"] : requestedUrl; + return { + tabId, + requestedUrl, + finalUrl, + wasDiscarded: response["wasDiscarded"] === true, + }; + } + async function readStorage( kinds: string[], options: { tabId?: TabId } = {} @@ -1570,6 +1610,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise { - const onListening = () => { - server.off("error", onError); - const address = server.address(); - resolve(typeof address === "object" && address ? address.port : port); - }; - const onError = (error: NodeJS.ErrnoException) => { - // listen() registers onListening before the bind is attempted. A - // failed attempt leaves it in place, so a walk across taken ports - // stacks one listener per try and every one of them runs if a later - // port succeeds. - server.off("listening", onListening); if (error.code === "EADDRINUSE" && remaining > 1 && startPort !== 0) { remaining -= 1; port += 1; @@ -1713,7 +1740,11 @@ function listen( }; server.once("error", onError); - server.listen(port, host, onListening); + server.listen(port, host, () => { + server.off("error", onError); + const address = server.address(); + resolve(typeof address === "object" && address ? address.port : port); + }); }; tryListen(); diff --git a/browser-tools-mcp/src/mcp/client.ts b/browser-tools-mcp/src/mcp/client.ts index e8b00f21..1a185290 100644 --- a/browser-tools-mcp/src/mcp/client.ts +++ b/browser-tools-mcp/src/mcp/client.ts @@ -40,6 +40,13 @@ export interface ConnectorStatus { counts: { console: number; network: number }; } +export interface NavigateResult { + tabId: TabId; + requestedUrl: string; + finalUrl: string; + wasDiscarded: boolean; +} + export interface ScreenshotResult { path: string; tabId?: TabId | null; @@ -68,6 +75,7 @@ export interface ConnectorClient { wipe(options?: { tabId?: TabId }): Promise; screenshot(options: { name?: string; tabId?: TabId }): Promise; refresh(options?: { tabId?: TabId }): Promise; + navigate(options: { url: string; tabId?: TabId }): Promise; storage(kinds: string[], options?: { tabId?: TabId }): Promise>; audit( category: AuditCategory, @@ -147,6 +155,10 @@ export class InProcessConnectorClient implements ConnectorClient { return this.#connector.refreshTab(options); } + async navigate(options: { url: string; tabId?: TabId }): Promise { + return this.#connector.navigateTab(options); + } + async storage( kinds: string[], options: { tabId?: TabId } = {} @@ -269,6 +281,10 @@ export class HttpConnectorClient implements ConnectorClient { await this.#request("/api/refresh", { method: "POST", body: options }); } + navigate(options: { url: string; tabId?: TabId }): Promise { + return this.#request("/api/navigate", { method: "POST", body: options }); + } + async storage( kinds: string[], options: { tabId?: TabId } = {} diff --git a/browser-tools-mcp/src/mcp/resource-cli.ts b/browser-tools-mcp/src/mcp/resource-cli.ts new file mode 100644 index 00000000..b43f97bf --- /dev/null +++ b/browser-tools-mcp/src/mcp/resource-cli.ts @@ -0,0 +1,43 @@ +import type { ConnectorClient } from "./client.js"; +import { buildHar } from "../util/har.js"; +import { scopeToOptions } from "./resources.js"; + +export const ALL_RESOURCE_COMMANDS = [ + "console-history", + "network-history", + "network-har", + "screenshot", + "audit-report", +] as const; + +export type ResourceCommandName = (typeof ALL_RESOURCE_COMMANDS)[number]; + +export async function fetchResource( + name: ResourceCommandName, + client: ConnectorClient, + scope: string +): Promise { + switch (name) { + case "console-history": + return client.exportConsole(scopeToOptions(scope)); + case "network-history": + return client.exportNetwork(scopeToOptions(scope)); + case "network-har": { + const exported = await client.exportNetwork(scopeToOptions(scope)); + return buildHar(exported.entries); + } + case "screenshot": { + const artifact = await client.readArtifact("screenshot", decodeURIComponent(scope)); + return { + mimeType: artifact.mimeType, + ...(artifact.blob !== undefined ? { blob: artifact.blob } : { text: artifact.text ?? "" }), + }; + } + case "audit-report": { + const artifact = await client.readArtifact("audit", decodeURIComponent(scope)); + return artifact.text ? JSON.parse(artifact.text) : null; + } + default: + throw new Error(`Unknown resource: ${name satisfies never}`); + } +} diff --git a/browser-tools-mcp/src/mcp/server.ts b/browser-tools-mcp/src/mcp/server.ts index 0ff888ce..674c0979 100644 --- a/browser-tools-mcp/src/mcp/server.ts +++ b/browser-tools-mcp/src/mcp/server.ts @@ -594,6 +594,49 @@ const TOOLS: ToolDefinition[] = [ ); }, }, + { + name: "navigateBrowser", + register(server, client) { + server.registerTool( + "navigateBrowser", + { + title: "Navigate to a URL", + description: + "Loads a URL in the chosen browser tab without focusing it or attaching the debugger. " + + "Uses the tabId from listBrowserTabs. Requires the extension service worker, the popup " + + "switch, and --allow-input on browser-tools-mcp (browser-tools CLI: --allow-actions).", + inputSchema: { + url: z.string().describe("http(s) URL to load in the tab"), + tabId: tabIdInput, + }, + outputSchema: { + tabId: z.union([z.number(), z.string()]), + requestedUrl: z.string(), + finalUrl: z.string(), + wasDiscarded: z.boolean(), + }, + annotations: { + title: "Navigate to a URL", + readOnlyHint: false, + destructiveHint: false, + idempotentHint: false, + openWorldHint: true, + }, + }, + async ({ url, tabId }) => { + try { + const result = await client.navigate({ + url, + ...(tabId !== undefined ? { tabId } : {}), + }); + return ok(result as unknown as Record); + } catch (error) { + return fail(error); + } + } + ); + }, + }, { name: "refreshBrowser", register(server, client) { diff --git a/browser-tools-mcp/src/mcp/tool-invoke.ts b/browser-tools-mcp/src/mcp/tool-invoke.ts new file mode 100644 index 00000000..6227347e --- /dev/null +++ b/browser-tools-mcp/src/mcp/tool-invoke.ts @@ -0,0 +1,333 @@ +import type { ConnectorClient } from "./client.js"; +import { + auditUri, + consoleUri, + harUri, + networkUri, + screenshotUri, +} from "./resources.js"; +import type { AuditCategory } from "../lighthouse/types.js"; + +export type ToolContent = + | { type: "text"; text: string } + | { type: "image"; data: string; mimeType: string } + | { + type: "resource_link"; + uri: string; + name: string; + description?: string; + mimeType?: string; + }; + +export type ToolResult = { + content: ToolContent[]; + structuredContent?: Record; + isError?: boolean; +}; + +function link( + uri: string, + name: string, + description: string, + mimeType = "application/json" +): ToolContent { + return { type: "resource_link", uri, name, description, mimeType }; +} + +function ok(structured: Record, extraContent: ToolContent[] = []): ToolResult { + return { + content: [{ type: "text", text: JSON.stringify(structured, null, 2) }, ...extraContent], + structuredContent: structured, + }; +} + +function fail(error: unknown): ToolResult { + const message = error instanceof Error ? error.message : String(error); + return { content: [{ type: "text", text: message }], isError: true }; +} + +function truncationLinks(result: { truncated: boolean; tabId: unknown }): ToolContent[] { + if (!result.truncated) return []; + const tabId = result.tabId as string | number | null; + return [ + link( + consoleUri(tabId), + "console-history", + "Every captured console entry, without the per-call size budget" + ), + ]; +} + +function networkLinks(result: { + truncated: boolean; + total: number; + tabId: unknown; +}): ToolContent[] { + const tabId = result.tabId as string | number | null; + const links: ToolContent[] = []; + if (result.total > 0) { + links.push( + link(harUri(tabId), "network-har", "This tab's network activity as a HAR file") + ); + } + if (result.truncated) { + links.push( + link( + networkUri(tabId), + "network-history", + "Every captured request, without the per-call size budget" + ) + ); + } + return links; +} + +/** Hides values while still showing which keys exist. */ +function summariseStorage(storage: Record): Record { + const out: Record = {}; + + for (const [kind, value] of Object.entries(storage)) { + if (Array.isArray(value)) { + const names = value + .map((item) => + item && typeof item === "object" && "name" in item ? String((item as any).name) : null + ) + .filter((name): name is string => Boolean(name)); + out[kind] = { names, count: value.length }; + } else if (value && typeof value === "object") { + const keys = Object.keys(value as Record); + out[kind] = { keys, count: keys.length }; + } else { + out[kind] = { keys: [], count: 0 }; + } + } + + return out; +} + +function tabIdFrom(args: Record): number | string | undefined { + const tabId = args["tabId"]; + if (typeof tabId === "number" || typeof tabId === "string") return tabId; + return undefined; +} + +/** + * Runs one MCP tool by name. Kept in step with the MCP server's tool list — + * parity tests fail when a tool is added on one side and not the other. + */ +export async function invokeTool( + name: string, + client: ConnectorClient, + args: Record = {} +): Promise { + switch (name) { + case "listBrowserTabs": + try { + return ok((await client.tabs()) as unknown as Record); + } catch (error) { + return fail(error); + } + case "getConsoleLogs": + try { + const result = await client.console({ ...args }); + return ok(result as unknown as Record, truncationLinks(result)); + } catch (error) { + return fail(error); + } + case "getConsoleErrors": + try { + const result = await client.console({ ...args, errorsOnly: true }); + return ok(result as unknown as Record, truncationLinks(result)); + } catch (error) { + return fail(error); + } + case "getNetworkLogs": + try { + const result = await client.network({ ...args }); + return ok(result as unknown as Record, networkLinks(result)); + } catch (error) { + return fail(error); + } + case "getNetworkErrors": + try { + const result = await client.network({ ...args, errorsOnly: true }); + return ok(result as unknown as Record, networkLinks(result)); + } catch (error) { + return fail(error); + } + case "getSelectedElement": + try { + const tabId = tabIdFrom(args); + const element = (await client.selectedElement( + tabId !== undefined ? { tabId } : {} + )) as Record | null; + return ok({ element }); + } catch (error) { + return fail(error); + } + case "getPageInfo": + try { + return ok((await client.page()) as unknown as Record); + } catch (error) { + return fail(error); + } + case "getConnectionStatus": + try { + return ok((await client.status()) as unknown as Record); + } catch (error) { + return fail(error); + } + case "takeScreenshot": { + try { + const nameArg = typeof args["name"] === "string" ? args["name"] : undefined; + const tabId = tabIdFrom(args); + const result = await client.screenshot({ + ...(nameArg ? { name: nameArg } : {}), + ...(tabId !== undefined ? { tabId } : {}), + }); + const base64 = result.data.replace(/^data:[^;]+;base64,/, ""); + const structured = { + path: result.path, + name: result.name, + mimeType: result.mimeType, + bytes: result.bytes, + imageIncluded: result.withinBudget, + tabId: result.tabId ?? null, + url: result.url ?? "", + }; + const asResource = link( + screenshotUri(result.name), + result.name, + "The captured screenshot", + result.mimeType + ); + if (!result.withinBudget) { + return ok(structured, [ + { + type: "text", + text: + `The screenshot is ${Math.round(result.bytes / 1024)} KB, too large to include here. ` + + `It was saved to ${result.path} and can be read from the linked resource.`, + }, + asResource, + ]); + } + return ok(structured, [ + { type: "image", data: base64, mimeType: result.mimeType }, + asResource, + ]); + } catch (error) { + return fail(error); + } + } + case "refreshBrowser": + try { + const tabId = tabIdFrom(args); + await client.refresh(tabId !== undefined ? { tabId } : {}); + return ok({ ok: true }); + } catch (error) { + return fail(error); + } + case "navigateBrowser": { + try { + const url = args["url"]; + if (typeof url !== "string" || !url.trim()) { + return fail(new Error("url is required")); + } + const tabId = tabIdFrom(args); + const result = await client.navigate({ + url: url.trim(), + ...(tabId !== undefined ? { tabId } : {}), + }); + return ok(result as unknown as Record); + } catch (error) { + return fail(error); + } + } + case "getBrowserStorage": { + try { + const kinds = Array.isArray(args["kinds"]) + ? (args["kinds"] as string[]) + : undefined; + const includeValues = args["includeValues"] === true; + const tabId = tabIdFrom(args); + const requested = kinds?.length ? kinds : ["localStorage", "sessionStorage"]; + const raw = await client.storage(requested, tabId !== undefined ? { tabId } : {}); + return ok({ + storage: includeValues ? raw : summariseStorage(raw), + includedValues: Boolean(includeValues), + }); + } catch (error) { + return fail(error); + } + } + case "wipeLogs": + try { + const tabId = tabIdFrom(args); + await client.wipe(tabId !== undefined ? { tabId } : {}); + return ok({ ok: true }); + } catch (error) { + return fail(error); + } + case "runAccessibilityAudit": + return runAudit(client, "accessibility", args); + case "runPerformanceAudit": + return runAudit(client, "performance", args); + case "runSEOAudit": + return runAudit(client, "seo", args); + case "runBestPracticesAudit": + return runAudit(client, "best-practices", args); + default: + throw new Error(`Unknown tool: ${name}`); + } +} + +async function runAudit( + client: ConnectorClient, + category: AuditCategory, + args: Record +): Promise { + try { + const url = typeof args["url"] === "string" ? args["url"] : undefined; + const tabId = tabIdFrom(args); + const report = await client.audit(category, { + ...(url ? { url } : {}), + ...(tabId !== undefined ? { tabId } : {}), + }); + return ok( + report as unknown as Record, + report.reportId + ? [ + link( + auditUri(report.reportId), + `${category}-report`, + "The unabridged Lighthouse result behind this summary" + ), + ] + : [] + ); + } catch (error) { + return fail(error); + } +} + +/** Every registered MCP tool name must have an invoke implementation. */ +export const INVOKABLE_TOOL_NAMES: readonly string[] = [ + "listBrowserTabs", + "getConsoleLogs", + "getConsoleErrors", + "getNetworkLogs", + "getNetworkErrors", + "getSelectedElement", + "getPageInfo", + "getConnectionStatus", + "takeScreenshot", + "refreshBrowser", + "navigateBrowser", + "getBrowserStorage", + "wipeLogs", + "runAccessibilityAudit", + "runPerformanceAudit", + "runSEOAudit", + "runBestPracticesAudit", +]; diff --git a/browser-tools-mcp/src/runtime.ts b/browser-tools-mcp/src/runtime.ts index ed7b702d..b2d458b1 100644 --- a/browser-tools-mcp/src/runtime.ts +++ b/browser-tools-mcp/src/runtime.ts @@ -69,6 +69,9 @@ class UnavailableConnectorClient implements ConnectorClient { refresh(): Promise { return this.#fail(); } + navigate(): Promise { + return this.#fail(); + } storage(): Promise { return this.#fail(); } @@ -178,14 +181,13 @@ export async function createRuntime(options: CliOptions): Promise { verbose: options.verbose, ...(options.auditAllowedOrigins ? { auditAllowedOrigins: options.auditAllowedOrigins } : {}), auditAllowPrivateNetwork: options.auditAllowPrivateNetwork, - ...(options.enabledTools ? { enabledTools: options.enabledTools } : {}), - ...(options.disabledTools ? { disabledTools: options.disabledTools } : {}), - allowActions: options.allowActions, - ...(options.extensionId ? { extensionId: options.extensionId } : {}), allowEval: options.allowEval, allowInput: options.allowInput, ...(options.allowInputOrigins ? { allowInputOrigins: options.allowInputOrigins } : {}), ...(options.excludeOrigins ? { excludeOrigins: options.excludeOrigins } : {}), + ...(options.enabledTools ? { enabledTools: options.enabledTools } : {}), + ...(options.disabledTools ? { disabledTools: options.disabledTools } : {}), + ...(options.extensionId ? { extensionId: options.extensionId } : {}), }); writeSessionFile({ diff --git a/browser-tools-mcp/src/tools-cli-bin.ts b/browser-tools-mcp/src/tools-cli-bin.ts new file mode 100644 index 00000000..dba962a6 --- /dev/null +++ b/browser-tools-mcp/src/tools-cli-bin.ts @@ -0,0 +1,15 @@ +#!/usr/bin/env node +import { runToolsCli } from "./tools-cli.js"; +import { createLogger, setLogLevel } from "./util/logger.js"; + +const log = createLogger("tools-cli"); + +runToolsCli(process.argv.slice(2)) + .then((code) => { + process.exitCode = code; + }) + .catch((error) => { + setLogLevel("error"); + log.error("Fatal error:", error); + process.exit(1); + }); diff --git a/browser-tools-mcp/src/tools-cli.ts b/browser-tools-mcp/src/tools-cli.ts new file mode 100644 index 00000000..193dc550 --- /dev/null +++ b/browser-tools-mcp/src/tools-cli.ts @@ -0,0 +1,171 @@ +import { parseCli, readPackageVersion, type CliOptions } from "./cli.js"; +import { createRuntime } from "./runtime.js"; +import { invokeTool, INVOKABLE_TOOL_NAMES } from "./mcp/tool-invoke.js"; +import { ALL_TOOL_NAMES } from "./mcp/server.js"; +import { + ALL_RESOURCE_COMMANDS, + fetchResource, + type ResourceCommandName, +} from "./mcp/resource-cli.js"; + +export interface ToolsCliParseResult { + options: CliOptions; + command?: string; + argsJson: string; +} + +/** + * Parses argv for the browser-tools CLI. + * + * Capability gating uses `--allow-actions` only (maps to connector `--allow-input`). + * The MCP server binary keeps separate `--allow-eval` / `--allow-input` flags. + */ +export function parseToolsCli( + argv: string[], + env: NodeJS.ProcessEnv = process.env +): ToolsCliParseResult { + let allowActions = false; + const connectorArgv: string[] = []; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]!; + if (arg === "--allow-actions") { + allowActions = true; + continue; + } + if (arg.startsWith("--allow-eval") || arg.startsWith("--allow-input")) { + throw new Error( + "browser-tools uses --allow-actions for navigation and other input, not --allow-eval or --allow-input" + ); + } + connectorArgv.push(arg); + } + + const parsed = parseCli(connectorArgv, env); + if (allowActions) { + parsed.allowInput = true; + } + + const positional: string[] = []; + for (let i = 0; i < connectorArgv.length; i++) { + const arg = connectorArgv[i]!; + if (arg.startsWith("-")) { + if ( + arg === "--port" || + arg === "--host" || + arg === "--screenshot-dir" || + arg === "--connect" || + arg === "--token" || + arg === "--only" || + arg === "--exclude" || + arg === "--audit-allow-origin" || + arg === "--allow-input-origins" || + arg === "--exclude-origins" || + arg === "--extension-id" + ) { + i++; + } + continue; + } + positional.push(arg); + } + + const command = positional[0]; + const argsJson = positional[1] ?? "{}"; + return { options: parsed, ...(command ? { command } : {}), argsJson }; +} + +export function toolsHelpText(): string { + return `BrowserTools CLI — mirror of the Browser Tools MCP server + +Usage: + browser-tools [connector options] ['{"arg":"value"}'] + +Connector options match browser-tools-mcp except capability gating: + --allow-actions Allow navigation and other input (maps to connector input policy). + Not --allow-eval / --allow-input. No environment variable. + --allow-input-origins, --exclude-origins, --connect, --token, --port, … + +Tool commands (same names and JSON args as the MCP tools): + ${ALL_TOOL_NAMES.join(", ")} + +Resource commands: + browser-tools resource + Names: ${ALL_RESOURCE_COMMANDS.join(", ")} + +Examples: + browser-tools getConnectionStatus + browser-tools getConsoleLogs '{"limit":20}' + browser-tools --allow-actions navigateBrowser '{"url":"http://localhost:3000/","tabId":1}' +`; +} + +export async function runToolsCli(argv: string[]): Promise { + let parsed: ToolsCliParseResult; + try { + parsed = parseToolsCli(argv); + } catch (error) { + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } + + const { options, command, argsJson } = parsed; + + if (options.showVersion) { + process.stdout.write(`${readPackageVersion()}\n`); + return 0; + } + if (options.showHelp || !command) { + process.stdout.write(toolsHelpText()); + return command ? 0 : options.showHelp ? 0 : 1; + } + + let args: Record = {}; + if (command !== "resource" && argsJson.trim()) { + try { + const value = JSON.parse(argsJson) as unknown; + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + args = value as Record; + } else { + process.stderr.write("Tool arguments must be a JSON object\n"); + return 1; + } + } catch (error) { + process.stderr.write( + `Could not parse tool arguments as JSON: ${error instanceof Error ? error.message : String(error)}\n` + ); + return 1; + } + } + + const runtime = await createRuntime(options); + try { + if (command === "resource") { + const parts = argsJson.trim().split(/\s+/); + const resourceName = parts[0] as ResourceCommandName | undefined; + const scope = parts.slice(1).join(" ") || "all"; + if (!resourceName || !ALL_RESOURCE_COMMANDS.includes(resourceName)) { + process.stderr.write(`Unknown resource. Choose one of: ${ALL_RESOURCE_COMMANDS.join(", ")}\n`); + return 1; + } + const payload = await fetchResource(resourceName, runtime.client, scope); + process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`); + return 0; + } + + if (!INVOKABLE_TOOL_NAMES.includes(command) && !ALL_TOOL_NAMES.includes(command)) { + process.stderr.write(`Unknown command: ${command}\n`); + return 1; + } + + const result = await invokeTool(command, runtime.client, args); + if (result.structuredContent) { + process.stdout.write(`${JSON.stringify(result.structuredContent, null, 2)}\n`); + } else if (result.content[0]?.type === "text") { + process.stdout.write(`${result.content[0].text}\n`); + } + return result.isError ? 1 : 0; + } finally { + await runtime.close(); + } +} diff --git a/browser-tools-mcp/test/helpers/fake-extension.ts b/browser-tools-mcp/test/helpers/fake-extension.ts index ff0d63b5..d2931ad2 100644 --- a/browser-tools-mcp/test/helpers/fake-extension.ts +++ b/browser-tools-mcp/test/helpers/fake-extension.ts @@ -14,6 +14,7 @@ export interface FakeExtensionOptions { /** Respond to capture-screenshot requests. Defaults to returning TINY_PNG_BASE64. */ onScreenshot?: (msg: any) => Promise | unknown; onRefresh?: (msg: any) => Promise | unknown; + onNavigate?: (msg: any) => Promise | unknown; onStorage?: (msg: any) => Promise | unknown; /** `worker` answers capability probes and is not a DevTools tab. */ role?: "devtools" | "worker"; @@ -105,6 +106,14 @@ export class FakeExtension { this.send({ type: "refresh-result", requestId: msg.requestId, ...(payload as object) }); break; } + case "navigate-tab": { + const custom = this.#options.onNavigate; + const payload = custom + ? await custom(msg) + : { ok: true, finalUrl: msg.url, wasDiscarded: false }; + this.send({ type: "navigate-result", requestId: msg.requestId, ...(payload as object) }); + break; + } case "get-storage": { const custom = this.#options.onStorage; const payload = custom diff --git a/browser-tools-mcp/test/integration/attach.test.ts b/browser-tools-mcp/test/integration/attach.test.ts index 0f697d68..d5a6bb33 100644 --- a/browser-tools-mcp/test/integration/attach.test.ts +++ b/browser-tools-mcp/test/integration/attach.test.ts @@ -7,7 +7,7 @@ import { CONNECTOR_BIND_ATTEMPTS, createConnector, type Connector } from "../../ import { holdConsecutivePorts } from "../helpers/port"; import { HttpConnectorClient } from "../../src/mcp/client"; import { createRuntime } from "../../src/runtime"; -import { writeSessionFile, readSessionFile } from "../../src/util/session"; +import { writeSessionFile, readSessionFile, clearSessionFile } from "../../src/util/session"; import { FakeExtension, TINY_PNG_BASE64 } from "../helpers/fake-extension"; import type { CliOptions } from "../../src/cli"; @@ -28,7 +28,8 @@ const baseOptions: CliOptions = { redact: true, standalone: false, auditAllowPrivateNetwork: false, - allowActions: false, + allowEval: false, + allowInput: false, }; beforeEach(async () => { @@ -40,7 +41,7 @@ beforeEach(async () => { port: 0, screenshotDir, requestTimeoutMs: 3_000, - allowActions: true, + allowInput: true, // Hermetic: audit targets are resolved before the runner is called. auditLookup: async () => ["93.184.215.14"], auditRunner: async ({ url, category }) => ({ @@ -386,6 +387,7 @@ describe("runtime attach behaviour", () => { // CONNECTOR_BIND_ATTEMPTS, so hold that whole run. const held = await holdConsecutivePorts(CONNECTOR_BIND_ATTEMPTS); try { + clearSessionFile(); const runtime = await createRuntime({ ...baseOptions, port: held.startPort }); expect(runtime.degradedReason).toBeTruthy(); diff --git a/browser-tools-mcp/test/integration/connector-flow.test.ts b/browser-tools-mcp/test/integration/connector-flow.test.ts index 4a8f37f1..c2b76553 100644 --- a/browser-tools-mcp/test/integration/connector-flow.test.ts +++ b/browser-tools-mcp/test/integration/connector-flow.test.ts @@ -19,7 +19,7 @@ beforeEach(async () => { screenshotDir, heartbeatIntervalMs: 200, requestTimeoutMs: 3_000, - allowActions: true, + allowInput: true, }); }); diff --git a/browser-tools-mcp/test/integration/connector-security.test.ts b/browser-tools-mcp/test/integration/connector-security.test.ts index 5378b391..cfe6d43c 100644 --- a/browser-tools-mcp/test/integration/connector-security.test.ts +++ b/browser-tools-mcp/test/integration/connector-security.test.ts @@ -23,7 +23,7 @@ let screenshotDir: string; beforeAll(async () => { screenshotDir = fs.mkdtempSync(path.join(os.tmpdir(), "bt-sec-")); - connector = await createConnector({ port: 0, screenshotDir, allowActions: true }); + connector = await createConnector({ port: 0, screenshotDir, allowInput: true }); }); afterAll(async () => { @@ -154,25 +154,17 @@ describe("HTTP authentication", () => { describe("websocket upgrade", () => { const bearer = () => ({ Authorization: `Bearer ${connector.token}` }); - it("rejects a chrome extension origin that does not present the token", async () => { + it("accepts a chrome extension origin without a separate token check", async () => { const result = await tryWebSocket(`ws://127.0.0.1:${connector.port}/extension-ws`, { origin: EXAMPLE_CHROME_EXTENSION_ORIGIN, }); - expect(result.accepted).toBe(false); - }); - - it("accepts a chrome extension origin that presents the token", async () => { - const result = await tryWebSocket(`ws://127.0.0.1:${connector.port}/extension-ws`, { - origin: EXAMPLE_CHROME_EXTENSION_ORIGIN, - headers: bearer(), - }); expect(result.accepted).toBe(true); }); - it("accepts the token as a websocket subprotocol, which is how the extension sends it", async () => { + it("still accepts a chrome extension origin that also presents the token", async () => { const result = await tryWebSocket(`ws://127.0.0.1:${connector.port}/extension-ws`, { origin: EXAMPLE_CHROME_EXTENSION_ORIGIN, - protocols: ["browser-tools", connector.token], + headers: bearer(), }); expect(result.accepted).toBe(true); }); diff --git a/browser-tools-mcp/test/integration/local-api-policy.test.ts b/browser-tools-mcp/test/integration/local-api-policy.test.ts index c6b7031e..9b00c672 100644 --- a/browser-tools-mcp/test/integration/local-api-policy.test.ts +++ b/browser-tools-mcp/test/integration/local-api-policy.test.ts @@ -20,7 +20,7 @@ describe("tool filtering on the local API", () => { beforeAll(async () => { connector = await createConnector({ port: 0, - allowActions: true, + allowInput: true, enabledTools: ["getConsoleLogs", "getPageInfo", "wipeLogs", "runPerformanceAudit"], disabledTools: ["wipeLogs"], auditLookup: async () => ["93.184.215.14"], @@ -97,7 +97,7 @@ describe("confirmation gate on state-changing local API calls", () => { const ext = new FakeExtension({ port: connector.port }); await ext.connect(); await ext.waitForWelcome(); - ext.send({ type: "actions-confirmed", confirmed: true }); + ext.send({ type: "capability-state", panelEnabled: true, popupEnabled: false, excludeOrigins: [] }); await vi.waitFor(async () => { const allowed = await request(connector.app).post("/api/wipe").set(auth).send({}); @@ -113,7 +113,7 @@ describe("confirmation gate on state-changing local API calls", () => { }); it("allows those calls when the connector was started with --allow-actions", async () => { - const open = await createConnector({ port: 0, allowActions: true }); + const open = await createConnector({ port: 0, allowInput: true }); try { const res = await request(open.app) .post("/api/tabs/select") diff --git a/browser-tools-mcp/test/integration/mcp-server.test.ts b/browser-tools-mcp/test/integration/mcp-server.test.ts index 14d06d3b..2efdc3c3 100644 --- a/browser-tools-mcp/test/integration/mcp-server.test.ts +++ b/browser-tools-mcp/test/integration/mcp-server.test.ts @@ -71,6 +71,7 @@ describe("tool registration", () => { "getPageInfo", "getSelectedElement", "listBrowserTabs", + "navigateBrowser", "refreshBrowser", "runAccessibilityAudit", "runBestPracticesAudit", diff --git a/browser-tools-mcp/test/integration/navigate.test.ts b/browser-tools-mcp/test/integration/navigate.test.ts new file mode 100644 index 00000000..9b356eef --- /dev/null +++ b/browser-tools-mcp/test/integration/navigate.test.ts @@ -0,0 +1,86 @@ +import { afterEach, describe, expect, it } from "vitest"; +import os from "node:os"; +import path from "node:path"; +import { createConnector } from "../../src/connector/connector"; +import { GateReason } from "../../src/gates/capability"; +import { FakeExtension } from "../helpers/fake-extension"; + +describe("navigateBrowser", () => { + let connector: Awaited> | undefined; + let devtools: FakeExtension | undefined; + let worker: FakeExtension | undefined; + let probePopup = false; + + afterEach(async () => { + await devtools?.close(); + await worker?.close(); + await connector?.close(); + probePopup = false; + }); + + it("navigates when input is allowed and the worker confirms the popup switch", async () => { + const screenshotDir = path.join(os.tmpdir(), `bt-nav-${Date.now()}`); + connector = await createConnector({ port: 0, screenshotDir, allowInput: true }); + devtools = new FakeExtension({ port: connector.port, tabId: 7 }); + worker = new FakeExtension({ + port: connector.port, + role: "worker", + onCapabilityProbe: () => ({ + popupEnabled: probePopup, + panelEnabled: false, + liveUrl: "http://127.0.0.1:3000/", + excludeOrigins: [], + }), + onNavigate: async (msg) => ({ + ok: true, + finalUrl: msg.url, + wasDiscarded: false, + }), + }); + await devtools.connect(); + await worker.connect(); + worker.send({ type: "capability-state", popupEnabled: true }); + probePopup = true; + + await expect.poll(async () => + (await connector.checkCapability("navigate", { + tabId: 7, + destinationUrl: "http://127.0.0.1:3000/next", + })).allowed + ).toBe(true); + + const result = await connector.navigateTab({ + tabId: 7, + url: "http://127.0.0.1:3000/next", + }); + expect(result.finalUrl).toBe("http://127.0.0.1:3000/next"); + expect(result.tabId).toBe(7); + }); + + it("refuses navigation when allowInput is off", async () => { + const screenshotDir = path.join(os.tmpdir(), `bt-nav-deny-${Date.now()}`); + connector = await createConnector({ port: 0, screenshotDir, allowInput: false }); + devtools = new FakeExtension({ port: connector.port, tabId: 3 }); + worker = new FakeExtension({ + port: connector.port, + role: "worker", + onCapabilityProbe: () => ({ + popupEnabled: probePopup, + panelEnabled: false, + liveUrl: "http://127.0.0.1:3000/", + excludeOrigins: [], + }), + }); + await devtools.connect(); + await worker.connect(); + worker.send({ type: "capability-state", popupEnabled: true }); + probePopup = true; + + await expect.poll(async () => + (await connector.checkCapability("navigate", { + tabId: 3, + destinationUrl: "http://127.0.0.1:3000/next", + })).reason + ).toBe(GateReason.inputOff); + }); +}); diff --git a/browser-tools-mcp/test/unit/cli-audit-flags.test.ts b/browser-tools-mcp/test/unit/cli-audit-flags.test.ts index cba24183..0a1a6c64 100644 --- a/browser-tools-mcp/test/unit/cli-audit-flags.test.ts +++ b/browser-tools-mcp/test/unit/cli-audit-flags.test.ts @@ -15,12 +15,11 @@ describe("audit flags", () => { for (const value of ["false", "0", "", "yes"]) expect(allows(value), value).toBe(false); }); - it("reads --allow-actions and --extension-id the same way as the other switches", () => { - expect(parseCli([], {}).allowActions).toBe(false); - expect(parseCli([], {}).extensionId).toBeUndefined(); - expect(parseCli(["--allow-actions"], {}).allowActions).toBe(true); - expect(parseCli([], { BROWSER_TOOLS_ALLOW_ACTIONS: "1" }).allowActions).toBe(true); - expect(parseCli([], { BROWSER_TOOLS_ALLOW_ACTIONS: "yes" }).allowActions).toBe(false); + it("keeps capability flags argv-only and reads --extension-id from argv or env", () => { + expect(parseCli([], {}).allowInput).toBe(false); + expect(parseCli([], {}).allowEval).toBe(false); + expect(parseCli(["--allow-input"], {}).allowInput).toBe(true); + expect(parseCli([], { BROWSER_TOOLS_ALLOW_ACTIONS: "1" }).allowInput).toBe(false); expect(parseCli(["--extension-id", "abcdefghijklmnopabcdefghijklmnop"], {}).extensionId).toBe( "abcdefghijklmnopabcdefghijklmnop" ); diff --git a/browser-tools-mcp/test/unit/extension-gates.test.ts b/browser-tools-mcp/test/unit/extension-gates.test.ts index a17df3b3..a518bbd3 100644 --- a/browser-tools-mcp/test/unit/extension-gates.test.ts +++ b/browser-tools-mcp/test/unit/extension-gates.test.ts @@ -109,11 +109,11 @@ describe("extension confirmBeforeAct", () => { describe("worker probe", () => { const worker = fs.readFileSync(path.join(extensionDir, "worker.js"), "utf8"); - it("reads the tab itself and does not perform page actions or hide the banner", () => { + it("reads tabs for probes and navigate without the debugger or focus changes", () => { expect(worker).toContain("tabs.get"); - expect(worker).not.toContain("message.url"); + expect(worker).toContain("navigate-tab"); + expect(worker).toMatch(/tabs\.update\([^)]*active:\s*false/); expect(worker).not.toMatch(/chrome\.debugger|api\.debugger|\.attach\(/); - expect(worker).not.toContain("tabs.update"); expect(worker).not.toContain("windows.update"); expect(worker).not.toContain("executeScript"); expect(worker).not.toContain("silent-debugger"); diff --git a/browser-tools-mcp/test/unit/tools-cli.test.ts b/browser-tools-mcp/test/unit/tools-cli.test.ts new file mode 100644 index 00000000..e5987ce4 --- /dev/null +++ b/browser-tools-mcp/test/unit/tools-cli.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; +import { parseToolsCli } from "../../src/tools-cli"; +import { ALL_TOOL_NAMES } from "../../src/mcp/server"; +import { INVOKABLE_TOOL_NAMES } from "../../src/mcp/tool-invoke"; + +describe("tools CLI", () => { + it("maps --allow-actions to connector allowInput, not allowEval", () => { + const parsed = parseToolsCli(["--allow-actions", "getPageInfo"], {}); + expect(parsed.options.allowInput).toBe(true); + expect(parsed.options.allowEval).toBe(false); + expect(parsed.command).toBe("getPageInfo"); + }); + + it("rejects MCP-only capability flags", () => { + expect(() => parseToolsCli(["--allow-input", "getPageInfo"], {})).toThrow(/allow-actions/); + expect(() => parseToolsCli(["--allow-eval"], {})).toThrow(/allow-actions/); + }); + + it("lists the same tool names as the MCP server and invoke layer", () => { + expect(new Set(INVOKABLE_TOOL_NAMES)).toEqual(new Set(ALL_TOOL_NAMES)); + }); +}); diff --git a/chrome-extension/devtools.js b/chrome-extension/devtools.js index fc040715..f1332240 100644 --- a/chrome-extension/devtools.js +++ b/chrome-extension/devtools.js @@ -21,8 +21,6 @@ let debuggerAttached = false; let injectPollTimer = null; let closing = false; - /** Panel confirmation for state-changing local API calls. Dies with this page. */ - let actionsConfirmed = false; const consoleQueue = []; const networkQueue = []; @@ -78,27 +76,9 @@ serverAddress = { host: found.host, port: found.port }; - let token = ""; - try { - const paired = await fetch(`http://${found.host}:${found.port}/.pair`, { method: "POST" }); - if (paired.ok) { - const body = await paired.json(); - if (body && typeof body.token === "string") token = body.token; - } - } catch { - token = ""; - } - if (!token) { - setState("disconnected", "The connector refused the extension connection."); - scheduleReconnect(); - return; - } - let ws; try { - // The token is a subprotocol, not part of the URL, so it does not land - // in an access log. `browser-tools` is the name the server selects. - ws = new WebSocket(`ws://${found.host}:${found.port}/extension-ws`, ["browser-tools", token]); + ws = new WebSocket(`ws://${found.host}:${found.port}/extension-ws`); } catch (error) { setState("disconnected", String(error)); scheduleReconnect(); @@ -110,8 +90,7 @@ ws.onopen = () => { reconnectDelayMs = 1000; setState("connected"); - send({ type: "hello", extensionVersion: "2.0.4", tabId, role: "devtools" }); - if (actionsConfirmed) send({ type: "actions-confirmed", confirmed: actionsConfirmed }); + send({ type: "hello", extensionVersion: "2.0.0", tabId, role: "devtools" }); void reportPanelSwitch(); sendPageState(); startCapture(); @@ -765,11 +744,6 @@ panelWindow.btmcp = { getStatus, getSettings: () => ({ ...settings }), - getActionsConfirmed: () => actionsConfirmed, - setActionsConfirmed(confirmed) { - actionsConfirmed = Boolean(confirmed); - send({ type: "actions-confirmed", confirmed: actionsConfirmed }); - }, async updateSettings(next) { const previous = settings; settings = { ...settings, ...next }; diff --git a/chrome-extension/panel.html b/chrome-extension/panel.html index f5b6dab3..c8aac757 100644 --- a/chrome-extension/panel.html +++ b/chrome-extension/panel.html @@ -177,14 +177,6 @@

Connection

Loopback addresses only. The extension will not send captured data to any other host.

-

Local API

- -

- Off until you turn it on here, or start the connector with --allow-actions. - Covers reload, screenshots, wiping captured logs, settings changes and which tab is - current. Closing DevTools turns it off again. -

-

Input on this tab

diff --git a/chrome-extension/panel.js b/chrome-extension/panel.js index afce5ba4..a3f10852 100644 --- a/chrome-extension/panel.js +++ b/chrome-extension/panel.js @@ -69,9 +69,6 @@ } applySettings(bridge.getSettings()); - if (el("allowActions")) { - el("allowActions").checked = Boolean(bridge.getActionsConfirmed && bridge.getActionsConfirmed()); - } bridge.subscribe(renderStatus); if (bridge.getPanelInputEnabled) { @@ -95,10 +92,6 @@ void bridge.updateSettings(collectSettings()) ); - el("allowActions").addEventListener("change", () => { - if (bridge.setActionsConfirmed) bridge.setActionsConfirmed(el("allowActions").checked); - }); - el("cookies").addEventListener("click", async () => { const granted = await bridge.requestCookiePermission(); el("detail").textContent = granted diff --git a/chrome-extension/worker.js b/chrome-extension/worker.js index 53d7a683..cd7420ed 100644 --- a/chrome-extension/worker.js +++ b/chrome-extension/worker.js @@ -81,9 +81,24 @@ async function ensureConnected() { return; } + var token = ""; + try { + var paired = await fetch("http://" + found.host + ":" + found.port + "/.pair", { method: "POST" }); + if (paired.ok) { + var body = await paired.json(); + if (body && typeof body.token === "string") token = body.token; + } + } catch (error) { + token = ""; + } + if (!token) { + scheduleReconnect(); + return; + } + var ws; try { - ws = new WebSocket("ws://" + found.host + ":" + found.port + "/extension-ws"); + ws = new WebSocket("ws://" + found.host + ":" + found.port + "/extension-ws", ["browser-tools", token]); } catch (error) { scheduleReconnect(); return; @@ -92,7 +107,7 @@ async function ensureConnected() { ws.onopen = function () { reconnectDelayMs = 1000; - send({ type: "hello", extensionVersion: "2.0.0", role: "worker" }); + send({ type: "hello", extensionVersion: "2.0.4", role: "worker" }); void reportState(); }; @@ -105,6 +120,8 @@ async function ensureConnected() { } if (message && message.type === "capability-probe") { void answerProbe(message); + } else if (message && message.type === "navigate-tab") { + void navigateTab(message); } else if (message && message.type === "ping") { send({ type: "pong", id: message.id }); } @@ -124,6 +141,76 @@ async function ensureConnected() { * Reads the switch and the tab again. The URL on the probe message is ignored; * chrome.tabs.get is the only source. */ +function respond(requestId, payload) { + send(Object.assign({ requestId: requestId }, payload)); +} + +function waitForTabUrl(tabId, timeoutMs) { + return new Promise(function (resolve) { + var done = false; + var timer = setTimeout(function () { + if (done) return; + done = true; + api.tabs + .get(tabId) + .then(function (tab) { + resolve(tab && tab.url ? tab.url : ""); + }) + .catch(function () { + resolve(""); + }); + }, timeoutMs); + + function onUpdated(updatedId, changeInfo, tab) { + if (done) return; + if (String(updatedId) !== String(tabId)) return; + if (changeInfo.status === "complete" && tab && tab.url) { + done = true; + clearTimeout(timer); + api.tabs.onUpdated.removeListener(onUpdated); + resolve(tab.url); + } + } + api.tabs.onUpdated.addListener(onUpdated); + }); +} + +async function navigateTab(message) { + var tabId = message.tabId; + var url = message.url; + if ((typeof tabId !== "number" && typeof tabId !== "string") || typeof url !== "string" || !url) { + respond(message.requestId, { + type: "navigate-result", + ok: false, + error: "tabId and url are required", + }); + return; + } + + try { + var before = await api.tabs.get(tabId); + var wasDiscarded = Boolean(before && before.discarded); + await api.tabs.update(tabId, { url: url, active: false }); + var finalUrl = await waitForTabUrl(tabId, 30000); + if (!finalUrl) { + var after = await api.tabs.get(tabId); + finalUrl = after && after.url ? after.url : url; + } + respond(message.requestId, { + type: "navigate-result", + ok: true, + finalUrl: finalUrl, + wasDiscarded: wasDiscarded, + }); + } catch (error) { + respond(message.requestId, { + type: "navigate-result", + ok: false, + error: error instanceof Error ? error.message : String(error), + }); + } +} + async function answerProbe(message) { var state = await readHumanState(); var liveUrl = null;