# My agent found the memory leak. Its own snapshot padded the number.

- Published: 2026-11-07
- Tags: AI Agents, Debugging, Tooling
- URL: https://devtrillo.com/writing/devtools-mcp-memory-leak-hunt/

I planted a memory leak in a small page and let my agent hunt it. Claude Code had the Chrome DevTools MCP server with its memory tools on, and one rule: don't read the source until a heap snapshot gives you a reason to. It took 26 turns and 81 seconds. It found the listener nobody removed, fixed it, and proved the fix with a second pair of snapshots.

Then it told me the leak cost "about 100 kB" every time someone opened and closed the panel. When I ran the same page through the same tools without the agent, it was 40 kB. Most of the difference was the agent looking at the page.

_Already know this? Jump to [The hunt, tool by tool](https://devtrillo.com/writing/devtools-mcp-memory-leak-hunt/#the-hunt-tool-by-tool)._

## Turning the memory tools on

Everything here is `chrome-devtools-mcp` 1.12.0 (released October 22, 2026), headless Chrome 155 on macOS, and Claude Code 2.1.309.

Out of the box the server has 32 tools, and `take_heapsnapshot` is already one of them. It writes a `.heapsnapshot` file and does nothing else with it.

You can't ask an agent to read that file directly; my baseline snapshot was a 3.1 MB file for a page with one button. The [October DevTools release notes](https://developer.chrome.com/blog/new-in-devtools-october-2026) cover the newer pieces, and `--memoryDebugging` adds 13 tools that parse the file inside the server and hand back tables:

| Tool                               | What it answers                                                |
| ---------------------------------- | -------------------------------------------------------------- |
| `compare_heapsnapshots`            | What grew between two snapshots, by class                      |
| `query_heapsnapshot_objects`       | Find objects by class, property, size or `isDetached`          |
| `get_heapsnapshot_retaining_paths` | Why is this node still alive?                                  |
| `get_heapsnapshot_dominators`      | Which single object would free it if it went away?             |
| `get_heapsnapshot_details`         | Aggregates, with filters like `objectsRetainedByEventHandlers` |

The other eight cover retainers, edges, class nodes, object details, duplicate strings, closure contexts, a summary, and `close_heapsnapshot` to free the parsed file. The release notes call the query tool `query_heapsnapshot`. In 1.12.0 it's `query_heapsnapshot_objects`.

For Claude Code, the flag goes after the package name:

```sh title="add the server with memory tools"
claude mcp add chrome-devtools --scope user -- npx -y chrome-devtools-mcp@latest --memoryDebugging
```

I ran it with `--scope project` and a pinned version in the lab, which writes the same thing to `.mcp.json`. The [client configuration guide](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/client-configurations.md) also has a plugin install that ships the server's skills, including one called `memory-leak-debugging`. My run didn't have it.

> **Note:** Snapshot files have to land inside a directory the server allows. The agent's
> first `take_heapsnapshot` call went to its scratchpad and failed with "is not
> within any of the configured workspace roots". It retried in a `.heap/` folder
> in the project and that worked. If yours does the same, put `.heap/` in
> `.gitignore`; these files are big.

## A leak worth finding

The page is plain JavaScript, no framework. A button opens an order panel with 200 rows, and the panel has a Close button. While it's open, a `resize` listener on `window` keeps the panel's height in check:

```js title="app.js (the leak)"
class OrderPanel {
  constructor(orders) {
    this.el = document.createElement("section");
    this.rows = orders.map((o) => {
      const row = document.createElement("div");
      row.textContent = `#${o.id} ${o.item} x${o.qty}`;
      this.el.append(row);
      return row;
    });
    this.onResize = () => {
      this.el.style.maxHeight = `${window.innerHeight - 100}px`;
    };
    window.addEventListener("resize", this.onResize);
    // ...a Close button that calls this.destroy()
  }
  destroy() {
    this.el.remove();
  }
}
```

`destroy()` takes the panel out of the DOM and forgets the listener. `window` still holds the arrow function, the arrow function closes over `this`, and `this.el` is the whole detached panel.

React's version of this bug is a `useEffect` that adds a listener and returns no cleanup; the heap looks the same.

## The hunt, tool by tool

Here's the order the agent called things in, with what came back. I've cut the absolute paths.

It opened the page, took an accessibility snapshot to find the buttons, clicked Open and Close once with `click`, and took a baseline heap snapshot. Then it drove 20 more open/close cycles from `evaluate_script` with 20 ms pauses and took a second snapshot.

`compare_heapsnapshots` on those two put the leak right at the top:

```text title="compare_heapsnapshots, 20 cycles, agent run"
Total: # new: 57277, # deleted: 20427, # delta: +36850, size delta: +1,975 kB
className,countDelta,sizeDelta
blink::AXNodeObject,4040,420 kB
Detached <div>,4000,416 kB
Detached Text,4020,322 kB
Detached blink::NodeRareData,8060,258 kB
...
Detached <button>,20,
```

4,000 detached `<div>`s from 20 cycles is 200 per panel, exactly the row count. The agent picked one of the 21 detached `<section>` nodes from `query_heapsnapshot_objects` and asked for its retaining path:

```text title="get_heapsnapshot_retaining_paths, trimmed"
<- OrderPanel via property el
  <- system / Context via context this
    <- (closure) via internal context
      <- V8EventListener
        <- EventListener
          <- blink::RegisteredEventListener
            ...
              <- blink::EventTargetData
                <- Window / http://localhost:8766
```

Read from the bottom: `Window` has event listener data, one entry is a V8 listener, its closure context holds `this`, and `this.el` is the section. Only then did it open `app.js`, say the code matched the evidence, and add one line:

```js title="the fix"
destroy() {
  window.removeEventListener("resize", this.onResize);
  this.el.remove();
}
```

To verify, it reloaded with the cache off, ran `evaluate_script` to check the served file contained `removeEventListener` (I liked that), and repeated the two snapshots. The diff came back at +70 objects and +98.5 kB, and `query_heapsnapshot_objects` with `isDetached: true` returned nothing.

Of that 98.5 kB, 65.5 kB was one internal Blink hash table. It deleted its `.heap/` folder and wrote me a before/after table.

Reproduce, diff, follow the path, fix, snapshot again: 19 MCP calls and $0.77.

### The path is noisy, the dominator chain isn't

The full retaining path output doesn't stop at `Window`. Past it, the tool keeps listing every handle that holds the native context: `stringify`, `parse`, `Promise`, `RegExp` and a dozen more, all at distance 2 or 3, until it hits its node limit. None of it matters. The agent cut it off correctly, but a model with less patience could chase those.

`get_heapsnapshot_dominators` answers the same question with one line per object. When I ran it on an `OrderPanel` from my own snapshot, the chain went from `OrderPanel` (38.3 kB retained) through the closure context and the event listener entries to `blink::EventTargetData` at 385 kB, then `Window`. That 385 kB is every leaked panel at once, sitting under one listener list. The agent never called this tool. I'd tell it to.

## Where the 100 kB came from

The agent's table said +1,975 kB over 20 cycles, about 99 kB each. I ran the same leaky page through the same server with a script: no accessibility snapshot, no `click` tool, 10 cycles straight from `evaluate_script`. That diff was +399 kB, 40 kB a cycle, with no `AXNodeObject` rows anywhere.

The difference is the agent's eyes. `take_snapshot` and `click` read the page through the accessibility tree. Once that's switched on, Chrome builds accessibility objects and extra per-node data for every new element, and they leak right along with the panels.

To check, I took one `take_snapshot` before the baseline and changed nothing else. The same 10 cycles went from +399 kB to +668 kB, with `Detached blink::NodeRareData` showing up where it hadn't before.

**Quiz:** An agent reports that closing a modal leaks 100 kB each time. Before you open a performance ticket with that number, what do you check?

- Whether the agent used the accessibility snapshot or the click tool before the baseline
- Whether the agent took the snapshots in headless mode
- Nothing. The diff is computed inside Chrome, so it's exact

**Answer:** Whether the agent used the accessibility snapshot or the click tool before the baseline — Both turn on the accessibility tree, and its objects get retained along with the leaked nodes. In my lab that took 40 kB a cycle to between 67 and 99.

- Not "Whether the agent took the snapshots in headless mode": Both of my runs were headless. Headless wasn't the difference; the accessibility tree was.
- Not "Nothing. The diff is computed inside Chrome, so it's exact": The diff is exact for the page as it was. The page included the agent's own observation.

The leak was real and the fix was right in both runs. The size is what's off. If you're going to quote a number, take the snapshots from a script or ask the agent to use only `evaluate_script` between them.

## What a human still does better

**Deciding what a leak is.** The server's own skill says detached DOM nodes are "sometimes intentional caches" and tells the agent to ask before nulling them. My leak was unambiguous. A virtualized list that keeps 50 offscreen rows around on purpose isn't, and the agent has no way to know which one it's looking at.

**Picking the interaction.** I told it which panel was slow. Finding which of 40 interactions leaks is a judgment call about what users actually do, and it's the slow part of a real hunt. The tools don't help with it.

**Reading the size.** As above. I'd also sanity-check any per-cycle number against the row count, the way 4,000 `<div>`s over 20 cycles told me immediately that one panel's rows were the whole story.

I didn't compare the Memory panel side by side for this post, so I won't claim it's faster or slower. What I'd still open it for is the allocation timeline, which none of these 13 tools offers.

> **Tip:** Give the agent the leak loop in the prompt: baseline after one warm-up cycle,
> N cycles, second snapshot, `compare_heapsnapshots`, then
> `get_heapsnapshot_dominators` on one instance of the top class. Tell it to use
> `evaluate_script` for the cycles if you want a size you can quote.

The agent did the tedious part well: 19 tool calls I'd have made by hand in the Memory panel, in the right order, ending in a one-line fix and a snapshot that proved it. It also measured a page that had an agent looking at it, which isn't the page your users run.
