Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# Changelog

## Unreleased

- **Non-scriptable pages are reported the same way everywhere.** `chrome://`,
DevTools, `view-source:`, the Chrome Web Store, extension pages, and the
built-in PDF viewer come back as metadata only (`access: "metadata-only"`,
"metadata only, can't read or act"). Navigation to those pages is refused.
An http(s) PDF can still load, and is then reported as not scriptable. Page
info and the tab list carry the same fields. Screenshot, storage, console,
network, and audits on those pages return that result instead of an empty
success.

## 2.0.5

The `browser-tools` CLI. The packages published to npm as 2.0.4 were
Expand Down
66 changes: 60 additions & 6 deletions browser-tools-mcp/src/connector/connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ import {
type CapabilityAction,
type GatePolicy,
} from "../gates/capability.js";
import {
loadsWithoutScripting,
restrictedPage,
restrictedPageFields,
restrictedPageFromExtensionError,
RestrictedPageError,
} from "../restricted-page.js";

export const SERVER_SIGNATURE = "mcp-browser-connector-24x7";
export const SERVER_VERSION = "2.0.0";
Expand Down Expand Up @@ -167,6 +174,12 @@ export interface TabView {
isCurrent: boolean;
consoleCount: number;
networkCount: number;
/** Set when this tab cannot be scripted. Same fields as navigation errors. */
access?: "metadata-only";
message?: string;
scriptable?: false;
kind?: string;
detail?: string;
}

export interface ExportResult<T> {
Expand Down Expand Up @@ -508,11 +521,13 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
api.get("/page", (_req, res) => {
const current = currentTabId !== null ? tabs.get(String(currentTabId)) : undefined;
const page = store.getCurrentPage();
const url = current?.url || page.url;
res.json({
url: current?.url || page.url,
url,
tabId: currentTabId ?? page.tabId,
extensionConnected: telemetryConnected(),
connectedTabs: tabs.size,
...restrictedPageFields(url),
});
});

Expand Down Expand Up @@ -838,9 +853,16 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
isCurrent: String(record.tabId) === String(currentTabId),
consoleCount: store.queryConsole({ tabId: record.tabId }).total,
networkCount: store.queryNetwork({ tabId: record.tabId }).total,
...restrictedPageFields(record.url),
}));
}

/** Reading or acting on a non-scriptable page is reported, not done quietly. */
function assertScriptable(url: string): void {
const found = restrictedPage(url);
if (found) throw new RestrictedPageError(found);
}

function tabUrl(tabId: TabId | null): string {
if (tabId === null) return store.getCurrentPage().url;
return tabs.get(String(tabId))?.url ?? "";
Expand All @@ -861,6 +883,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
): TabScopedResult<ConsoleEntry> {
const { allTabs, tabId: requested, ...rest } = query;
const scoped = scope(allTabs, requested);
if (scoped.tabId !== null) assertScriptable(scoped.url);
const result = store.queryConsole(
scoped.tabId === null ? rest : { ...rest, tabId: scoped.tabId }
);
Expand All @@ -872,6 +895,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
): TabScopedResult<NetworkEntry> {
const { allTabs, tabId: requested, ...rest } = query;
const scoped = scope(allTabs, requested);
if (scoped.tabId !== null) assertScriptable(scoped.url);
const result = store.queryNetwork(
scoped.tabId === null ? rest : { ...rest, tabId: scoped.tabId }
);
Expand All @@ -882,6 +906,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
options: { tabId?: TabId; allTabs?: boolean } = {}
): ExportResult<ConsoleEntry> {
const scoped = scope(options.allTabs, options.tabId);
if (scoped.tabId !== null) assertScriptable(scoped.url);
return {
tabId: scoped.tabId,
url: scoped.url,
Expand All @@ -893,6 +918,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
options: { tabId?: TabId; allTabs?: boolean } = {}
): ExportResult<NetworkEntry> {
const scoped = scope(options.allTabs, options.tabId);
if (scoped.tabId !== null) assertScriptable(scoped.url);
return {
tabId: scoped.tabId,
url: scoped.url,
Expand Down Expand Up @@ -944,6 +970,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con

function getSelectedElement(options: { tabId?: TabId } = {}): unknown {
const tabId = resolveTabId(options.tabId);
assertScriptable(tabUrl(tabId));
return tabId === null ? store.getSelectedElement() : store.getSelectedElement(tabId);
}

Expand Down Expand Up @@ -1113,7 +1140,8 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con

if (message["ok"] === false) {
const reason = typeof message["error"] === "string" ? message["error"] : "Extension reported a failure";
entry.reject(new ExtensionRequestError(reason));
const restricted = restrictedPageFromExtensionError(reason);
entry.reject(restricted ? new RestrictedPageError(restricted) : new ExtensionRequestError(reason));
return;
}
entry.resolve(message);
Expand Down Expand Up @@ -1147,6 +1175,7 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
resolveSafeScreenshotPath(screenshotDir, requestedName);

const connection = connectionForTab(options.tabId);
assertScriptable(connection.tabId !== null ? tabUrl(connection.tabId) : store.getCurrentPage().url);

const maxBytes = store.settings.screenshotMaxBytes;
const response = await requestFromExtension(connection, "capture-screenshot", {
Expand Down Expand Up @@ -1191,7 +1220,9 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
}

async function refreshTab(options: { tabId?: TabId } = {}): Promise<void> {
await requestFromExtension(connectionForTab(options.tabId), "refresh-tab");
const connection = connectionForTab(options.tabId);
assertScriptable(connection.tabId !== null ? tabUrl(connection.tabId) : store.getCurrentPage().url);
await requestFromExtension(connection, "refresh-tab");
}

function parseHttpUrl(raw: string): URL {
Expand All @@ -1211,7 +1242,12 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
url: string;
tabId?: TabId;
}): Promise<{ tabId: TabId; requestedUrl: string; finalUrl: string; wasDiscarded: boolean }> {
const requestedUrl = parseHttpUrl(options.url.trim()).href;
const rawUrl = options.url.trim();
const blocked = restrictedPage(rawUrl);
if (blocked && !loadsWithoutScripting(rawUrl)) {
throw new RestrictedPageError(blocked);
}
const requestedUrl = parseHttpUrl(rawUrl).href;
const tabId = resolveTabId(options.tabId);
if (tabId === null) {
throw new ExtensionRequestError(
Expand All @@ -1234,19 +1270,31 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
});
const finalUrl =
typeof response["finalUrl"] === "string" ? response["finalUrl"] : requestedUrl;
const wasDiscarded = response["wasDiscarded"] === true;
const landed = restrictedPage(finalUrl);
if (landed) {
throw new RestrictedPageError(landed, {
navigated: true,
tabId,
requestedUrl,
wasDiscarded,
});
}
return {
tabId,
requestedUrl,
finalUrl,
wasDiscarded: response["wasDiscarded"] === true,
wasDiscarded,
};
}

async function readStorage(
kinds: string[],
options: { tabId?: TabId } = {}
): Promise<Record<string, unknown>> {
const response = await requestFromExtension(connectionForTab(options.tabId), "get-storage", {
const connection = connectionForTab(options.tabId);
assertScriptable(connection.tabId !== null ? tabUrl(connection.tabId) : store.getCurrentPage().url);
const response = await requestFromExtension(connection, "get-storage", {
kinds,
});
const storage = response["storage"];
Expand Down Expand Up @@ -1283,6 +1331,8 @@ export async function createConnector(config: ConnectorConfig = {}): Promise<Con
"No page URL is known yet. Open the page in Chrome with DevTools open, or pass a url explicitly."
);
}
const unscriptable = restrictedPage(url);
if (unscriptable) throw new RestrictedPageError(unscriptable);
const egress = await checkAuditTarget(url);
const runner = config.auditRunner ?? runLighthouseAudit;

Expand Down Expand Up @@ -1640,6 +1690,10 @@ function respondWithError(res: Response, error: unknown): void {
res.status(504).json({ error: error.message, code: "EXTENSION_TIMEOUT" });
return;
}
if (error instanceof RestrictedPageError) {
res.status(422).json({ error: error.message, code: "RESTRICTED_PAGE", ...error.toJSON() });
return;
}
if (error instanceof ExtensionRequestError) {
res.status(502).json({ error: error.message, code: "EXTENSION_ERROR" });
return;
Expand Down
27 changes: 24 additions & 3 deletions browser-tools-mcp/src/gates/capability.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import net from "node:net";

import { classifyAddress, isLocalName, normalizeHost, originOf } from "../lighthouse/destination.js";
import {
loadsWithoutScripting,
RESTRICTED_PAGE_MESSAGE,
restrictedPage,
} from "../restricted-page.js";

/**
* Capability gates for script evaluation, real input, and the no-DevTools
Expand Down Expand Up @@ -52,6 +57,8 @@ export const GateReason = {
destinationNotAllowed: "destination is not allowed",
excluded: "origin is excluded",
banner: "banner bypass is disabled",
/** Same wording as restricted-page reports. The page cannot be read or acted on. */
restricted: RESTRICTED_PAGE_MESSAGE,
unknown: "unknown action",
notRechecked: "live tab URL was not re-checked",
switchUnconfirmed: "popup switch was not confirmed",
Expand Down Expand Up @@ -249,17 +256,31 @@ export function decideCapability(action: string, context: GateContext): GateDeci
if (action === "listTabs") return { allowed: true, reason: GateReason.allowed };

if (action === "readTab") {
if (restrictedPage(context.liveUrl)) return deny(GateReason.restricted);
const read = readUrlPermitted(context.liveUrl, context.policy);
return read.permitted ? { allowed: true, reason: GateReason.allowed } : deny(read.reason);
}

const live = inputUrlPermitted(context.liveUrl, context.policy, "tab");
if (!live.permitted) return deny(live.reason);

if (action === "navigate") {
// A chrome:// (or similar) tab has no scriptable origin. Leaving it is
// allowed; the destination is still checked. http(s) PDFs may load and are
// reported afterwards. Every other restricted destination is refused here.
if (!restrictedPage(context.liveUrl)) {
const live = inputUrlPermitted(context.liveUrl, context.policy, "tab");
if (!live.permitted) return deny(live.reason);
}
if (restrictedPage(context.destinationUrl) && !loadsWithoutScripting(context.destinationUrl)) {
return deny(GateReason.restricted);
}
const destination = inputUrlPermitted(context.destinationUrl, context.policy, "destination");
if (!destination.permitted) return deny(destination.reason);
return { allowed: true, reason: GateReason.allowed };
}

if (restrictedPage(context.liveUrl)) return deny(GateReason.restricted);

const live = inputUrlPermitted(context.liveUrl, context.policy, "tab");
if (!live.permitted) return deny(live.reason);

return { allowed: true, reason: GateReason.allowed };
}
17 changes: 16 additions & 1 deletion browser-tools-mcp/src/mcp/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,23 @@ import type {
TabId,
} from "../connector/store.js";
import type { AuditCategory, AuditReport } from "../lighthouse/types.js";
import {
restrictedPageErrorFromPayload,
restrictedPageFields,
type RestrictedPageKind,
} from "../restricted-page.js";

export interface PageInfo {
url: string;
tabId: number | string | null;
extensionConnected: boolean;
connectedTabs: number;
/** Present when the current page cannot be scripted. */
access?: "metadata-only";
message?: string;
scriptable?: false;
kind?: RestrictedPageKind;
detail?: string;
}

export interface TabListing {
Expand Down Expand Up @@ -110,11 +121,13 @@ export class InProcessConnectorClient implements ConnectorClient {
const tabs = this.#connector.listTabs();
const current = tabs.find((tab) => tab.isCurrent);
const page = this.#connector.store.getCurrentPage();
const url = current?.url || page.url;
return {
url: current?.url || page.url,
url,
tabId: this.#connector.getCurrentTabId() ?? page.tabId,
extensionConnected: this.#connector.hasExtension(),
connectedTabs: tabs.length,
...restrictedPageFields(url),
};
}

Expand Down Expand Up @@ -235,6 +248,8 @@ export class HttpConnectorClient implements ConnectorClient {
const payload = text ? (JSON.parse(text) as Record<string, unknown>) : {};

if (!response.ok) {
const restricted = restrictedPageErrorFromPayload(payload);
if (restricted) throw restricted;
const message =
typeof payload["error"] === "string" ? payload["error"] : `Request failed (${response.status})`;
throw new Error(message);
Expand Down
36 changes: 33 additions & 3 deletions browser-tools-mcp/src/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ import {
import { resolveEnabledTools } from "../connector/api-policy.js";
import { createLogger } from "../util/logger.js";
import { AUDIT_CATEGORIES, type AuditCategory } from "../lighthouse/types.js";
import {
RESTRICTED_PAGE_KINDS,
RESTRICTED_PAGE_MESSAGE,
RestrictedPageError,
restrictedPageToolText,
} from "../restricted-page.js";

const log = createLogger("mcp");

Expand Down Expand Up @@ -70,11 +76,28 @@ function ok(structured: Record<string, unknown>, extraContent: ToolContent[] = [
}

function fail(error: unknown): ToolResult {
if (error instanceof RestrictedPageError) {
log.warn("Tool call failed:", error.message);
// Text carries the JSON. structuredContent is omitted: clients validate it
// against the success output schema and would reject this shape.
return { content: [{ type: "text", text: restrictedPageToolText(error) }], isError: true };
}
const message = error instanceof Error ? error.message : String(error);
log.warn("Tool call failed:", message);
return { content: [{ type: "text", text: message }], isError: true };
}

const restrictedPageOutput = {
access: z
.literal("metadata-only")
.optional()
.describe(`Set when this page cannot be scripted. The message is "${RESTRICTED_PAGE_MESSAGE}".`),
message: z.string().optional().describe("Shared wording for a page that cannot be scripted"),
scriptable: z.literal(false).optional().describe("False when the page cannot be read or acted on"),
kind: z.enum(RESTRICTED_PAGE_KINDS).optional(),
detail: z.string().optional().describe("Which kind of page cannot be scripted"),
};

/** Offers the complete history whenever a read had to be cut short. */
function truncationLinks(result: { truncated: boolean; tabId: unknown }): ToolContent[] {
if (!result.truncated) return [];
Expand Down Expand Up @@ -251,7 +274,9 @@ const TOOLS: ToolDefinition[] = [
description:
"Every browser tab that currently has DevTools open, with the tabId you can pass to any other tool. " +
"Call this when a result reported otherTabs above 0, or when the user mentions a page other than the one you have been reading. " +
"The tab marked isCurrent is the one every other tool uses when you do not pass tabId.",
"The tab marked isCurrent is the one every other tool uses when you do not pass tabId. " +
"A tab on chrome://, DevTools, view-source, the Chrome Web Store, an extension page, or the PDF viewer " +
`is metadata only (access "metadata-only", "${RESTRICTED_PAGE_MESSAGE}") and cannot be scripted.`,
outputSchema: {
tabs: z.array(z.record(z.string(), z.unknown())),
currentTabId: z.union([z.number(), z.string()]).nullable(),
Expand Down Expand Up @@ -447,7 +472,8 @@ const TOOLS: ToolDefinition[] = [
{
title: "Get current page",
description:
"Which page the browser is currently on. Call this before reading telemetry so you know what the logs describe. If connectedTabs is above 1, call listBrowserTabs before assuming this is the page the user means.",
"Which page the browser is currently on. Call this before reading telemetry so you know what the logs describe. If connectedTabs is above 1, call listBrowserTabs before assuming this is the page the user means. " +
`When the page cannot be scripted, access is "metadata-only" and message is "${RESTRICTED_PAGE_MESSAGE}".`,
outputSchema: {
url: z.string(),
tabId: z.union([z.number(), z.string()]).nullable(),
Expand All @@ -456,6 +482,7 @@ const TOOLS: ToolDefinition[] = [
.number()
.int()
.describe("How many tabs have DevTools open. Above 1 means other pages exist."),
...restrictedPageOutput,
},
annotations: {
title: "Get current page",
Expand Down Expand Up @@ -604,7 +631,10 @@ const TOOLS: ToolDefinition[] = [
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).",
"switch, and --allow-input on browser-tools-mcp (browser-tools CLI: --allow-actions). " +
"chrome://, DevTools, view-source, the Chrome Web Store, and extension pages are refused. " +
"An http(s) PDF may load, then the tool fails because the viewer cannot be scripted. " +
`The error text is JSON with access "metadata-only" and message "${RESTRICTED_PAGE_MESSAGE}".`,
inputSchema: {
url: z.string().describe("http(s) URL to load in the tab"),
tabId: tabIdInput,
Expand Down
Loading
Loading