Chrome DevTools for coding agents
feat(config): support reloading blockedUrlPattern and allowedUrlPattern (#3268)
Nikolay Vitkovcc850f5ad916
diff --git a/docs/configuration.md b/docs/configuration.mdindex 8218c9ab..91007390 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -309,11 +309,12 @@ available tools, and notifies the MCP client with`notifications/tools/list_changed`. If the new file is invalid, the server logsthe error to stderr and keeps the previous configuration.-Tool categories (except `categoryExtensions`) and tool-specific options apply-immediately. Options that configure the browser, such as `headless`, `channel`,-`viewport`, `blockedUrlPattern`, or `categoryExtensions`, only apply after-restarting chrome-devtools-mcp. The server logs a message to stderr when a-change requires a restart.+Tool categories (except `categoryExtensions`), network URL restrictions+(`blockedUrlPattern`, `allowedUrlPattern`), and tool-specific options apply+immediately. Options that launch or connect to the browser, such as `headless`,+`channel`, `viewport`, or `categoryExtensions`, only apply after restarting+chrome-devtools-mcp. The server logs a message to stderr when a change requires+a restart.### Locking down the configuration file from agent accessdiff --git a/src/McpContext.ts b/src/McpContext.tsindex 96dce64b..2dedc8a7 100644--- a/src/McpContext.ts+++ b/src/McpContext.ts@@ -100,6 +100,10 @@ function hasOptionChanged(}const FEATURE_CONTROLLERS: readonly FeatureController[] = [+ {+ gate: {options: ['blockedUrlPattern', 'allowedUrlPattern']},+ onChange: context => context.syncNetworkRestrictions(),+ },{gate: {options: ['sourceMaps']},onChange: context => context.syncSourceMaps(),@@ -241,6 +245,25 @@ export class McpContext implements Context, BrowserlessContext {}}+ /**+ * Applies updated URL allowlist/blocklist rules to the connected browser and+ * clears incompatible page network throttling state.+ */+ async syncNetworkRestrictions(): Promise<void> {+ const {blockedUrlPattern, allowedUrlPattern} = this.#config.resolved;+ if (this.#browser) {+ await this.#browser.restrictNetwork({+ blocklist: blockedUrlPattern,+ allowlist: allowedUrlPattern,+ });+ }+ if (blockedUrlPattern || allowedUrlPattern) {+ for (const mcpPage of this.#allMcpPages()) {+ mcpPage.clearNetworkConditions();+ }+ }+ }+/*** Synchronizes the DevTools source maps setting across all pages.*/diff --git a/src/McpPage.ts b/src/McpPage.tsindex 51ba3874..c731f081 100644--- a/src/McpPage.ts+++ b/src/McpPage.ts@@ -1326,6 +1326,14 @@ export class McpPage implements ContextPage {}}+ clearNetworkConditions(): void {+ if (!this.emulationSettings.networkConditions) {+ return;+ }+ delete this.emulationSettings.networkConditions;+ this.updateTimeouts();+ }+updateTimeouts(): void {if (!this.#pptrPage) {return;diff --git a/src/config/puppeteer-options.ts b/src/config/puppeteer-options.tsindex fb07c10e..1ee5a897 100644--- a/src/config/puppeteer-options.ts+++ b/src/config/puppeteer-options.ts@@ -7,6 +7,10 @@import type {YargsOptions} from '../third_party/index.js';import {validateUrlPatterns} from '../utils/url.js';+interface PuppeteerOption extends YargsOptions {+ reloadable?: boolean;+}+/*** Options that are applied through Puppeteer when launching or connecting to* the browser.@@ -45,6 +49,7 @@ export const puppeteerOptions = {blockedUrlPattern: {type: 'array',string: true,+ reloadable: true,describe:"Restricts browser's network access by blocking specified URL patterns (uses https://urlpattern.spec.whatwg.org/). Silently detaches from targets with blocked URLs upon connection, and blocks runtime requests (including navigations and subresources). Accepts an array of patterns. A pattern that uses a regexp group, a named group (`:name`), or a partial IPv4 wildcard (for example `(127\\.\\d+\\.\\d+\\.\\d+)`, `*://127.0.0.1::port/*`, or `*://127.0.0.*/*`) is rejected, because it is not enforced on redirects or subresources; use an exact value or a `*` wildcard instead.",coerce: (arg: string[] | undefined) => {@@ -58,6 +63,7 @@ export const puppeteerOptions = {allowedUrlPattern: {type: 'array',string: true,+ reloadable: true,describe:"Restricts browser's network access by allowing only specified URL patterns (uses https://urlpattern.spec.whatwg.org/). Requires Chrome 149+. Silently detaches from targets with unallowed URLs upon connection, and blocks runtime requests (including navigations and subresources). Accepts an array of patterns. A pattern that uses a regexp group, a named group (`:name`), or a partial IPv4 wildcard (for example `(127\\.\\d+\\.\\d+\\.\\d+)`, `*://127.0.0.1::port/*`, or `*://127.0.0.*/*`) is rejected, because it is not enforced on redirects or subresources; use an exact value or a `*` wildcard instead.",coerce: (arg: string[] | undefined) => {@@ -73,4 +79,4 @@ export const puppeteerOptions = {return arg;},},-} satisfies Record<string, YargsOptions>;+} satisfies Record<string, PuppeteerOption>;diff --git a/tests/McpContext.test.ts b/tests/McpContext.test.tsindex 31060d50..5ddd2b78 100644--- a/tests/McpContext.test.ts+++ b/tests/McpContext.test.ts@@ -1730,6 +1730,116 @@ describe('McpContext', () => {sinon.assert.calledOnceWithExactly(syncSourceMapsSpy);});+ it('updates browser network restrictions only when blockedUrlPattern or allowedUrlPattern changes', async () => {+ const browser = createMockPuppeteerBrowser();+ const config = createMockServerConfig();+ const context = await createMockContext({browser, config});+ const mcpPage = context.getSelectedMcpPage();+ const clearNetworkConditionsSpy = sinon.spy(+ mcpPage,+ 'clearNetworkConditions',+ );++ await updateConfig(config, context, {performanceCrux: false});+ sinon.assert.notCalled(browser.restrictNetwork);+ sinon.assert.notCalled(clearNetworkConditionsSpy);++ await updateConfig(config, context, {+ blockedUrlPattern: ['https://blocked.example.com/*'],+ });+ sinon.assert.calledOnceWithExactly(browser.restrictNetwork, {+ blocklist: ['https://blocked.example.com/*'],+ allowlist: undefined,+ });+ sinon.assert.calledOnceWithExactly(clearNetworkConditionsSpy);++ browser.restrictNetwork.resetHistory();+ clearNetworkConditionsSpy.resetHistory();+ await updateConfig(config, context, {+ blockedUrlPattern: ['https://blocked.example.com/*'],+ });+ sinon.assert.notCalled(browser.restrictNetwork);+ sinon.assert.notCalled(clearNetworkConditionsSpy);++ await updateConfig(config, context, {+ blockedUrlPattern: undefined,+ allowedUrlPattern: ['https://allowed.example.com/*'],+ });+ sinon.assert.calledOnceWithExactly(browser.restrictNetwork, {+ blocklist: undefined,+ allowlist: ['https://allowed.example.com/*'],+ });+ sinon.assert.calledOnceWithExactly(clearNetworkConditionsSpy);++ browser.restrictNetwork.resetHistory();+ clearNetworkConditionsSpy.resetHistory();+ await updateConfig(config, context, {+ allowedUrlPattern: undefined,+ });+ sinon.assert.calledOnceWithExactly(browser.restrictNetwork, {+ blocklist: undefined,+ allowlist: undefined,+ });+ sinon.assert.notCalled(clearNetworkConditionsSpy);+ });++ it('does not connect a browser when network restrictions change before ensureBrowser() is called', async () => {+ const config = createMockServerConfig();+ const getBrowser = sinon+ .stub<[], Promise<Browser>>()+ .resolves(createMockPuppeteerBrowser());+ const taskRunner = new TaskRunner();+ const context = McpContext.create(+ undefined,+ {+ config,+ heapSnapshotManager: new HeapSnapshotManager(taskRunner),+ taskRunner,+ getBrowser,+ },+ Locator,+ );++ await updateConfig(config, context, {+ blockedUrlPattern: ['https://blocked.example.com/*'],+ });++ sinon.assert.notCalled(getBrowser);+ context.dispose();+ });++ it('reads updated blockedUrlPattern and allowedUrlPattern in loadResource', async () => {+ sinon.stub(globalThis, 'fetch').callsFake(async () => new Response('ok'));+ const config = createMockServerConfig();+ const context = await createMockContext({config});++ assert.strictEqual(+ await context.loadResource('https://example.com/resource.map'),+ 'ok',+ );++ await updateConfig(config, context, {+ blockedUrlPattern: ['https://example.com/*'],+ });+ await assert.rejects(+ context.loadResource('https://example.com/resource.map'),+ /Blocked by blocklist/,+ );++ await updateConfig(config, context, {+ blockedUrlPattern: undefined,+ allowedUrlPattern: ['https://allowed.example.com/*'],+ });+ await assert.rejects(+ context.loadResource('https://example.com/resource.map'),+ /Not allowed by allowlist/,+ );+ assert.strictEqual(+ await context.loadResource('https://allowed.example.com/resource.map'),+ 'ok',+ );+ });+it('refreshes the pages when experimentalIncludeAllPages changes', async () => {const config = createMockServerConfig({experimentalIncludeAllPages: false,diff --git a/tests/McpPage.test.ts b/tests/McpPage.test.tsindex dbe71f8d..0a0a15d0 100644--- a/tests/McpPage.test.ts+++ b/tests/McpPage.test.ts@@ -954,6 +954,46 @@ describe('McpPage', () => {});});+ describe('clearNetworkConditions()', () => {+ it('clears networkConditions and updates timeouts while keeping other emulation settings', async () => {+ const config = createMockServerConfig();+ const {mcpPage, pptrPage} = await createMcpPage({config});+ await mcpPage.emulate({+ networkConditions: 'Slow 3G',+ cpuThrottlingRate: 2,+ });+ pptrPage.setDefaultTimeout.resetHistory();+ pptrPage.setDefaultNavigationTimeout.resetHistory();+ config.commit(+ createMockServerConfig({+ blockedUrlPattern: ['https://example.com/*'],+ }),+ );++ mcpPage.clearNetworkConditions();++ assert.strictEqual(mcpPage.networkConditions, null);+ assert.strictEqual(mcpPage.cpuThrottlingRate, 2);+ sinon.assert.calledOnceWithExactly(pptrPage.setDefaultTimeout, 10_000);+ sinon.assert.calledOnceWithExactly(+ pptrPage.setDefaultNavigationTimeout,+ 20_000,+ );+ await mcpPage.restoreEmulation();+ });++ it('does nothing when networkConditions is not set', async () => {+ const {mcpPage, pptrPage} = await createMcpPage();+ pptrPage.setDefaultTimeout.resetHistory();+ pptrPage.setDefaultNavigationTimeout.resetHistory();++ mcpPage.clearNetworkConditions();++ sinon.assert.notCalled(pptrPage.setDefaultTimeout);+ sinon.assert.notCalled(pptrPage.setDefaultNavigationTimeout);+ });+ });+describe('getNetworkRequests', () => {it('delegates to networkCollector.getData with includePreservedRequests', async () => {const {mcpPage} = await createMcpPage();diff --git a/tests/McpServer.test.ts b/tests/McpServer.test.tsindex 241bf0a9..e2748f11 100644--- a/tests/McpServer.test.ts+++ b/tests/McpServer.test.ts@@ -465,8 +465,7 @@ describe('McpServer', () => {it('commits the shared config, updates roots, and notifies the context with previous args', async () => {const {server, context, config} = await createTestServer([- '--blockedUrlPattern',- 'https://example.com/*',+ '--chromeArg=--foo',]);const previousArgs = config.resolved;let cruxWhenNotified: boolean | undefined;@@ -487,9 +486,7 @@ describe('McpServer', () => {]);sinon.assert.calledOnceWithExactly(context.onConfigChanged, previousArgs);assert.strictEqual(cruxWhenNotified, false);- assert.deepStrictEqual(config.resolved.blockedUrlPattern, [- 'https://example.com/*',- ]);+ assert.deepStrictEqual(config.resolved.chromeArg, ['--foo']);});it('logs the CrUX disclaimer only when CrUX becomes active', async () => {diff --git a/tests/config/ServerConfig.test.ts b/tests/config/ServerConfig.test.tsindex 85d977f3..c052cf79 100644--- a/tests/config/ServerConfig.test.ts+++ b/tests/config/ServerConfig.test.ts@@ -239,6 +239,7 @@ describe('ServerConfig', () => {'--memoryDebugging','--no-category-network','--no-file-navigations',+ '--blockedUrlPattern=https://example.com/*','--slim',]),).resolved;@@ -246,20 +247,41 @@ describe('ServerConfig', () => {assert.strictEqual(merged.memoryDebugging, true);assert.strictEqual(merged.categoryNetwork, false);assert.strictEqual(merged.fileNavigations, false);+ assert.deepStrictEqual(merged.blockedUrlPattern, [+ 'https://example.com/*',+ ]);assert.strictEqual(merged.slim, true);});+ it('switches between blockedUrlPattern and allowedUrlPattern across reloads', () => {+ const withBlocked = parseConfig().mergeReloadable(+ parseConfig(['--blockedUrlPattern=https://blocked.example.com/*']),+ );+ assert.deepStrictEqual(withBlocked.resolved.blockedUrlPattern, [+ 'https://blocked.example.com/*',+ ]);+ assert.strictEqual(withBlocked.resolved.allowedUrlPattern, undefined);++ const withAllowed = withBlocked.mergeReloadable(+ parseConfig(['--allowedUrlPattern=https://allowed.example.com/*']),+ );+ assert.strictEqual(withAllowed.resolved.blockedUrlPattern, undefined);+ assert.deepStrictEqual(withAllowed.resolved.allowedUrlPattern, [+ 'https://allowed.example.com/*',+ ]);+ });+it('keeps restart-required options', () => {const merged = parseConfig().mergeReloadable(parseConfig(['--categoryExtensions',- '--blockedUrlPattern=https://example.com/*',+ '--headless','--experimentalDevtools',]),).resolved;assert.strictEqual(merged.categoryExtensions, undefined);- assert.strictEqual(merged.blockedUrlPattern, undefined);+ assert.strictEqual(merged.headless, false);assert.strictEqual(merged.experimentalDevtools, false);});@@ -410,15 +432,13 @@ describe('ServerConfig', () => {});it('compares restart-required array and object options by value', () => {- const previous = parseConfig([- '--blockedUrlPattern=https://example.com/*',- ]);- const same = parseConfig(['--blockedUrlPattern=https://example.com/*']);- const changed = parseConfig(['--blockedUrlPattern=https://other.com/*']);+ const previous = parseConfig(['--chromeArg=--foo']);+ const same = parseConfig(['--chromeArg=--foo']);+ const changed = parseConfig(['--chromeArg=--bar']);assert.deepStrictEqual(previous.getRestartRequiredChanges(same), []);assert.deepStrictEqual(previous.getRestartRequiredChanges(changed), [- 'blockedUrlPattern',+ 'chromeArg',]);});diff --git a/tests/mocks.ts b/tests/mocks.tsindex d831a903..66ea3323 100644--- a/tests/mocks.ts+++ b/tests/mocks.ts@@ -198,6 +198,7 @@ export function createMockPuppeteerBrowser(): sinon.SinonStubbedInstance<Browsersinon.stub(browser, 'connected').get(() => true);browser.close.resolves();browser.disconnect.resolves();+ browser.restrictNetwork.resolves();browser.pages.resolves([]);browser.targets.returns([]);browser.browserContexts.returns([]);