Chrome DevTools for coding agents
feat: Add get_heapsnapshot_duplicate_strings MCP tool (#2280)
Dominik Inführ67a56c055772
diff --git a/README.md b/README.mdindex ab45b255..15ef3b19 100644--- a/README.md+++ b/README.md@@ -514,13 +514,14 @@ If you run into any issues, checkout our [troubleshooting guide](./docs/troubles- [`take_snapshot`](docs/tool-reference.md#take_snapshot)- [`screencast_start`](docs/tool-reference.md#screencast_start)- [`screencast_stop`](docs/tool-reference.md#screencast_stop)-- **Memory** (10 tools)+- **Memory** (11 tools)- [`take_heapsnapshot`](docs/tool-reference.md#take_heapsnapshot)- [`close_heapsnapshot`](docs/tool-reference.md#close_heapsnapshot)- [`compare_heapsnapshots`](docs/tool-reference.md#compare_heapsnapshots)- [`get_heapsnapshot_class_nodes`](docs/tool-reference.md#get_heapsnapshot_class_nodes)- [`get_heapsnapshot_details`](docs/tool-reference.md#get_heapsnapshot_details)- [`get_heapsnapshot_dominators`](docs/tool-reference.md#get_heapsnapshot_dominators)+ - [`get_heapsnapshot_duplicate_strings`](docs/tool-reference.md#get_heapsnapshot_duplicate_strings)- [`get_heapsnapshot_edges`](docs/tool-reference.md#get_heapsnapshot_edges)- [`get_heapsnapshot_retainers`](docs/tool-reference.md#get_heapsnapshot_retainers)- [`get_heapsnapshot_retaining_paths`](docs/tool-reference.md#get_heapsnapshot_retaining_paths)diff --git a/docs/tool-reference.md b/docs/tool-reference.mdindex 93adf75e..35f04752 100644--- a/docs/tool-reference.md+++ b/docs/tool-reference.md@@ -39,13 +39,14 @@- [`take_snapshot`](#take_snapshot)- [`screencast_start`](#screencast_start)- [`screencast_stop`](#screencast_stop)-- **[Memory](#memory)** (10 tools)+- **[Memory](#memory)** (11 tools)- [`take_heapsnapshot`](#take_heapsnapshot)- [`close_heapsnapshot`](#close_heapsnapshot)- [`compare_heapsnapshots`](#compare_heapsnapshots)- [`get_heapsnapshot_class_nodes`](#get_heapsnapshot_class_nodes)- [`get_heapsnapshot_details`](#get_heapsnapshot_details)- [`get_heapsnapshot_dominators`](#get_heapsnapshot_dominators)+ - [`get_heapsnapshot_duplicate_strings`](#get_heapsnapshot_duplicate_strings)- [`get_heapsnapshot_edges`](#get_heapsnapshot_edges)- [`get_heapsnapshot_retainers`](#get_heapsnapshot_retainers)- [`get_heapsnapshot_retaining_paths`](#get_heapsnapshot_retaining_paths)@@ -511,6 +512,18 @@ in the DevTools Elements panel (if any).---+### `get_heapsnapshot_duplicate_strings`++**Description:** Loads a memory heapsnapshot and returns duplicate strings grouped by their value. (requires flag: --memoryDebugging=true)++**Parameters:**++- **filePath** (string) **(required)**: A path to a .heapsnapshot file to read.+- **pageIdx** (number) _(optional)_: The page index for pagination.+- **pageSize** (number) _(optional)_: The page size for pagination.++---+### `get_heapsnapshot_edges`**Description:** Loads a memory heapsnapshot and returns outgoing edges (references) for a specific node ID. (requires flag: --memoryDebugging=true)diff --git a/src/HeapSnapshotManager.ts b/src/HeapSnapshotManager.tsindex 3cd0c893..fc19d219 100644--- a/src/HeapSnapshotManager.ts+++ b/src/HeapSnapshotManager.ts@@ -34,6 +34,9 @@ export interface HeapSnapshotDetailedClassDiff extends HeapSnapshotClassDiff {deletedSelfSizes: number[];}+export type DuplicateStringGroup =+ DevTools.HeapSnapshotModel.HeapSnapshotModel.DuplicateStringGroup;+export class HeapSnapshotManager {#snapshotIdGenerator = createIdGenerator();#snapshots = new Map<@@ -324,6 +327,11 @@ export class HeapSnapshotManager {return {snapshot, worker: workerProxy};}+ async getDuplicateStrings(filePath: string): Promise<DuplicateStringGroup[]> {+ const snapshot = await this.getSnapshot(filePath);+ return await snapshot.getDuplicateStrings();+ }+hasSnapshots(): boolean {return this.#snapshots.size > 0;}diff --git a/src/McpContext.ts b/src/McpContext.tsindex 46a59560..b7505a54 100644--- a/src/McpContext.ts+++ b/src/McpContext.ts@@ -20,6 +20,7 @@ import type {AggregatedInfoWithId,HeapSnapshotClassDiff,HeapSnapshotDetailedClassDiff,+ DuplicateStringGroup,} from './HeapSnapshotManager.js';import {McpPage} from './McpPage.js';import {@@ -914,6 +915,12 @@ export class McpContext implements Context {return await this.#heapSnapshotManager.getAggregates(filePath);}+ async getHeapSnapshotDuplicateStrings(+ filePath: string,+ ): Promise<DuplicateStringGroup[]> {+ return await this.#heapSnapshotManager.getDuplicateStrings(filePath);+ }+async getHeapSnapshotStats(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.Statistics> {diff --git a/src/McpResponse.ts b/src/McpResponse.tsindex 0e613949..b7e19552 100644--- a/src/McpResponse.ts+++ b/src/McpResponse.ts@@ -19,6 +19,7 @@ import {SnapshotFormatter} from './formatters/SnapshotFormatter.js';import type {HeapSnapshotClassDiff,HeapSnapshotDetailedClassDiff,+ DuplicateStringGroup,} from './HeapSnapshotManager.js';import type {McpContext} from './McpContext.js';import type {McpPage} from './McpPage.js';@@ -234,6 +235,7 @@ export class McpResponse implements Response {dominators?: DevTools.HeapSnapshotModel.HeapSnapshotModel.DominatorChain;classDiffs?: HeapSnapshotClassDiff[];detailedClassDiff?: HeapSnapshotDetailedClassDiff;+ duplicateStrings?: DuplicateStringGroup[];};#networkRequestsOptions?: {include: boolean;@@ -490,6 +492,18 @@ export class McpResponse implements Response {};}+ setHeapSnapshotDuplicateStrings(+ duplicateStrings: DuplicateStringGroup[],+ options?: PaginationOptions,+ ) {+ this.#heapSnapshotOptions = {+ ...this.#heapSnapshotOptions,+ include: true,+ duplicateStrings,+ pagination: options,+ };+ }+setHeapSnapshotRetainingPaths(retainingPaths: DevTools.HeapSnapshotModel.HeapSnapshotModel.RetainingPaths,) {@@ -861,6 +875,7 @@ export class McpResponse implements Response {heapSnapshotDominators?: readonly object[];heapSnapshotClassDiffs?: HeapSnapshotClassDiff[];heapSnapshotDetailedClassDiff?: HeapSnapshotDetailedClassDiff;+ heapSnapshotDuplicateStrings?: readonly DuplicateStringGroup[];extensionServiceWorkers?: object[];extensionPages?: object[];errorMessage?: string;@@ -1219,6 +1234,24 @@ Call ${handleDialog.name} to handle it before continuing.`););structuredContent.heapSnapshotDetailedClassDiff = detailedClassDiff;}+ const duplicateStrings = this.#heapSnapshotOptions.duplicateStrings;+ if (duplicateStrings) {+ response.push('### Duplicate Strings');+ const paginationData = this.#dataWithPagination(+ duplicateStrings,+ this.#heapSnapshotOptions.pagination,+ );++ structuredContent.pagination = paginationData.pagination;+ response.push(...paginationData.info);++ const formatted = HeapSnapshotFormatter.formatDuplicateStrings(+ paginationData.items,+ );+ response.push(formatted);++ structuredContent.heapSnapshotDuplicateStrings = paginationData.items;+ }}if (data.detailedNetworkRequest) {diff --git a/src/bin/chrome-devtools-cli-options.ts b/src/bin/chrome-devtools-cli-options.tsindex a6d06391..b0d6a4fe 100644--- a/src/bin/chrome-devtools-cli-options.ts+++ b/src/bin/chrome-devtools-cli-options.ts@@ -407,6 +407,31 @@ export const commands: Commands = {},},},+ get_heapsnapshot_duplicate_strings: {+ description:+ 'Loads a memory heapsnapshot and returns duplicate strings grouped by their value. (requires flag: --memoryDebugging=true)',+ category: 'Memory',+ args: {+ filePath: {+ name: 'filePath',+ type: 'string',+ description: 'A path to a .heapsnapshot file to read.',+ required: true,+ },+ pageIdx: {+ name: 'pageIdx',+ type: 'number',+ description: 'The page index for pagination.',+ required: false,+ },+ pageSize: {+ name: 'pageSize',+ type: 'number',+ description: 'The page size for pagination.',+ required: false,+ },+ },+ },get_heapsnapshot_edges: {description:'Loads a memory heapsnapshot and returns outgoing edges (references) for a specific node ID. (requires flag: --memoryDebugging=true)',diff --git a/src/formatters/HeapSnapshotFormatter.ts b/src/formatters/HeapSnapshotFormatter.tsindex 2734dfc6..ac4cda34 100644--- a/src/formatters/HeapSnapshotFormatter.ts+++ b/src/formatters/HeapSnapshotFormatter.ts@@ -8,6 +8,7 @@ import type {AggregatedInfoWithId,HeapSnapshotClassDiff,HeapSnapshotDetailedClassDiff,+ DuplicateStringGroup,} from '../HeapSnapshotManager.js';import {DevTools} from '../third_party/index.js';import {stableIdSymbol} from '../utils/id.js';@@ -121,6 +122,21 @@ export class HeapSnapshotFormatter {return lines.join('\n');}+ static formatDuplicateStrings(+ groups: readonly DuplicateStringGroup[],+ ): string {+ const lines: string[] = [];+ lines.push('value,count,totalSelfSize,totalRetainedSize,truncated,nodeIds');+ for (const group of groups) {+ const nodeIds = group.nodes.map(n => `@${n.id}`).join(' ');+ const truncated = group.truncated ?? false;+ lines.push(+ `${JSON.stringify(group.value)},${group.count},${DevTools.I18n.ByteUtilities.formatBytesToKb(group.totalSelfSize)},${DevTools.I18n.ByteUtilities.formatBytesToKb(group.totalRetainedSize)},${truncated},${nodeIds}`,+ );+ }+ return lines.join('\n');+ }+#getSortedAggregates(): AggregatedInfoWithId[] {return Object.values(this.#aggregates).sort((a, b) => b.maxRet - a.maxRet);}diff --git a/src/telemetry/tool_call_metrics.json b/src/telemetry/tool_call_metrics.jsonindex 10feca6a..2d44ef99 100644--- a/src/telemetry/tool_call_metrics.json+++ b/src/telemetry/tool_call_metrics.json@@ -859,5 +859,22 @@"argType": "number"}]+ },+ {+ "name": "get_heapsnapshot_duplicate_strings",+ "args": [+ {+ "name": "file_path_length",+ "argType": "number"+ },+ {+ "name": "page_idx",+ "argType": "number"+ },+ {+ "name": "page_size",+ "argType": "number"+ }+ ]}]diff --git a/src/tools/ToolDefinition.ts b/src/tools/ToolDefinition.tsindex 27569c54..e135344b 100644--- a/src/tools/ToolDefinition.ts+++ b/src/tools/ToolDefinition.ts@@ -9,6 +9,7 @@ import type {AggregatedInfoWithId,HeapSnapshotClassDiff,HeapSnapshotDetailedClassDiff,+ DuplicateStringGroup,} from '../HeapSnapshotManager.js';import type {McpPage} from '../McpPage.js';import {zod} from '../third_party/index.js';@@ -120,6 +121,10 @@ export interface Response {nodes: DevTools.HeapSnapshotModel.HeapSnapshotModel.ItemsRange,options?: PaginationOptions,): void;+ setHeapSnapshotDuplicateStrings(+ duplicateStrings: DuplicateStringGroup[],+ options?: PaginationOptions,+ ): void;setHeapSnapshotRetainingPaths(retainingPaths: DevTools.HeapSnapshotModel.HeapSnapshotModel.RetainingPaths,): void;@@ -253,6 +258,9 @@ export type Context = Readonly<{getHeapSnapshotAggregates(filePath: string,): Promise<Record<string, AggregatedInfoWithId>>;+ getHeapSnapshotDuplicateStrings(+ filePath: string,+ ): Promise<DuplicateStringGroup[]>;getHeapSnapshotStats(filePath: string,): Promise<DevTools.HeapSnapshotModel.HeapSnapshotModel.Statistics>;diff --git a/src/tools/memory.ts b/src/tools/memory.tsindex 219b355b..e4d9c37d 100644--- a/src/tools/memory.ts+++ b/src/tools/memory.ts@@ -324,3 +324,31 @@ export const compareHeapSnapshots = defineTool({}},});++export const getHeapSnapshotDuplicateStrings = defineTool({+ name: 'get_heapsnapshot_duplicate_strings',+ description:+ 'Loads a memory heapsnapshot and returns duplicate strings grouped by their value.',+ annotations: {+ category: ToolCategory.MEMORY,+ readOnlyHint: true,+ conditions: ['memoryDebugging'],+ },+ blockedByDialog: false,+ verifyFilesSchema: ['filePath'],+ schema: {+ filePath: zod.string().describe('A path to a .heapsnapshot file to read.'),+ pageIdx: zod.number().optional().describe('The page index for pagination.'),+ pageSize: zod.number().optional().describe('The page size for pagination.'),+ },+ handler: async (request, response, context) => {+ const duplicateStrings = await context.getHeapSnapshotDuplicateStrings(+ request.params.filePath,+ );++ response.setHeapSnapshotDuplicateStrings(duplicateStrings, {+ pageIdx: request.params.pageIdx,+ pageSize: request.params.pageSize,+ });+ },+});diff --git a/tests/tools/memory.test.js.snapshot b/tests/tools/memory.test.js.snapshotindex 38eb499d..3bb55cf4 100644--- a/tests/tools/memory.test.js.snapshot+++ b/tests/tools/memory.test.js.snapshot@@ -221,6 +221,26 @@ nodeId,nodeName,selfSize,retainedSize1,,0.0 kB,802 kB`;+exports[`memory > get_heapsnapshot_duplicate_strings > with default options 1`] = `+## Heap Snapshot Data+### Duplicate Strings+Showing 1-13 of 13 (Page 1 of 1).+value,count,totalSelfSize,totalRetainedSize,truncated,nodeIds+"get disposed",8,0.2 kB,0.2 kB,false,@30685 @30731 @33713 @33781 @42891 @42947 @45203 @45233+"WebAssembly.Suspending",4,0.1 kB,0.1 kB,false,@44967 @45473 @46069 @46195+"extensions::SafeBuiltins",2,0.1 kB,0.1 kB,false,@25155 @26209+"WebAssembly",2,0.0 kB,0.0 kB,false,@7495 @15037+"EventTarget",3,0.0 kB,0.0 kB,false,@13309 @25089 @26185+"v8/LoadTimes",2,0.0 kB,0.0 kB,false,@25159 @26365+"Document",3,0.0 kB,0.0 kB,false,@12341 @25969 @26603+"WebAssembly.Exception",2,0.0 kB,0.0 kB,false,@1855 @7473+"WebAssembly.Module",2,0.0 kB,0.0 kB,false,@1857 @7429+"HTMLBodyElement",2,0.0 kB,0.0 kB,false,@13679 @44753+"MutationObserver",2,0.0 kB,0.0 kB,false,@14347 @32179+"HTMLElement",2,0.0 kB,0.0 kB,false,@11557 @43899+" ",2,0.0 kB,0.0 kB,false,@725 @789+`;+exports[`memory > get_heapsnapshot_edges > with pagination 1`] = `## Heap Snapshot Dataname,type,nodeId,nodeNamediff --git a/tests/tools/memory.test.ts b/tests/tools/memory.test.tsindex d7416792..0e8538cb 100644--- a/tests/tools/memory.test.ts+++ b/tests/tools/memory.test.ts@@ -22,6 +22,7 @@ import {getHeapSnapshotEdges,getHeapSnapshotDominators,compareHeapSnapshots,+ getHeapSnapshotDuplicateStrings,} from '../../src/tools/memory.js';import {withMcpContext} from '../utils.js';@@ -526,4 +527,31 @@ describe('memory', () => {assert.equal(secondNewObjectDiff.addedCount, 5);});});++ describe('get_heapsnapshot_duplicate_strings', () => {+ it('with default options', async t => {+ await withMcpContext(async (response, context) => {+ const filePath = join(+ process.cwd(),+ 'tests/fixtures/example.heapsnapshot',+ );++ await getHeapSnapshotDuplicateStrings.handler(+ {params: {filePath}},+ response,+ context,+ );++ const responseData = await response.handle(+ getHeapSnapshotDuplicateStrings.name,+ context,+ );+ const output = responseData.content+ .map(c => (c.type === 'text' ? c.text : ''))+ .join('\n');++ t.assert.snapshot(output);+ });+ });+ });});