This exposes DevTools named filters in get_heapsnapshot_details and
get_heapsnapshot_class_nodes tools. This allows the client to list e.g.
all objects retained through detached DOM objects.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
## What
`generateToolMetrics` reads an enum parameter's values by unwrapping
**at most
one** `optional` wrapper:
```ts
if (schema._def.values?.length > 0) {
values = schema._def.values;
} else {
values = schema._def.innerType._def.values; // only one level
}
```
An enum parameter wrapped in `.default().optional()` (or any nested
`optional`/`default`/`nullable` combination) therefore falls through to
`schema._def.innerType._def.values === undefined`, and `npm run
update-metrics`
(run as part of `npm run gen`) crashes:
```
TypeError: Cannot read properties of undefined (reading '0')
at validateEnumHomogeneity (build/src/telemetry/metricsRegistry.js:12)
at generateToolMetrics (build/src/telemetry/metricsRegistry.js:59)
```
## Why it matters
`npm run gen` is required whenever a tool is added or changed (per
`CONTRIBUTING.md`). Declaring an enum parameter with a default — a
natural,
documented zod pattern — silently breaks docs/metrics generation.
## Fix
Add `getEnumValues()` in `transformation.ts` that recursively unwraps
`optional` / `default` / `nullable` / `effects` wrappers, mirroring the
existing
`getZodType()`, and use it in `generateToolMetrics`. Behavior is
unchanged for
the existing bare-enum and single-`optional` cases.
## Tests
- `getEnumValues` unit tests: bare enum, `optional`, `default`, both
orders of
`default`+`optional`, and throws for a non-enum type.
- `generateToolMetrics` regression test with
`zod.enum(...).default(...).optional()`.
- `npm run typecheck`, the telemetry tests, and `npm run check-format`
pass.
---
First-time contributor here — happy to sign the CLA.
Follow-up to #2304.
`createPagesSnapshot()` reselects `#pages[0]` whenever the selected page
is missing from `#pages`, even when that page is still open. So a live
selection can be silently swapped, not only a closed one.
The case that hit us is a `devtools://` page:
- the server connects with `handleDevToolsAsPage: true`
(`src/browser.ts`), so DevTools frontends are pages and land in
`#mcpPages`
- `#pages` filters `devtools://` out (`src/McpContext.ts`, unless
`experimentalDevToolsDebugging` is set)
- `getPageById()` (used by `select_page`) reads `#mcpPages`, not
`#pages`, so a devtools page can be selected even though `list_pages`
never lists it
- the next snapshot finds it missing from `#pages` and, because the
fallback keys on `#pages` membership rather than `isClosed()`, reselects
`#pages[0]` with the page still open (`isClosed() === false`)
This reproduces on a normal Chrome (details and a repro in #2304).
This change gates the fallback on `isClosed()`, as proposed in #2304. A
still-open selection is kept; a genuinely closed page still
auto-advances, so the browser-like behavior for closed tabs is
unchanged.
One consequence: the "is no longer listed" wording added in #2308
becomes unreachable, since a live page missing from the list no longer
triggers a fallback. I left it in place to keep this diff focused, but
I'm happy to simplify it here or in a follow-up.
The unit test that covered the missing-but-open case now asserts the
selection is retained.
Refs: #2304
## Summary
validatePath() in McpContext returned immediately, with no restriction
at all, whenever roots() returned undefined. roots() only returns
undefined when the connecting MCP client never negotiates the optional
roots capability during initialize, which any minimal client can trigger
simply by omitting it from its declared capabilities.
Since roots() already always appends the OS temp directory to whatever
explicit roots are configured, this change makes it return that same
default (temp directory only) instead of undefined when no roots have
been set. This removes the early return in validatePath() entirely, so
path validation now runs unconditionally rather than being conditional
on whether the connecting client happened to negotiate a capability it
was never required to declare per the MCP spec.
Any filePath-accepting tool (take_screenshot, saveFile, and the
performance/Lighthouse export tools that route through the same check)
had its only path-traversal guard silently disabled for the lifetime of
a connection whenever the client omitted the optional roots capability.
Since this server is designed to let an LLM drive a browser, and browsed
page content is not trusted input, this meant a client that simply
doesn't implement roots (a plausible, non-adversarial default for
lightweight or custom MCP clients) removed the only boundary preventing
the connected agent from writing to any path the process can reach.
Added a test that exercises the actual default state of roots (never
calling setRoots()) directly, since the existing tests always call
setRoots(), even with an empty array, before validating. Verified
locally with a minimal MCP client that declares no capabilities: before
this change, take_screenshot with a filePath outside any root wrote a
real file to an arbitrary path with no error; after this change, the
same call is rejected with the existing Access denied error. Also
verified that a client that does declare roots is unaffected, and that
writes to the OS temp directory continue to succeed with no roots
negotiated, matching prior behavior for that path.
Follow-up to #2304 (the "note" part discussed there).
When the selected page disappears from the page list,
`createPagesSnapshot()` silently re-selects the first page. The agent
gets no signal: if its next call is `list_pages` (which is what the
closed-page error message recommends), the listing already shows the new
selection and every subsequent tool call runs against a page the agent
never picked.
This PR records the automatic fallback and surfaces it as a one-line
note in the pages section of the same response:
```
## Pages
Note: the previously selected page was closed. Page 1 is now selected.
1: about:blank [selected]
```
For a selected page that is missing from the list without being closed,
the note reads "is no longer listed" instead. If the expectation from
#2304 holds (a page stays listed as long as it is not closed), that
wording never renders; if the transient case discussed there does occur
in the wild, the note will make it visible.
The fallback behavior itself is unchanged (as discussed in #2304, closed
tabs keep the browser-like auto-selection). No note is emitted on first
connect, when nothing was selected before.
Tests: two unit tests for the fallback bookkeeping (closed page, regular
selection), one for the missing-but-open case via a stubbed page list,
and the one affected snapshot updated (`close_page` now includes the
note).
Refs: #2304
Fixes output path validation so tools cannot validate one path and then
write to a different canonical target after extension enforcement.
Changes:
- Resolve dangling symlinks to their target path during
canonicalization.
- Validate the final extension-enforced output path before writing.
- Apply the same final-path validation to heap snapshots and
screencasts.
- Add regression coverage for dangling symlinks that point outside
configured roots.
Validation:
- npm run format
- npm run check-format
- npm run test tests/utils/files.test.ts
- npm run test tests/roots.test.ts
- npm run test tests/tools/memory.test.ts tests/tools/screencast.test.ts
Note: I also ran the full npm test suite locally. The targeted tests
above passed, but the full suite hit local WSL daemon/e2e startup
timeouts while waiting for daemon.pid / server_start, which appear
unrelated to this path-validation change.
---------
Co-authored-by: huynhtrungcsc <huynhtrungcsc@users.noreply.github.com>
Fixes flakiness in pages.test.ts where unawaited page.evaluate()
promises triggering dialogs would resolve after the test ended, causing
TargetCloseError when the next test closed the pages.
TAG=agy
CONV=dc6c530f-5d71-4a91-9440-6a7006d168e6
Co-authored-by: Piotr Paulski <piotrpaulski@chromium.org>
Instead of two separate MCP tools, we can have one instead which takes
classIndex as optional argument.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
This commit adds two MCP tools for comparing heap snapshots.
`compare_heapsnapshot_summary` compares two memory snapshot and returns
which classes have new/deleted objects.
`compare_heapsnapshot_class_nodes` can then be used to list the object
ids added and deleted for a specific class.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
Since toon dependency is only needed for `--experimentalToonFormat`
flag, we can make it optional to decrease package size and security
footprint for users that don't use it.
Testing npx optional peer dependency resolution before the release:
```
npm i -g verdaccio
verdaccio
```
On a separate terminal:
```
npm adduser --registry http://localhost:4873/
# follow prompts to create user and login
# replace the published package in verdaccio
npm unpublish chrome-devtools-mcp@1.4.0 --force --registry http://localhost:4873
npm publish --registry http://localhost:4873
# clear npx cache
rm -rf ~/.npm/_npx
# run the server from commandline and observe both packages being installed:
npx --registry http://localhost:4873 --package chrome-devtools-mcp@latest --package @toon-format/toon chrome-devtools-mcp --experimentalToonFormat
```
Paste the following commands (each line separately) to manually interact
with the mcp server and observe TOON formatted response directly
### 1. Initialize the session
{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test-client","version":"1.0.0"}}}
### 2. Confirm initialization
{"jsonrpc":"2.0","method":"notifications/initialized"}
### 3. Navigate to Google (this will already create snapshot in most
recent versions)
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"navigate_page","arguments":{"url":"https://google.com"}}}
### 4. Take Snapshot (if not returned by the previous command)
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"take_snapshot","arguments":{}}}
---------
Co-authored-by: Piotr Paulski <piotrpaulski@chromium.org>
## Summary
Fixes#2230.
- Sets `windowsHide: true` on the detached update-check process so
Windows does not flash a console window.
- Also hides the `npm config get registry` subprocess used by the
updater helper.
- Covers the update-check spawn options in the existing tests.
## Verification
- `NODE_OPTIONS=--max-old-space-size=4096 npm run build`
- `npm run test:no-build -- tests/check-for-updates.test.ts`
- `NODE_OPTIONS=--max-old-space-size=4096 npx eslint
src/utils/check-for-updates.ts src/bin/check-latest-version.ts
tests/check-for-updates.test.ts`
- `npx prettier --check src/utils/check-for-updates.ts
src/bin/check-latest-version.ts tests/check-for-updates.test.ts`
- `git diff --check`
Note: plain `npm run build` and full-repo `npm run check-format` hit the
local Node heap limit in this runner; the same build passed with the
heap limit raised, and touched-file lint/format checks passed.
Co-authored-by: cyphercodes <cyphercodes@users.noreply.github.com>
## Problem
`get_network_request` returns, from the **same call**, both a
human-readable
text block (`toStringDetailed()`) and a
`structuredContent.networkRequest`
object (`toJSONDetailed()`) — emitted together in `McpResponse.ts`. For
a
request that went through HTTP redirects, the redirect chain comes out
in
**opposite orders** in the two representations:
- `toJSONDetailed()` (`NetworkFormatter.ts`) reverses `redirectChain()`
once →
newest→oldest in the JSON.
- the text formatter then reverses it **a second time** → oldest→newest
in the
text.
Because each path calls `redirectChain()` separately and Puppeteer
returns a
fresh copy on every call (`HTTPRequest#redirectChain()` does
`this._redirectChain.slice()`), the two reverses operate on different
arrays and
don't cancel. So a consumer reading the text and a consumer parsing the
structured JSON from the same response see contradictory redirect
orders.
## Solution
Drop the redundant `.reverse()` in the text formatter so the rendered
text uses
the order already produced by `toJSONDetailed()`. Both representations
are now
consistent (newest→oldest), and `structuredContent` is unchanged.
## Why the existing tests didn't catch it
- The existing "handles redirect chain" test uses a **single-element**
chain,
where reversing is a no-op.
- `getMockRequest().redirectChain()` returned the **same array
reference** on
every call, unlike real Puppeteer — so the two reverses accidentally
agreed in
tests. This PR makes the mock return a fresh copy per call (matching
Puppeteer)
and adds a regression test with a multi-element chain that asserts the
text and
JSON orders match.
## Testing
- `npm test` for the formatter suite passes. New test
`renders the redirect chain in the same order in text and JSON` is
**red**
before the fix (text `[first, second]` vs JSON `[second, first]`) and
**green**
after, with no change to existing snapshots.
- `npm run typecheck` and Prettier/ESLint are clean.
No existing issue tracked this; found via code inspection and confirmed
empirically.
Fixes#2206
### Problem
`screencast_start` matched the requested file extension with a
**case-sensitive** `endsWith()` against `['.webm', '.mp4']` and
**silently fell back to `.mp4`** when nothing matched. Combined with
`ensureExtension()` (which replaces the extension), a request for
`demo.WEBM` was recorded as **MP4** to **`demo.mp4`** — a different
format *and* path than requested — and any unsupported extension (e.g.
`recording.avi`) silently became `.mp4`.
Separately, when `screencast_start` is called without a `filePath`, it
creates a temp directory via `mkdtemp()`. If `page.screencast()` then
throws (e.g. ffmpeg missing), that directory was leaked.
### Changes
Two commits:
1. **`fix: match screencast extension case-insensitively and reject
unsupported ones`** — match via `path.extname().toLowerCase()`; reject
an explicitly requested but unsupported extension with an explicit error
listing the supported formats; a missing extension still defaults to
`.mp4`.
2. **`fix: clean up screencast temp directory when recording fails to
start`** — remove the generated temp dir in the `catch` handler, but
only when we own the generated path (never when the caller supplied
`filePath`).
| requested | before | after |
| --------------- | --------------- | -------------- |
| `demo.WEBM` | mp4 → `demo.mp4`| webm → `demo.webm` |
| `recording.avi` | mp4 → `recording.mp4` | error (rejected) |
| `demo.webm` | webm → `demo.webm` | unchanged |
| *(no filePath)* | mp4 temp | unchanged |
The matched extension is normalized to lower case (`demo.WEBM` →
`demo.webm`).
### Testing
Added three regression tests to `tests/tools/screencast.test.ts` using
the existing `sinon`/`withMcpContext` harness. Verified locally against
Chrome for Testing 149 (`PUPPETEER_EXECUTABLE_PATH`):
- With the fix reverted, the two extension tests fail (uppercase `.WEBM`
→ mp4, `.avi` not rejected) and the cleanup test fails (temp dir left
behind) — i.e. they fail for the right reason.
- With the fix applied, the full `screencast.test.ts` suite passes
(11/11).
- `tsc --noEmit` and `npm run check-format` (eslint + prettier) are
clean.
> Note: I ran the `screencast` test file (which stubs `page.screencast`)
plus typecheck/lint locally; the rest of the browser-based suite I left
to CI.
### Notes for reviewers
- I chose to **`throw`** for an unsupported explicit extension
(consistent with the ffmpeg-missing `throw` in the same handler and with
the issue's "reject with an explicit error"). Happy to switch to the
softer `appendResponseLine(...) + return` style used by the in-progress
guard if you'd prefer.
- The two commits are independent and can be split if you'd rather take
them separately.
- I left the pre-existing `as \`${string}.webm\`` assertion on
`resolvedPath` untouched to keep the diff focused, though it's slightly
misleading now that the default is `.mp4`.
---------
Co-authored-by: Nicholas Roscino <nroscino@google.com>
## Summary
Adds **opt-in** CLI flags so operators can cap the size of screenshots
returned by `take_screenshot` before they are embedded in the MCP
response. Refs #879.
The flags address two related symptoms reported when MCP clients display
screenshots inline:
1. **Per-image dimension limit**: hosted LLM APIs commonly reject images
exceeding per-image dimension constraints (typical caps are in the
2000-8000 px range, sometimes scaling down further when many images are
in the same request). This is the exact error reported in #879.
2. **Cumulative request size**: after many captures, the cumulative
base64 payload eventually pushes a request over the per-call body size
limit imposed by the LLM API.
Both can be mitigated at the source by reducing format/quality and
downscaling the capture.
## New flags (all opt-in)
- `--screenshot-format <jpeg|png|webp>`: override the default format
used by `take_screenshot` when the caller does not specify one
- `--screenshot-quality <0-100>`: override the default JPEG/WebP
quality. Ignored for PNG
- `--screenshot-max-width <px>`: downscale screenshots wider than this
before they are returned
- `--screenshot-max-height <px>`: downscale screenshots taller than
this. Combines with `--screenshot-max-width`; the smaller scale wins so
both bounds are respected while preserving aspect ratio
For the exact error in #879, the recipe is `--screenshot-max-width=8000
--screenshot-max-height=8000` (or a smaller value such as `2000` if many
images may end up in the same request, depending on the operator's
chosen API).
## Implementation
- Resizing leverages Puppeteer's `clip.scale` (CDP
`Page.captureScreenshot`), so **no new dependencies**.
- Source dimensions per capture mode:
- viewport: `page.viewport()`
- full page: `document.documentElement.scrollWidth/scrollHeight` via
`page.evaluate()`
- element (`uid`): `elementHandle.boundingBox()`
- For element and full-page captures with a downscale clip, the call
routes through `page.screenshot({clip})` so the scale parameter applies.
`captureBeyondViewport` is left to Puppeteer's default (`true` when a
clip is set), preserving correct behavior for elements below the fold
and full-page captures.
- ~150 lines of source code, ~200 lines of new tests.
## Backwards compatibility
**Fully opt-in**: when no flags are set, `take_screenshot` returns the
exact same bytes as before. No behavioral change for existing users.
## Design alignment
- Aligned with the **"Reference over Value"** principle in
`docs/design-principles.md`: the existing 2 MB threshold still routes
oversized screenshots to a temporary file. This change only reduces the
size of the **inline base64 fallback path**, which the principles
document calls out as an acceptable exception when MCP clients display
images natively.
- The MCP server **hardcodes no LLM-specific size limits**. Operators
pick the values that match their client/model combination. This keeps
the maintenance surface here minimal as model limits evolve, and is
intended as a **complement to, not a replacement for**, fixes in the MCP
client itself.
## Addressing concerns raised in #879
> "It's not feasible for us to maintain this. Limits will change when
models change." (@natorion)
The flags are pure parameters; nothing about the upstream LLM is encoded
in the server. When a vendor raises (or lowers) a limit, no code change
is needed here, only the operator's CLI args change.
> "`filePath` / `page_resize` already work as a workaround." (@OrKoN)
`filePath` is great when the call site knows it's about to take a huge
screenshot, but as you noted earlier in the thread, an oversized image
already in the request history keeps causing failures even on subsequent
calls. `page_resize` works but mutates the page being debugged. The
resize in this PR happens **between Puppeteer and the MCP response**, so
the inspected page is untouched and the failure mode is prevented at the
source.
> "Should be fixed client side."
Agreed, this PR is intended as a complement, not a substitute. A
client-side fix (e.g. compaction evicts/downsamples old images) handles
the cumulative case for *any* MCP. A server-side cap handles the
per-call dimension limit for users who hit it before compaction can kick
in. The two address overlapping but distinct failure modes.
Happy to drop or rework any of this if the maintainers prefer a
different shape, for example making the threshold automatic from a
single `--max-image-bytes` knob, or rejecting the PR entirely in favor
of waiting for a client-side fix. Just wanted to put a concrete option
on the table.
## Tests
Added 6 new tests:
- `honors screenshotFormat default from CLI args`
- `keeps "png" as default format when no CLI override is set`
- `downscales viewport screenshot when screenshotMaxWidth is set`
- `downscales using the smaller scale when both max-width and max-height
are set`
- `does not resize when source is smaller than the max bounds`
- `downscales full page screenshot when screenshotMaxWidth is set`
All 627 tests in the suite pass. `npm run typecheck` and `npm run
check-format` are clean.
## Notes for reviewers
- The dimensions compared against `--screenshot-max-width/height` are
**CSS pixels** (`page.viewport()`), not raw bitmap pixels. With
`deviceScaleFactor > 1` (HiDPI emulation) the actual bitmap may still be
larger. Happy to clarify this in the option description if preferred.
- For element captures with a downscale clip, the call routes through
`page.screenshot({clip})` instead of `element.screenshot()`. Same-frame
elements are correct (boundingBox returns main-frame coords). I have
**not** exercised this path against cross-origin iframe elements; let me
know if you'd like a fallback there.
- The PR is currently in **Draft** state pending CLA verification and
any feedback on the framing above.
Refs #879
Closes https://github.com/ChromeDevTools/chrome-devtools-mcp/issues/879
Adding the get_heapsnapshot_dominators MCP tool to show the dominators
for a given node. In combination with get_heapsnapshot_retaining_paths
this should help understand what keeps an object reachable and thus
alive.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
Co-authored-by: Nicholas Roscino <nroscino@google.com>
## Summary
`screencast_stop` returns an empty response when no recording is active,
making it impossible for the calling agent to distinguish "stopped
successfully" from "nothing was recording."
`screencast_start` already handles its inverse case with an explicit
error (`"a screencast recording is already in progress"`), so this makes
`stop` consistent.
## Change
Added an error message when `screencast_stop` is called without an
active recording:
```ts
if (!data) {
response.appendResponseLine(
'Error: no active screencast recording to stop.',
);
return;
}
```
## Before
Empty tool response — agent cannot tell what happened.
## After
`Error: no active screencast recording to stop.`
---------
Co-authored-by: Nicholas Roscino <nroscino@google.com>
This PR adds the get_heapsnapshot_edges MCP tool. Agents can use it to
look at the outgoing edges for a specifc object.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
## Motivation
`list_pages` shows each page's URL but not its title, which is painful
when multiple pages share a host — e.g. several tabs under
`app.example.com/u/0/`, `/u/1/`, `/u/2/`. There's no way to tell which
is which without visiting each one, even though every page has a usable
`document.title`.
Fixes#2156.
Closes#2175
## What this changes
- `list_pages` text output now shows the title before the URL when
available: `1: My Page (https://example.com) [selected]`. If the page
has no title (e.g. `about:blank`), the format is unchanged.
- The structured content entry for each page now includes a `title`
field alongside `id`, `url`, and `selected`.
- `page.title()` is awaited with a `.catch(() => '')` so a closed or
erroring page silently falls back to the URL-only format.
- `format()` is made `async` to support the `await` inside the page
loop; `createStructuredPage()` likewise becomes `async`.
## Testing
Start the MCP server with multiple tabs open. Call `list_pages` — pages
with titles now display as `id: Title (url)`. Pages without titles
(`about:blank`, data URLs) display as before.
---------
Co-authored-by: Piotr Paulski <31672205+zyzyzyryxy@users.noreply.github.com>
This PR adds the `get_heapsnapshot_retaining_paths` MCP tool. This can
be used to find the paths from the target object to the GC roots which
keep that object alive.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
This PR introduces the HostBindingAdapter to utilize the functions
usually available to DevTools.
Additionally I moved all the DevTools related files under a `devtools`
directory to better separate the extractor logic.
The patch scripts for DevTools were moved under a function to remove the
side-effect nature of the file.
Now gets called in a the creation of the McpContext (and a before hook
in test.)
Adds `--experimentalToonFormat` boolean flag, controlling how structured
content is formatted in text response.
By default, custom shorthand format is used. With this flag, TOON format
(see https://github.com/toon-format/toon) is used instead.
TOON format is supposed to be more token-efficient and less error-prone
for agents to understand than json, but it's not clear if it will be
better on those metrics than the custom format used so far. (Evals
pending)
One clear benefit over custom format would be less code to maintain if
we decide to fully switch to TOON, due to dropping custom formatters and
reusing json formatters used for structuredContent anyways.
Co-authored-by: Piotr Paulski <piotrpaulski@chromium.org>
## Support for Network Blocklists and Allowlists
(`--blocked-url-pattern` & `--allowed-url-pattern` arguments)
This PR adds support for CLI options to restrict network access in the
browser session via URL patterns.
### Key Features & How It Works
- **Pattern Matching:** Utilizes the [URLPattern
Standard](https://urlpattern.spec.whatwg.org/) for pattern matching.
- **Target Detachment:** Silently detaches from targets (pages/tabs)
whose URLs match blocked patterns (or do not match allowed patterns)
upon connection.
- **Runtime Blocking:** Prevents navigations and blocks runtime requests
(such as fetch/XHR and subresources) if they violate the pattern rules.
- **Mutual Exclusivity:** `--blocked-url-pattern` and
`--allowed-url-pattern` conflict with each other and cannot be
configured simultaneously.
- **Browser Requirements:**
- **`--allowed-url-pattern`**: Requires **Chrome 149+**.
- **`--blocked-url-pattern`**: Works on Chrome versions older than 149,
but **Chrome 149+ is highly recommended**.
### Important Limitations & Side Effects
- **Network Emulation/Throttling Conflict:** Network throttling is
disabled when a network blocklist/allowlist is configured, to avoid
conflicting with Puppeteer's underlying blocking mechanisms.
- Using the `emulate` tool to modify `networkConditions` (e.g. setting
to `Offline`) will throw an error: *`Network throttling is not supported
when network blocking (allowlist/blocklist) is configured.`*
- Other emulation settings (e.g., `cpuThrottlingRate`, `geolocation`,
`viewport`) are unaffected and remain fully functional.
---
### Configuration Examples
#### 1. Blocking specific domains or endpoints (Blocklist)
Add the `--blocked-url-pattern` options to the `args` list in your MCP
settings file:
```json
{
"mcpServers": {
"chrome-devtools": {
"command": "npx",
"args": [
"chrome-devtools-mcp@latest",
"--blocked-url-pattern=*://*.blocked-example.com/*",
"--blocked-url-pattern=*://*.another-blocked-example.com/*"
]
}
}
}
```
#### 2. Restricting access to authorized domains (Allowlist)
Add the `--allowed-url-pattern` options to restrict the browser to
permitted hosts (requires Chrome 149+):
```json
{
"mcpServers": {
"chrome-devtools": {
"command": "npx",
"args": [
"chrome-devtools-mcp@latest",
"--allowed-url-pattern=https://*.allowed-example.com/*",
"--allowed-url-pattern=https://*.another-allowed-example.com/*"
]
}
}
}
```
---------
Co-authored-by: Natallia Harshunova <nharshunova@chromium.org>
Co-authored-by: Alex Rudenko <alexrudenko@chromium.org>
Updates the flag for the memory tooling to remove the experimental bit
(keep alias for backwards compatibility).
And updates the SKILLs to reflected the update names and point to the
available tools.
Q: Should it be called `take_heapsnapshot` or `take_heap_snapshot`?
This commit adds the close_heapsnapshot MCP tool such that the coding
agent can close heap snapshots again.
Co-authored-by: Dominik Inführ <dinfuehr@chromium.org>
Co-authored-by: Nicholas Roscino <nroscino@google.com>
This allows a page to have multiple providers of third-party developer
tools, which each respond to the `devtoolstooldiscovery` event.
- Multiple `ToolGroup`s
- MCP tool responses only mention third-party developer tools, if there
are any. Otherwise this part of the output is skipped.
Fixes#2116.
`chrome-devtools-mcp-main.ts` currently has no shutdown handler. After a
session calls `navigate_page` (or anything else that launches Chrome),
the Chrome subprocess keeps the Node event loop ref'd, so closing stdin
(the stdio MCP convention for "I'm done") doesn't make the server exit.
Callers that close stdin to terminate the server have to fall back to
SIGTERM / SIGKILL on every page-loaded session — deterministically, not
flakily.
This change:
1. Adds `closeBrowser()` in `browser.ts` that calls `browser.close()`
for launched instances (reaps the Chrome subprocess) and
`browser.disconnect()` for attached instances (leaves the user's Chrome
alive). No-op if no browser is active or the connection has already been
dropped.
2. Registers shutdown handlers in `chrome-devtools-mcp-main.ts` for:
- `stdin.on('end' | 'close')` — stdio MCP transport convention
- `SIGTERM` / `SIGINT` / `SIGHUP` — clients that signal instead of
closing stdin (`SIGHUP` for parity with `src/daemon/daemon.ts`)
The handler is idempotent (guarded `shuttingDown` flag), and has an
unref'd 10s timeout backstop in case Chrome teardown hangs (slow
`beforeunload` handlers, many tabs, etc.).
### Note on scope
This complements (does not replace) the client-side fixes filed against
#1765, e.g. google-gemini/gemini-cli#13391 and
anthropics/claude-code#42300. The MCP stdio convention is that closing
stdin signals shutdown; a server that doesn't honor that forces every
client to special-case it. The watchdog sub-process
(`src/telemetry/watchdog/main.ts:145-146`) and the daemon
(`src/daemon/daemon.ts:224-230`) both already implement this for the
same reason — this PR extends the same pattern to the main entry point
so all three execution paths behave consistently.
### Measurement
Repro script in #2116, same env (chrome-devtools-mcp@1.0.1, Chrome
148.0.7778.178, Node v24.11.1, Linux), 10 iterations:
| Scenario | Before | After |
|---|---|---|
| `tools/list only` (no navigation) | 10/10 clean, 30-37 ms | 10/10
clean, 29-40 ms |
| `navigate example.com` | 10/10 SIGTERM at ~5080 ms | 10/10 clean at
145-180 ms |
### Notes
- I didn't add a subprocess-based test for this; the existing
`tests/utils.ts:runCli` infrastructure targets the `chrome-devtools`
CLI, not the stdio MCP server, and a shutdown-timing test would
introduce non-trivial Chrome-startup flakiness in CI. Happy to add one
if maintainers want it — pointer to the right test directory
appreciated.
This addresses #1955
CPU throttling needs to be applied to both the primary puppeteer session
and the secondary CDP session from the DevTools universe to have an
effect.
For network throttling this does not seem to be the case, I can see a
slowdown with the current implementation which only applies the network
throttling to the primary CDP session.
I also had to increase the navigation timeout to prevent timeout errors.
## Summary
Extend the existing `emulate` tool with an `extraHTTPHeaders` parameter
that calls Puppeteer's `page.setExtraHTTPHeaders()` (which uses CDP
`Network.setExtraHTTPHeaders` under the hood).
Closes#1175
## Approach
Per [feedback from
@natorion](https://github.com/ChromeDevTools/chrome-devtools-mcp/issues/1175#issuecomment-4097587153),
this integrates into the existing `emulate` tool rather than adding a
standalone tool. The `emulate` tool is already the central hub for
page-level state modifications (userAgent, viewport, networkConditions,
geolocation, colorScheme), and custom HTTP headers fit naturally
alongside them. This also avoids increasing the MCP tool count and LLM
token overhead.
## Changes
- **`src/types.ts`** — Added `extraHTTPHeaders?: Record<string, string>`
to `EmulationSettings`
- **`src/tools/emulation.ts`** — Added `extraHTTPHeaders` as an optional
zod parameter on the `emulate` tool
- **`src/McpContext.ts`** — Added handler logic in the `emulate()`
method:
- Calls `page.setExtraHTTPHeaders()` when `extraHTTPHeaders` is provided
- Clears from settings when an empty `{}` is passed
- Preserves existing headers when the param is **omitted** (unlike other
emulation settings that reset when omitted) — prevents
`emulate({colorScheme: "dark"})` from accidentally clearing
previously-set headers
- **`tests/tools/emulation.test.ts`** — Added 5 test cases:
1. Sets extra headers on requests
2. Clears headers with `{}`
3. Headers persist across navigations
4. Does not affect other emulation settings
5. Reports correctly per-page (new page has no headers)
## Use Case
This enables setting custom HTTP headers on **all** requests — including
the initial document navigation and `<script>` tag loads — which
`initScript` cannot do since it runs after the document is already
fetched.
## Usage
```js
// Set headers
emulate({ extraHTTPHeaders: { "X-Custom": "value", "Authorization": "Bearer token" } })
// Clear headers
emulate({ extraHTTPHeaders: {} })
// Combine with other emulation settings
emulate({ extraHTTPHeaders: { "X-Branch": "feature-1" }, userAgent: "MyBot/1.0" })
```
---------
Co-authored-by: Alex Rudenko <alexrudenko@chromium.org>
Co-authored-by: Nicholas Roscino <nroscino@google.com>