Repository navigation
feat: add page-scoped network mocks - #3384
Conversation
|
Thanks @marco-prontera for the thorough PR, and @samiyac for the ping. Directionally yes. Swapping a production bundle for a local build (or pointing it at a dev server) is a real workflow for coding agents, and #848 shows the demand. I gave the branch a spin over MCP and the CLI on Canary and the core flow works well (local file and redirect, persists across reloads, rebuilds get picked up). A few things I'd like us to sort out before landing. What do you think about the following? 1.) One tool instead of three. We are trying to keep the default tool list small to save agent context, so folding add/list/remove into a single tool (similar to set_logpoints) would fit better. OR maybe there is even a better way to do this? |
|
Aleko846
…---------- Forwarded message ---------
De: Michael Hablich ***@***.***>
Date: mié, 4 de nov de 2026, 11:18 p. m.
Subject: Re: [ChromeDevTools/chrome-devtools-mcp] feat: add network request
overrides (PR #3384)
To: ChromeDevTools/chrome-devtools-mcp <
***@***.***>
Cc: Subscribed ***@***.***>
*natorion* left a comment (ChromeDevTools/chrome-devtools-mcp#3384)
<#3384 (comment)>
Thanks @marco-prontera <https://github.com/marco-prontera> for the thorough
PR, and @samiyac <https://github.com/samiyac> for the ping.
Directionally yes. Swapping a production bundle for a local build (or
pointing it at a dev server) is a real workflow for coding agents, and #848
<#848> shows
the demand. I gave the branch a spin over MCP and the CLI on Canary and the
core flow works well (local file and redirect, persists across reloads,
rebuilds get picked up).
A few things I'd like us to sort out before landing. What do you think
about the following?
1.) One tool instead of three. We are trying to keep the default tool list
small to save agent context, so folding add/list/remove into a single tool
(similar to set_logpoints) would fit better. OR maybe there is even a
better way to do this?
2.) Keep perf traces trustworthy. A big use case in #848
<#848> is
swapping a library and then tracing or running Lighthouse. Right now an
active override disables the cache for the whole page and intercepts every
request, which skews those numbers. This caveat somehow needs to be dealt
with/communicated to the agent.
3.) Help agents notice when nothing matched. A relative pattern like
/app.js* is accepted but silently matches nothing, and a failed local file
only shows up as net::ERR_FAILED. A warning plus hit counts in the list
output would save turns.
4.) Blocklist on redirects. A cross-origin redirect target that 302s to a
host on --blocked-url-pattern currently gets through. That should be closed
before merge. Minor: the CLI examples in the skill use --urlPattern / --id
flags, but those are positional.
—
Reply to this email directly, view it on GitHub
<#3384?email_source=notifications&email_token=CJCUUF5LGWCETZNWGR3B4GT5XQSUXA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNRVGIYTKNZQGIZKM4TFMFZW63VKON2WE43DOJUWEZLEUVSXMZLOOSWGM33PORSXEX3DNRUWG2Y#issuecomment-6652157022>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/CJCUUF7SUDSN4J5AQ4XAOO35XQSUXAVCNFSNUABGKJSXA33TNF2G64TZHMYTANJUG44TGNZSGY5US43TOVSTWNRRGE4DMNZUGYZTJILWAI>
.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>
|
|
I think with a single tool we need to have a textual representation for a single override to make it usable via CLI. |
3979aa0 to
b64a092
Compare
Thanks @natorion, these points are great and thank you for the explanation for all of them, you helped me understand some of the principles behind the goals. |
Do you mean a compact string representation for each override, similar to set_logpoint? |
yes, if it is possible (I have not really thought about it). Otherwise the CLI needs to accept plain JSON objects that are a bit harder to read and work with. |
|
Perhaps let's brain storm about what is the ideal payload for network overrides is before changing code. Once we agree, let's split the PR into a stack of smaller PRs to simplify review. |
|
It appears to be somewhat complex to work with a single command + string representation. What do you think about the following commands instead:
WDYT? |
I've used the three original tools extensively in practice. I initially chose add_network_override, list_network_overrides, and remove_network_override because this separation felt natural and consistent with the workflow in the browser Developer Tools UI. I'm happy to move in this direction using two tools. Before proceeding, how would you handle URL overrides? The current implementation supports both local response files and override URLs, while the proposed body parameter covers local files. |
Yes once we agree I will create smaller PRs sounds good, thank you! |
|
I think supporting url redirect is fine as long as we make sure that the allowlists/blocklists apply to that URL including redirects (in the 2 tool design proposal it could be modeled as |
91fed8f to
7d51987
Compare
|
in the meanwhile I will do some tests with all the three kind of implementation just to have a measure from some example of use cases |
|
Hi @OrKoN, I tried all 3 choices of implementation, 3 tools, 1 and two as you proposed. |
|
@marco-prontera thanks! do you have any number from your test? did you try only the MCP interface or also the CLI interface? |
Yes, I’ve now tested all three versions with real Chrome, through both MCP and the CLI. On a real website, I replaced the same JavaScript resource with a local file and verified that it executed and picked up subsequent file changes.
These cover the same scenarios, including updates, removal, diagnostics, redirect allowlists/blocklists, and trace/Lighthouse warnings. Counts include reloads and verification, excluding session setup and cleanup. The two-tool version also passed three additional checks on both interfaces: abort toggling, body/upstream exclusivity, and allow-origin with filtered removal—13 extra calls per interface. The practical difference was updating one mock while keeping another: three tools needed remove + add; the other versions needed one call. With the single tool, though, I had to resend the unchanged mock too. I leave the decision to you, but from the usage and this report I think the 2 tools choice is winning here. |
|
@marco-prontera thanks! I think 2 tool design with 1 tool to read + edit and 1 tool to remove might be indeed the best and I think it is more natural for the CLI interface. let's update this PR for this and I will do more testing next week. |
Perfect I already updated the PR as you suggested, I prefer it too. Do I need to split it, into 3 PRs? |
|
@marco-prontera it would be great (using a github pr stack) to allow for more careful review of the parts of the change |
7c8b72e to
983cc3b
Compare
|
@OrKoN I’ve split the change into three PRs, keeping the two-tool design: #3384: core and local-file replacements The last two are dependent drafts targeting main, so their diffs currently include the earlier changes. Could you publish the core and upstream branches in this repository so we can retarget the drafts and review each part separately? Otherwise, I’ll update them as each preceding PR lands. |
|
Seems like 2 tools is the best approach, so +1 to that one. |
OrKoN
left a comment
There was a problem hiding this comment.
Please address the following:
-
Remove the stale entries from
src/telemetry/tool_call_metrics.json: theset_network_overridestool and the deprecatedabort,allow_origin_length, andupstream_lengthargs ofmock_network. These names never shipped onmain; they are leftovers of earlier revisions of this branch, andnpm run genkeeps them because it only marks missing entries as deprecated. -
Wrap the wildcard characters in backticks in the
routedescriptions insrc/tools/network.ts(for example`*` matches any sequence). Prettier turns the current'*' ... '*'into emphasis, sodocs/tool-reference.mdnow reads'_' matches any sequenceandconfigure '_'. -
Declare
verifyFilesSchema: {body: true}onmock_networkand drop the firstcontext.validatePath(params.body)call from the handler.ToolHandler.validateToolFilesalready validates and resolves path parameters before the handler runs (seesrc/tools/memory.ts); keep only the per-read revalidation insideloadResponseFile. -
Use one term in all user-facing text. The tools are
mock_network/remove_network_mock, but the measurement warning insrc/formatters/NetworkOverridesFormatter.ts, the error inMcpPage.#getNetworkOverrideManagerForChanges, theignoreCachedescription, and the SKILL say "network overrides". -
Simplify
NetworkOverrideManager.#activate: remove the twoisClosed()checks after the awaited calls and the nested cleanup branches. A page that closes mid-activation makes the next CDP call reject, andMcpPage.dispose()→manager.dispose()already releases the state;#mockrolls back the rule set on any rejection. -
Count navigations from the
documentrequest of the main frame inside#handleRequestinstead of theframenavigatedlistener.framenavigatedalso fires for same-document navigations (hash changes), which produces the "no requests matched after navigation" warning without any request, and removing the listener drops one lifecycle to manage. -
Remove the URL-redaction
replace(...)onlastErrorin#handleRequest. The message is built from a validated local file path and anfserror, so it contains no URL. -
Remove the test
exposes optional scalar CLI parameters without a string representationintests/tools/network.test.ts. It asserts that optional Zod fields acceptundefinedand parse strings, which is Zod behavior and not a scenario of this tool. -
Nit: in
scripts/eval_scenarios/network_override_local_file_test.ts, compileoverrideCall.args.routeand assert that it matches themy-third-party.jsURL instead of comparing it to the literal*my-third-party.js*. A model that emits*/my-third-party.jsis correct but fails the scenario. -
Nit: replace the manual
guard[Symbol.dispose]()in#runLifecycleOperationwithusing guard = await this.#lifecycleMutex.acquire();.
Applied, thank for your review |
OrKoN
left a comment
There was a problem hiding this comment.
I think this is the last round of comments I have:
-
Rebase on
mainand add the new files tosrc/BUILD.gn(NetworkOverrideManager.ts,formatters/NetworkOverridesFormatter.ts) andtests/BUILD.gn(NetworkOverrideManager.test.ts,network_overrides.test.ts,tools/network_override_measurements.test.ts).mainnow lists every.tsfile explicitly, sonpm run buildandnpm run testskip the new modules and tests on the merge commit. Run npm run sync to set up gclient. -
Nit: use one term in code identifiers.
ContextPageexposesmockNetwork/removeNetworkMocksnext tolistNetworkOverrides, andNetworkMockInput/NetworkMockFiltersit next toNetworkOverride/NetworkOverrideManager/NetworkOverridesFormatter; rename at leastlistNetworkOverridestolistNetworkMocks. -
Nit: remove the
methodandheadersoptions fromcreateMockHTTPRequestintests/mocks.ts. No test passes them. -
Nit: remove the
this.#page.isClosed()check inNetworkOverrideManager.#mockafter#createOverride.#activateperforms the same check and throws the same class of error, and when interception is already active no CDP call follows.
e03a77d to
00ded7b
Compare
## Summary Part 2 of 3 for ChromeDevTools#848. Builds on the network mock core merged in ChromeDevTools#3384. This PR contains only upstream response support. ```text mock_network 1 --upstream URL -> validate URL -> fetch -> validate each redirect -> fulfill response ``` Adds `upstream` as an alternative to `body` for GET/HEAD requests. Allowlists and blocklists apply before contacting the initial target and every redirect destination, including same-origin replacements. Cross-origin hops drop credentials and other non-allowlisted headers. Fetch negotiates compression independently of Chrome. Decoded responses omit stale compression and length headers, and separate Set-Cookie headers are preserved. The redirect loop and URL policy checks are shared with `McpContext` resource loading. Resource loading still returns text and rejects HTTP errors; mocks preserve response status and binary bodies. Shared errors redact URL credentials and query strings, report missing Location headers, and release redirect bodies on error paths. Includes mutually exclusive parameter validation, generated CLI/docs, redirect-policy tests, and browser coverage. ChromeDevTools#3421 adds `abort` and `allowOrigin` after this PR. Network mocks are disabled by default in MCP and CLI. Enable them with `--categoryNetworkMocks`; changing the category requires a server restart. ## Evidence - **Before:** mocks could only serve local files. **After:** upstream responses work across reloads, and redirects to blocked destinations fail before the destination is contacted. - Rebased after ChromeDevTools#3384 merged; source and test files are registered with GN. - `npm run format` and the full `npm run test -- --test-concurrency=2` suite passed on this revision: 1,890 passed, 3 skipped, 0 failed, including real Chrome integration tests. - Three regression cases fail on the previous revision and pass with these fixes: same-origin and cross-origin Accept-Encoding, and multiple Set-Cookie. ## Merge Danger **Door:** two-way **Blast Radius:** network Opt-in upstream responses use server-side fetches and retain the core measurement warning.
🤖 I have created a release *beep* *boop* --- ## [1.13.0](ChromeDevTools/chrome-devtools-mcp@chrome-devtools-mcp-v1.12.0...chrome-devtools-mcp-v1.13.0) (2026-11-11) ### 🎉 Features * add logpoints built on the DevTools BreakpointManager ([ChromeDevTools#3211](ChromeDevTools#3211)) ([0877ee0](ChromeDevTools@0877ee0)) * add page-scoped network mocks ([ChromeDevTools#3384](ChromeDevTools#3384)) ([1d692d3](ChromeDevTools@1d692d3)) * support upstream network mock responses ([ChromeDevTools#3420](ChromeDevTools#3420)) ([c4bf342](ChromeDevTools@c4bf342)) ### 🛠️ Fixes * **config:** accept config files with a UTF-8 BOM ([ChromeDevTools#3365](ChromeDevTools#3365)) ([63170b1](ChromeDevTools@63170b1)) * **console:** stop resolving a cyclic Error.cause chain after 10 causes ([ChromeDevTools#3338](ChromeDevTools#3338)) ([172656a](ChromeDevTools@172656a)) * disable set_logpoints when --no-javascript-evaluation is set ([ChromeDevTools#3415](ChromeDevTools#3415)) ([11fcc59](ChromeDevTools@11fcc59)), closes [ChromeDevTools#3414](ChromeDevTools#3414) * **extensions:** say list_extensions only lists unpacked extensions ([ChromeDevTools#3433](ChromeDevTools#3433)) ([1383bb9](ChromeDevTools@1383bb9)) * ignore an invalid cached version in the update check ([ChromeDevTools#3392](ChromeDevTools#3392)) ([3a9f378](ChromeDevTools@3a9f378)) * **input:** validate press_key and submitKey parameters in Zod schema ([ChromeDevTools#3382](ChromeDevTools#3382)) ([375a269](ChromeDevTools@375a269)) * **network:** start an empty request list for navigations without a request ([ChromeDevTools#3357](ChromeDevTools#3357)) ([b701776](ChromeDevTools@b701776)) * normalize non-Error values thrown by tool handlers ([ChromeDevTools#3068](ChromeDevTools#3068)) ([535a3dc](ChromeDevTools@535a3dc)) * **performance:** error when performance_stop_trace is called on a non-recording page ([ChromeDevTools#2971](ChromeDevTools#2971)) ([ChromeDevTools#3117](ChromeDevTools#3117)) ([1ab630a](ChromeDevTools@1ab630a)) * **plugin:** launch the Claude Code MCP server with npx --prefix ([ChromeDevTools#3353](ChromeDevTools#3353)) ([a24334d](ChromeDevTools@a24334d)) * preserve task serialization on request cancellation ([ChromeDevTools#3079](ChromeDevTools#3079)) ([03fd4e8](ChromeDevTools@03fd4e8)) * report page loads that keep the URL ([ChromeDevTools#3395](ChromeDevTools#3395)) ([3cc38bb](ChromeDevTools@3cc38bb)) * save binary request bodies byte for byte ([ChromeDevTools#3404](ChromeDevTools#3404)) ([e3eb901](ChromeDevTools@e3eb901)) * suggest --headless when Chrome cannot find an X server ([ChromeDevTools#3428](ChromeDevTools#3428)) ([8b0856a](ChromeDevTools@8b0856a)) * **url:** unwrap view-source: before all scheme checks in validateUrl ([ChromeDevTools#3335](ChromeDevTools#3335)) ([7275268](ChromeDevTools@7275268)) * **wait:** explain whitespace-sensitive text matching ([ChromeDevTools#3350](ChromeDevTools#3350)) ([81a0379](ChromeDevTools@81a0379)) ### 📄 Documentation * add Pi client configuration ([ChromeDevTools#3364](ChromeDevTools#3364)) ([bc0d93e](ChromeDevTools@bc0d93e)) * clarify custom browser launch and connection options ([ChromeDevTools#3386](ChromeDevTools#3386)) ([7e10c08](ChromeDevTools@7e10c08)) * **input:** note that press_key cannot drive native <select> popups on macOS ([ChromeDevTools#3288](ChromeDevTools#3288)) ([8e79bd0](ChromeDevTools@8e79bd0)) ### ⚡ Performance * **memory:** drop async parents of request initiators in NetworkCollector ([ChromeDevTools#3345](ChromeDevTools#3345)) ([ca6f834](ChromeDevTools@ca6f834)), closes [ChromeDevTools#3344](ChromeDevTools#3344) ### 🏗️ Refactor * re-export only used Zod runtime members from third_party barrel ([ChromeDevTools#3439](ChromeDevTools#3439)) ([6b056c8](ChromeDevTools@6b056c8)) * reuse Zod schemas and validate integer viewport dimensions ([ChromeDevTools#3367](ChromeDevTools#3367)) ([3c609da](ChromeDevTools@3c609da)) --- This PR was generated with [Release Please](https://github.com/googleapis/release-please). See [documentation](https://github.com/googleapis/release-please#release-please). Co-authored-by: Alex Rudenko <[email protected]>
## Summary Adds `abort` and `allowOrigin` actions to page-scoped network mocks. The core (ChromeDevTools#3384) and upstream responses (ChromeDevTools#3420) are already on `main`. Closes ChromeDevTools#848. ```text abort=true -> fail matching requests abort=false -> resume the stored source or browser request allowOrigin + body/upstream -> set Access-Control-Allow-Origin allowOrigin without source -> configuration error ``` Omitted actions retain existing settings; `abort=true` takes precedence over the response source and origin header. `allowOrigin` requires a `body` or `upstream` source, supplied in the same call or already stored on the matching rule. It accepts `*`, `null`, or a serialized origin. This does not configure preflight or credential headers. Only upstream sources use server-side GET/HEAD fetches. With no source, `abort=false` sends the request to the network and still takes precedence over older matching mocks. Includes validation, generated CLI/docs, and tests for abort toggling, preserving sources, origin headers, and rejected aborts without retries or false replacement errors. Network mocks are disabled by default in MCP and CLI. Enable them with `--categoryNetworkMocks`; changing the category requires a server restart. ## Evidence - **Before:** rules needed a local body or upstream source. **After:** agents can abort requests or set an origin header on a replacement response, then update actions without replacing its source. - A real Chrome test verifies that a cross-origin fetch fails without `allowOrigin`, succeeds with it, and fails again with `abort: true`. - Regression tests reproduce source-less origins, invalid origin values, and duplicate aborts on the previous revision (12 failures). - `npm run gen` (including build and format) and the full `npm run test -- --test-concurrency=2` suite passed: 1,955 passed, 3 skipped, 0 failed. - Updated with `main` (`cf587b48`) and tested with Chrome for Testing 157. ## Merge Danger **Door:** two-way **Blast Radius:** page These actions are opt-in and retain the existing measurement warning.
Summary
Part 1 of 3 for #848: the core and local-file replacements.
Network mocks are disabled by default in MCP and CLI. Enable them with
--categoryNetworkMocks; changing the category requires a server restart.Adds the two-tool interface for local response files through MCP and CLI.
Rules use absolute URLPatterns with optional resource types. An omitted
query matches any query string; regex and named groups are rejected. Mocks survive reloads
and reread files on each request. Updating a rule preserves unrelated rules;
the most recently updated matching rule wins.
Inspection reports hit counts, unmatched rules, and replacement errors.
No-match navigation warnings follow main-frame document requests, so hash
changes do not trigger them.
Mocks disable the page cache and intercept all requests, so tool responses,
performance traces, and Lighthouse reports carry a measurement warning.
Changes are rejected during a trace; removing the last mock restores the
cache and stops interception.
Includes generated CLI definitions, documentation, metrics, and tests.
Follow-ups: #3420 adds upstream responses; #3421 adds abort and allow-origin.
Both are dependent drafts targeting
mainuntil their prerequisites land.Evidence
After: local-file replacement and rebuilds work through the new tools,
with useful diagnostics when a file disappears.
main; new source and test files are registered with GN.npm run sync,npm run gen,npm run format, and the fullnpm run testsuite passed:1,863 passed, 3 skipped, 0 failed, including real Chrome integration tests.
Merge Danger
Door: two-way
Blast Radius: page
Active mocks alter request delivery and measurements for their page.