chrome-devtools-mcp 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +59 -4
  2. package/build/src/HeapSnapshotManager.js +25 -16
  3. package/build/src/McpContext.js +35 -1
  4. package/build/src/McpResponse.js +77 -7
  5. package/build/src/PageCollector.js +1 -1
  6. package/build/src/bin/check-latest-version.js +1 -0
  7. package/build/src/bin/chrome-devtools-cli-options.js +84 -0
  8. package/build/src/bin/chrome-devtools-mcp-cli-options.js +47 -3
  9. package/build/src/{DevToolsConnectionAdapter.js → devtools/DevToolsConnectionAdapter.js} +1 -1
  10. package/build/src/{DevtoolsUtils.js → devtools/DevtoolsUtils.js} +75 -71
  11. package/build/src/devtools/McpHostBindingAdapter.js +165 -0
  12. package/build/src/formatters/ConsoleFormatter.js +1 -1
  13. package/build/src/formatters/HeapSnapshotFormatter.js +22 -0
  14. package/build/src/formatters/NetworkFormatter.js +3 -1
  15. package/build/src/third_party/THIRD_PARTY_NOTICES +4 -4
  16. package/build/src/third_party/bundled-packages.json +3 -3
  17. package/build/src/third_party/devtools-formatter-worker.js +0 -1
  18. package/build/src/third_party/devtools-heap-snapshot-worker.js +67 -3
  19. package/build/src/third_party/index.js +1971 -426
  20. package/build/src/tools/memory.js +76 -0
  21. package/build/src/tools/screencast.js +30 -9
  22. package/build/src/tools/screenshot.js +158 -76
  23. package/build/src/utils/check-for-updates.js +1 -0
  24. package/build/src/version.js +1 -1
  25. package/package.json +7 -6
  26. package/skills/a11y-debugging/SKILL.md +89 -0
  27. package/skills/a11y-debugging/references/a11y-snippets.md +92 -0
  28. package/skills/chrome-devtools/SKILL.md +72 -0
  29. package/skills/chrome-devtools-cli/SKILL.md +153 -0
  30. package/skills/chrome-devtools-cli/references/installation.md +14 -0
  31. package/skills/debug-optimize-lcp/SKILL.md +121 -0
  32. package/skills/debug-optimize-lcp/references/elements-and-size.md +27 -0
  33. package/skills/debug-optimize-lcp/references/lcp-breakdown.md +23 -0
  34. package/skills/debug-optimize-lcp/references/lcp-snippets.md +79 -0
  35. package/skills/debug-optimize-lcp/references/optimization-strategies.md +38 -0
  36. package/skills/memory-leak-debugging/SKILL.md +50 -0
  37. package/skills/memory-leak-debugging/references/common-leaks.md +33 -0
  38. package/skills/memory-leak-debugging/references/compare_snapshots.js +109 -0
  39. package/skills/memory-leak-debugging/references/memlab.md +29 -0
  40. package/skills/troubleshooting/SKILL.md +98 -0
@@ -0,0 +1,72 @@
1
+ ---
2
+ name: chrome-devtools
3
+ description: Uses Chrome DevTools via MCP for efficient debugging, troubleshooting and browser automation. Use when debugging web pages, automating browser interactions, analyzing performance, or inspecting network requests. This skill does not apply to `--slim` mode (MCP configuration).
4
+ ---
5
+
6
+ ## Core Concepts
7
+
8
+ **Browser lifecycle**: Browser starts automatically on first tool call using a persistent Chrome profile. Configure via CLI args in the MCP server configuration: `npx chrome-devtools-mcp@latest --help`.
9
+ Addional tooling can be enabled by providing the following flags:
10
+
11
+ - For extension tooling, use the `--categoryExtensions` flag.
12
+ - For memory tooling, use the `--memoryDebugging` flag.
13
+
14
+ **Page selection**: Tools operate on the currently selected page. Use `list_pages` to see available pages, then `select_page` to switch context.
15
+ **Element interaction**: Use `take_snapshot` to get page structure with element `uid`s. Each element has a unique `uid` for interaction. If an element isn't found, take a fresh snapshot - the element may have been removed or the page changed.
16
+
17
+ ## Workflow Patterns
18
+
19
+ ### Before interacting with a page
20
+
21
+ 1. Navigate: `navigate_page` or `new_page`
22
+ 2. Wait: `wait_for` to ensure content is loaded if you know what you look for.
23
+ 3. Snapshot: `take_snapshot` to understand page structure
24
+ 4. Interact: Use element `uid`s from snapshot for `click`, `fill`, etc.
25
+
26
+ ### Efficient data retrieval
27
+
28
+ - Use `filePath` parameter for large outputs (screenshots, snapshots, traces)
29
+ - Use pagination (`pageIdx`, `pageSize`) and filtering (`types`) to minimize data
30
+ - Set `includeSnapshot: false` on input actions unless you need updated page state
31
+
32
+ ### Tool selection
33
+
34
+ - **Automation/interaction**: `take_snapshot` (text-based, faster, better for automation)
35
+ - **Visual inspection**: `take_screenshot` (when user needs to see visual state)
36
+ - **Additional details**: `evaluate_script` for data not in accessibility tree
37
+
38
+ ### Parallel execution
39
+
40
+ You can send multiple tool calls in parallel, but maintain correct order: navigate → wait → snapshot → interact.
41
+
42
+ ### Testing an extension
43
+
44
+ > **Before proceeding**: Extension tools (`install_extension`, `list_extensions`, etc.) are only available when the MCP server is started with the `--categoryExtensions` flag. If these tools are not in your tool list, stop and ask the user to update their MCP server configuration:
45
+ >
46
+ > ```json
47
+ > {
48
+ > "mcpServers": {
49
+ > "chrome-devtools": {
50
+ > "command": "npx",
51
+ > "args": ["chrome-devtools-mcp@latest", "--categoryExtensions"]
52
+ > }
53
+ > }
54
+ > }
55
+ > ```
56
+ >
57
+ > After updating, the user must restart the MCP server (or their AI client) for the change to take effect.
58
+
59
+ 1. **Install**: Use `install_extension` with the path to the unpacked extension.
60
+ 2. **Identify**: Get the extension ID from the response or by calling `list_extensions`.
61
+ 3. **Trigger Action**: Use `trigger_extension_action` to open the popup or side panel if applicable.
62
+ 4. **Verify Service Worker**: Use `evaluate_script` with `serviceWorkerId` to check extension state or trigger background actions.
63
+ 5. **Verify Page Behavior**: Navigate to a page where the extension operates and use `take_snapshot` to check if content scripts injected elements or modified the page correctly.
64
+
65
+ ## Troubleshooting
66
+
67
+ If `chrome-devtools-mcp` is insufficient, guide users to use Chrome DevTools UI:
68
+
69
+ - https://developer.chrome.com/docs/devtools
70
+ - https://developer.chrome.com/docs/devtools/ai-assistance
71
+
72
+ If there are errors launching `chrome-devtools-mcp` or Chrome, refer to https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/troubleshooting.md.
@@ -0,0 +1,153 @@
1
+ ---
2
+ name: chrome-devtools-cli
3
+ description: Use this skill to write shell scripts or run shell commands to automate tasks in the browser or otherwise use Chrome DevTools via CLI.
4
+ ---
5
+
6
+ The `chrome-devtools-mcp` CLI lets you interact with the browser from your terminal.
7
+
8
+ ## Setup
9
+
10
+ _Note: If this is your very first time using the CLI, see [references/installation.md](references/installation.md) for setup. Installation is a one-time prerequisite and is **not** part of the regular AI workflow._
11
+
12
+ ## AI Workflow
13
+
14
+ 1. **Execute**: Run tools directly (e.g., `chrome-devtools list_pages`). The background server starts implicitly; **do not** run `start`/`status`/`stop` before each use.
15
+ 2. **Inspect**: Use `take_snapshot` to get an element `<uid>`.
16
+ 3. **Act**: Use `click`, `fill`, etc. State persists across commands.
17
+
18
+ Snapshot example:
19
+
20
+ ```
21
+ uid=1_0 RootWebArea "Example Domain" url="https://example.com/"
22
+ uid=1_1 heading "Example Domain" level="1"
23
+ ```
24
+
25
+ ## Command Usage
26
+
27
+ ```sh
28
+ chrome-devtools <tool> [arguments] [flags]
29
+ ```
30
+
31
+ Use `--help` on any command. Output defaults to Markdown, use `--output-format=json` for JSON.
32
+
33
+ ## Input Automation (<uid> from snapshot)
34
+
35
+ ```bash
36
+ chrome-devtools take_snapshot --help # Help message for commands, works for any command.
37
+ chrome-devtools take_snapshot # Take a text snapshot of the page to get UIDs for elements
38
+ chrome-devtools click "id" # Clicks on the provided element
39
+ chrome-devtools click "id" --dblClick true --includeSnapshot true # Double clicks and returns a snapshot
40
+ chrome-devtools drag "src" "dst" # Drag an element onto another element
41
+ chrome-devtools drag "src" "dst" --includeSnapshot true # Drag an element and return a snapshot
42
+ chrome-devtools fill "id" "text" # Type text into an input or select an option
43
+ chrome-devtools fill "id" "text" --includeSnapshot true # Fill an element and return a snapshot
44
+ chrome-devtools handle_dialog accept # Handle a browser dialog
45
+ chrome-devtools handle_dialog dismiss --promptText "hi" # Dismiss a dialog with prompt text
46
+ chrome-devtools hover "id" # Hover over the provided element
47
+ chrome-devtools hover "id" --includeSnapshot true # Hover over an element and return a snapshot
48
+ chrome-devtools press_key "Enter" # Press a key or key combination
49
+ chrome-devtools press_key "Control+A" --includeSnapshot true # Press a key and return a snapshot
50
+ chrome-devtools type_text "hello" # Type text using keyboard into a focused input
51
+ chrome-devtools type_text "hello" --submitKey "Enter" # Type text and press a submit key
52
+ chrome-devtools upload_file "id" "file.txt" # Upload a file through a provided element
53
+ chrome-devtools upload_file "id" "file.txt" --includeSnapshot true # Upload a file and return a snapshot
54
+ ```
55
+
56
+ ## Navigation
57
+
58
+ ```bash
59
+ chrome-devtools close_page 1 # Closes the page by its index
60
+ chrome-devtools list_pages # Get a list of pages open in the browser
61
+ chrome-devtools navigate_page --url "https://example.com" # Navigates the currently selected page to a URL
62
+ chrome-devtools navigate_page --type "reload" --ignoreCache true # Reload page ignoring cache
63
+ chrome-devtools navigate_page --url "https://example.com" --timeout 5000 # Navigate with a timeout
64
+ chrome-devtools navigate_page --handleBeforeUnload "accept" # Handle before unload dialog
65
+ chrome-devtools navigate_page --type "back" --initScript "foo()" # Navigate back and run an init script
66
+ chrome-devtools new_page "https://example.com" # Creates a new page
67
+ chrome-devtools new_page "https://example.com" --background true --timeout 5000 # Create new page in background
68
+ chrome-devtools new_page "https://example.com" --isolatedContext "ctx" # Create new page with isolated context
69
+ chrome-devtools select_page 1 # Select a page as a context for future tool calls
70
+ chrome-devtools select_page 1 --bringToFront true # Select a page and bring it to front
71
+ ```
72
+
73
+ ## Emulation
74
+
75
+ ```bash
76
+ chrome-devtools emulate --networkConditions "Offline" # Emulate network conditions
77
+ chrome-devtools emulate --cpuThrottlingRate 4 --geolocation "0x0" # Emulate CPU throttling and geolocation
78
+ chrome-devtools emulate --colorScheme "dark" --viewport "1920x1080" # Emulate color scheme and viewport
79
+ chrome-devtools emulate --userAgent "Mozilla/5.0..." # Emulate user agent
80
+ chrome-devtools resize_page 1920 1080 # Resizes the selected page's window
81
+ ```
82
+
83
+ ## Performance
84
+
85
+ ```bash
86
+ chrome-devtools performance_analyze_insight "1" "LCPBreakdown" # Get more details on a specific Performance Insight
87
+ chrome-devtools performance_start_trace true false # Starts a performance trace recording
88
+ chrome-devtools performance_start_trace true true --filePath t.gz # Start trace and save to a file
89
+ chrome-devtools performance_stop_trace # Stops the active performance trace
90
+ chrome-devtools performance_stop_trace --filePath "t.json" # Stop trace and save to a file
91
+ chrome-devtools take_memory_snapshot "./snap.heapsnapshot" # Capture a memory heapsnapshot
92
+ ```
93
+
94
+ ## Network
95
+
96
+ ```bash
97
+ chrome-devtools get_network_request # Get the currently selected network request
98
+ chrome-devtools get_network_request --reqid 1 --requestFilePath req.md # Get request by id and save to file
99
+ chrome-devtools get_network_request --responseFilePath res.md # Save response body to file
100
+ chrome-devtools list_network_requests # List all network requests
101
+ chrome-devtools list_network_requests --pageSize 50 --pageIdx 0 # List network requests with pagination
102
+ chrome-devtools list_network_requests --resourceTypes Fetch # Filter requests by resource type
103
+ chrome-devtools list_network_requests --includePreservedRequests true # Include preserved requests
104
+ ```
105
+
106
+ ## Debugging & Inspection
107
+
108
+ ```bash
109
+ chrome-devtools evaluate_script "() => document.title" # Evaluate a JavaScript function on the page
110
+ chrome-devtools evaluate_script "(a) => a.innerText" --args 1_4 # Evaluate JS with UID arguments
111
+ chrome-devtools get_console_message 1 # Gets a console message by its ID
112
+ chrome-devtools lighthouse_audit --mode "navigation" # Run Lighthouse audit for navigation
113
+ chrome-devtools lighthouse_audit --mode "snapshot" --device "mobile" # Run Lighthouse audit for a snapshot on mobile
114
+ chrome-devtools lighthouse_audit --outputDirPath ./out # Run Lighthouse audit and save reports
115
+ chrome-devtools list_console_messages # List all console messages
116
+ chrome-devtools list_console_messages --pageSize 20 --pageIdx 1 # List console messages with pagination
117
+ chrome-devtools list_console_messages --types error --types info # Filter console messages by type
118
+ chrome-devtools list_console_messages --includePreservedMessages true # Include preserved messages
119
+ chrome-devtools take_screenshot # Take a screenshot of the page viewport
120
+ chrome-devtools take_screenshot --fullPage true --format "jpeg" --quality 80 # Take a full page screenshot as JPEG with quality
121
+ chrome-devtools take_screenshot --uid "id" --filePath "s.png" # Take a screenshot of an element
122
+ chrome-devtools take_snapshot # Take a text snapshot of the page from the a11y tree
123
+ chrome-devtools take_snapshot --verbose true --filePath "s.txt" # Take a verbose snapshot and save to file
124
+ ```
125
+
126
+ ## Extensions
127
+
128
+ ```bash
129
+ chrome-devtools list_extensions # Lists all the Chrome extensions installed in the browser
130
+ chrome-devtools install_extension "/path/to/extension" # Installs a Chrome extension from the given path
131
+ chrome-devtools uninstall_extension "extension_id" # Uninstalls a Chrome extension by its ID
132
+ chrome-devtools reload_extension "extension_id" # Reloads an unpacked Chrome extension by its ID
133
+ chrome-devtools trigger_extension_action "extension_id" # Triggers the default action of an extension by its ID
134
+ ```
135
+
136
+ ## Experimental Features
137
+
138
+ Experimental tools are disabled by default. Enable them with the corresponding flag during `start`.
139
+
140
+ ```bash
141
+ chrome-devtools click_at 100 200 # Clicks at the provided coordinates (requires --experimentalVision=true)
142
+ chrome-devtools screencast_start # Starts a screencast recording (requires --experimentalScreencast=true and ffmpeg)
143
+ chrome-devtools screencast_stop # Stops the active screencast
144
+ chrome-devtools list_webmcp_tools # List all WebMCP tools (requires --categoryExperimentalWebmcp=true)
145
+ ```
146
+
147
+ ## Service Management
148
+
149
+ ```bash
150
+ chrome-devtools start # Start or restart chrome-devtools-mcp
151
+ chrome-devtools status # Checks if chrome-devtools-mcp is running
152
+ chrome-devtools stop # Stop chrome-devtools-mcp if any
153
+ ```
@@ -0,0 +1,14 @@
1
+ # Installation
2
+
3
+ Install the package globally to make the `chrome-devtools` command available. You only need to do this the first time you use it.
4
+
5
+ ```sh
6
+ npm i chrome-devtools-mcp@latest -g
7
+ chrome-devtools status # check if install worked.
8
+ ```
9
+
10
+ ## Troubleshooting
11
+
12
+ - **Command not found:** If `chrome-devtools` is not recognized, ensure your global npm `bin` directory is in your system's `PATH`. Restart your terminal or source your shell configuration file (e.g., `.bashrc`, `.zshrc`).
13
+ - **Permission errors:** If you encounter `EACCES` or permission errors during installation, avoid using `sudo`. Instead, use a node version manager like `nvm`, or configure npm to use a different global directory.
14
+ - **Old version running:** Run `chrome-devtools stop && npm uninstall -g chrome-devtools-mcp` before reinstalling, or ensure the latest version is being picked up by your path.
@@ -0,0 +1,121 @@
1
+ ---
2
+ name: debug-optimize-lcp
3
+ description: Guides debugging and optimizing Largest Contentful Paint (LCP) using Chrome DevTools MCP tools. Use this skill whenever the user asks about LCP performance, slow page loads, Core Web Vitals optimization, or wants to understand why their page's main content takes too long to appear. Also use when the user mentions "largest contentful paint", "page load speed", "CWV", or wants to improve how fast their hero image or main content renders.
4
+ ---
5
+
6
+ ## What is LCP and why it matters
7
+
8
+ Largest Contentful Paint (LCP) measures how quickly a page's main content becomes visible. It's the time from navigation start until the largest image or text block renders in the viewport.
9
+
10
+ - **Good**: 2.5 seconds or less
11
+ - **Needs improvement**: 2.5–4.0 seconds
12
+ - **Poor**: greater than 4.0 seconds
13
+
14
+ LCP is a Core Web Vital that directly affects user experience and search ranking. On 73% of mobile pages, the LCP element is an image.
15
+
16
+ ## LCP Subparts Breakdown
17
+
18
+ Every page's LCP breaks down into four sequential subparts with no gaps or overlaps. Understanding which subpart is the bottleneck is the key to effective optimization.
19
+
20
+ | Subpart | Ideal % of LCP | What it measures |
21
+ | ----------------------------- | -------------- | ---------------------------------------------- |
22
+ | **Time to First Byte (TTFB)** | ~40% | Navigation start → first byte of HTML received |
23
+ | **Resource load delay** | <10% | TTFB → browser starts loading the LCP resource |
24
+ | **Resource load duration** | ~40% | Time to download the LCP resource |
25
+ | **Element render delay** | <10% | LCP resource downloaded → LCP element rendered |
26
+
27
+ The "delay" subparts should be as close to zero as possible. If either delay subpart is large relative to the total LCP, that's the first place to optimize.
28
+
29
+ **Common Pitfall**: Optimizing one subpart (like compressing an image to reduce load duration) without checking others. If render delay is the real bottleneck, a smaller image won't help — the saved time just shifts to render delay.
30
+
31
+ ## Debugging Workflow
32
+
33
+ Follow these steps in order. Each step builds on the previous one.
34
+
35
+ ### Step 1: Record a Performance Trace
36
+
37
+ Navigate to the page, then record a trace with reload to capture the full page load including LCP:
38
+
39
+ 1. `navigate_page` to the target URL.
40
+ 2. `performance_start_trace` with `reload: true` and `autoStop: true`.
41
+
42
+ The trace results will include LCP timing and available insight sets. Note the insight set IDs from the output — you'll need them in the next step.
43
+
44
+ ### Step 2: Analyze LCP Insights
45
+
46
+ Use `performance_analyze_insight` to drill into LCP-specific insights. Look for these insight names in the trace results:
47
+
48
+ - **LCPBreakdown** — Shows the four LCP subparts with timing for each.
49
+ - **DocumentLatency** — Server response time issues affecting TTFB.
50
+ - **RenderBlocking** — Resources blocking the LCP element from rendering.
51
+ - **LCPDiscovery** — Whether the LCP resource was discoverable early.
52
+
53
+ Call `performance_analyze_insight` with the insight set ID and the insight name from the trace results.
54
+
55
+ ### Step 3: Identify the LCP Element
56
+
57
+ Use `evaluate_script` with the **"Identify LCP Element" snippet** found in [references/lcp-snippets.md](references/lcp-snippets.md) to reveal the LCP element's tag, resource URL, and raw timing data.
58
+
59
+ The `url` field tells you what resource to look for in the network waterfall. If `url` is empty, the LCP element is text-based (no resource to load).
60
+
61
+ ### Step 4: Check the Network Waterfall
62
+
63
+ Use `list_network_requests` to see when the LCP resource loaded relative to other resources:
64
+
65
+ - Call `list_network_requests` filtered by `resourceTypes: ["Image", "Font"]` (adjust based on Step 3).
66
+ - Then use `get_network_request` with the LCP resource's request ID for full details.
67
+
68
+ **Key Checks:**
69
+
70
+ - **Start Time**: Compare against the HTML document and the first resource. If the LCP resource starts much later than the first resource, there's resource load delay to eliminate.
71
+ - **Duration**: A large resource load duration suggests the file is too big or the server is slow.
72
+
73
+ ### Step 5: Inspect HTML for Common Issues
74
+
75
+ Use `evaluate_script` with the **"Audit Common Issues" snippet** found in [references/lcp-snippets.md](references/lcp-snippets.md) to check for lazy-loaded images in the viewport, missing fetchpriority, and render-blocking scripts.
76
+
77
+ ## Optimization Strategies
78
+
79
+ After identifying the bottleneck subpart, apply these prioritized fixes.
80
+
81
+ ### 1. Eliminate Resource Load Delay (target: <10%)
82
+
83
+ The most common bottleneck. The LCP resource should start loading immediately.
84
+
85
+ - **Root Cause**: LCP image loaded via JS/CSS, `data-src` usage, or `loading="lazy"`.
86
+ - **Fix**: Use standard `<img>` with `src`. **Never** lazy-load the LCP image.
87
+ - **Fix**: Add `<link rel="preload" fetchpriority="high">` if the image isn't discoverable in HTML.
88
+ - **Fix**: Add `fetchpriority="high"` to the LCP `<img>` tag.
89
+
90
+ ### 2. Eliminate Element Render Delay (target: <10%)
91
+
92
+ The element should render immediately after loading.
93
+
94
+ - **Root Cause**: Large stylesheets, synchronous scripts in `<head>`, or main thread blocking.
95
+ - **Fix**: Inline critical CSS, defer non-critical CSS/JS.
96
+ - **Fix**: Break up long tasks blocking the main thread.
97
+ - **Fix**: Use Server-Side Rendering (SSR) so the element exists in initial HTML.
98
+
99
+ ### 3. Reduce Resource Load Duration (target: ~40%)
100
+
101
+ Make the resource smaller or faster to deliver.
102
+
103
+ - **Fix**: Use modern formats (WebP, AVIF) and responsive images (`srcset`).
104
+ - **Fix**: Serve from a CDN.
105
+ - **Fix**: Set `Cache-Control` headers.
106
+ - **Fix**: Use `font-display: swap` if LCP is text blocked by a web font.
107
+
108
+ ### 4. Reduce TTFB (target: ~40%)
109
+
110
+ The HTML document itself takes too long to arrive.
111
+
112
+ - **Fix**: Minimize redirects and optimize server response time.
113
+ - **Fix**: Cache HTML at the edge (CDN).
114
+ - **Fix**: Ensure pages are eligible for back/forward cache (bfcache).
115
+
116
+ ## Verifying Fixes & Emulation
117
+
118
+ - **Verification**: Re-run the trace (`performance_start_trace` with `reload: true`) and compare the new subpart breakdown. The bottleneck should shrink.
119
+ - **Emulation**: Lab measurements differ from real-world experience. Use `emulate` to test under constraints:
120
+ - `emulate` with `networkConditions: "Fast 3G"` and `cpuThrottlingRate: 4`.
121
+ - This surfaces issues visible only on slower connections/devices.
@@ -0,0 +1,27 @@
1
+ # Elements and Size for LCP
2
+
3
+ ## What Elements are Considered?
4
+
5
+ The types of elements considered for Largest Contentful Paint (LCP) are:
6
+
7
+ - **`<img>` elements**: The first frame presentation time is used for animated content like GIFs.
8
+ - **`<image>` elements** inside an `<svg>` element.
9
+ - **`<video>` elements**: The poster image load time or first frame presentation time, whichever is earlier.
10
+ - **Background images**: Elements with a background image loaded using `url()`.
11
+ - **Block-level elements**: Containing text nodes or other inline-level text element children.
12
+
13
+ ## Heuristics to Exclude Non-Contentful Elements
14
+
15
+ Chromium-based browsers use heuristics to exclude:
16
+
17
+ - Elements with **opacity of 0**.
18
+ - Elements that **cover the full viewport** (likely background).
19
+ - **Placeholder images** or low-entropy images.
20
+
21
+ ## How is an Element's Size Determined?
22
+
23
+ - **Visible Area**: Typically the size visible within the viewport. Extending outside, clipped, or overflow portions don't count.
24
+ - **Image Elements**: Either the visible size or the intrinsic size, whichever is smaller.
25
+ - **Text Elements**: The smallest rectangle containing all text nodes.
26
+ - **Exclusions**: Margin, padding, and borders are not considered toward the size.
27
+ - **Containment**: Every text node belongs to its closest block-level ancestor element.
@@ -0,0 +1,23 @@
1
+ # Largest Contentful Paint (LCP) Breakdown
2
+
3
+ LCP measures the time from when the user initiates loading the page until the largest image or text block is rendered within the viewport. To provide a good user experience, sites should strive to have an LCP of 2.5 seconds or less for at least 75% of page visits.
4
+
5
+ ## The Four Subparts of LCP
6
+
7
+ Every page's LCP consists of these four subcategories. There's no gap or overlap between them, and they add up to the full LCP time.
8
+
9
+ | LCP subpart | % of LCP (Optimal) | Description |
10
+ | ----------------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
11
+ | **Time to First Byte (TTFB)** | ~40% | The time from when the user initiates loading the page until the browser receives the first byte of the HTML document response. |
12
+ | **Resource load delay** | <10% | The time between TTFB and when the browser starts loading the LCP resource. If the LCP element doesn't require a resource load (e.g., system font text), this time is 0. |
13
+ | **Resource load duration** | ~40% | The duration of time it takes to load the LCP resource itself. If the LCP element doesn't require a resource load, this time is 0. |
14
+ | **Element render delay** | <10% | The time between when the LCP resource finishes loading and the LCP element rendering fully. |
15
+
16
+ ## Why the Breakdown Matters
17
+
18
+ Optimizing for LCP requires identifying which of these subparts is the bottleneck:
19
+
20
+ - **Large delta between TTFB and FCP**: Indicates the browser needs to download a lot of render-blocking assets or complete a lot of work (e.g., client-side rendering).
21
+ - **Large delta between FCP and LCP**: Indicates the LCP resource is not immediately available for the browser to prioritize or the browser is completing other work before it can display the LCP content.
22
+ - **Large resource load delay**: Indicates the resource is not discoverable early or is deprioritized.
23
+ - **Large element render delay**: Indicates rendering is blocked by stylesheets, scripts, or long tasks.
@@ -0,0 +1,79 @@
1
+ # LCP Debugging Snippets
2
+
3
+ Use these JavaScript snippets with the `evaluate_script` tool to extract deep insights from the page.
4
+
5
+ ## 1. Identify LCP Element
6
+
7
+ Use this snippet to identify the LCP element and get raw timing data from the Performance API.
8
+
9
+ ```javascript
10
+ async () => {
11
+ return await new Promise(resolve => {
12
+ new PerformanceObserver(list => {
13
+ const entries = list.getEntries();
14
+ const last = entries[entries.length - 1];
15
+ resolve({
16
+ element: last.element?.tagName,
17
+ id: last.element?.id,
18
+ className: last.element?.className,
19
+ url: last.url,
20
+ startTime: last.startTime,
21
+ renderTime: last.renderTime,
22
+ loadTime: last.loadTime,
23
+ size: last.size,
24
+ });
25
+ }).observe({type: 'largest-contentful-paint', buffered: true});
26
+ });
27
+ };
28
+ ```
29
+
30
+ ## 2. Audit Common Issues
31
+
32
+ Use this snippet to check for common DOM-based LCP issues (lazy loading, priority).
33
+
34
+ ```javascript
35
+ () => {
36
+ const issues = [];
37
+
38
+ // Check for lazy-loaded images in viewport
39
+ document.querySelectorAll('img[loading="lazy"]').forEach(img => {
40
+ const rect = img.getBoundingClientRect();
41
+ if (rect.top < window.innerHeight) {
42
+ issues.push({
43
+ issue: 'lazy-loaded image in viewport',
44
+ element: img.outerHTML.substring(0, 200),
45
+ fix: 'Remove loading="lazy" from this image — it is in the initial viewport and may be the LCP element',
46
+ });
47
+ }
48
+ });
49
+
50
+ // Check for LCP-candidate images missing fetchpriority
51
+ document.querySelectorAll('img:not([fetchpriority])').forEach(img => {
52
+ const rect = img.getBoundingClientRect();
53
+ if (rect.top < window.innerHeight && rect.width * rect.height > 50000) {
54
+ issues.push({
55
+ issue: 'large viewport image without fetchpriority',
56
+ element: img.outerHTML.substring(0, 200),
57
+ fix: 'Add fetchpriority="high" to this image — it is large and visible in the initial viewport',
58
+ });
59
+ }
60
+ });
61
+
62
+ // Check for render-blocking scripts in head
63
+ document
64
+ .querySelectorAll(
65
+ 'head script:not([async]):not([defer]):not([type="module"])',
66
+ )
67
+ .forEach(script => {
68
+ if (script.src) {
69
+ issues.push({
70
+ issue: 'render-blocking script in head',
71
+ element: script.outerHTML.substring(0, 200),
72
+ fix: 'Add async or defer attribute, or move to end of body',
73
+ });
74
+ }
75
+ });
76
+
77
+ return {issueCount: issues.length, issues};
78
+ };
79
+ ```
@@ -0,0 +1,38 @@
1
+ # LCP Optimization Strategies
2
+
3
+ ## 1. Eliminate Resource Load Delay
4
+
5
+ **Goal**: Ensure the LCP resource starts loading as early as possible.
6
+
7
+ - **Early Discovery**: Ensure the LCP resource is discoverable in the initial HTML document response (not dynamically added by JS or hidden in `data-src`).
8
+ - **Preload**: Use `<link rel="preload">` with `fetchpriority="high"` for critical images or fonts.
9
+ - **Avoid Lazy Loading**: Never set `loading="lazy"` on the LCP image.
10
+ - **Fetch Priority**: Use `fetchpriority="high"` on the `<img>` tag.
11
+ - **Same Origin**: Host critical resources on the same origin or use `<link rel="preconnect">`.
12
+
13
+ ## 2. Eliminate Element Render Delay
14
+
15
+ **Goal**: Ensure the LCP element can render immediately after its resource has finished loading.
16
+
17
+ - **Minimize Render-Blocking CSS**: Inline critical CSS and defer non-critical CSS. Ensure the stylesheet is smaller than the LCP resource.
18
+ - **Minimize Render-Blocking JS**: Avoid synchronous scripts in the `<head>`. Inline very small scripts.
19
+ - **Server-Side Rendering (SSR)**: Deliver the full HTML markup from the server so image resources are discoverable immediately.
20
+ - **Break Up Long Tasks**: Prevent large JavaScript tasks from blocking the main thread during rendering.
21
+
22
+ ## 3. Reduce Resource Load Duration
23
+
24
+ **Goal**: Reduce the time spent transferring the bytes of the resource.
25
+
26
+ - **Optimize Resource Size**: Serve optimal image sizes, use modern formats (AVIF, WebP), and compress images/fonts.
27
+ - **Geographic Proximity (CDN)**: Use a Content Delivery Network to get servers closer to users.
28
+ - **Reduce Contention**: Use `fetchpriority="high"` to prevent lower-priority resources from competing for bandwidth.
29
+ - **Caching**: Use efficient `Cache-Control` policies.
30
+
31
+ ## 4. Reduce Time to First Byte (TTFB)
32
+
33
+ **Goal**: Deliver the initial HTML as quickly as possible.
34
+
35
+ - **Minimize Redirects**: Avoid multiple redirects from advertisements or shortened links.
36
+ - **CDN Caching**: Cache static HTML documents at the edge.
37
+ - **Edge Computing**: Move dynamic logic to the edge to avoid trips to the origin server.
38
+ - **Back/Forward Cache**: Ensure pages are eligible for bfcache.
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: memory-leak-debugging
3
+ description: Diagnoses and resolves memory leaks in JavaScript/Node.js applications. Use when a user reports high memory usage, OOM errors, or wants to analyze heapsnapshots or run memory leak detection tools like memlab.
4
+ ---
5
+
6
+ # Memory Leak Debugging
7
+
8
+ This skill provides expert guidance and workflows for finding, diagnosing, and fixing memory leaks in JavaScript and Node.js applications.
9
+
10
+ ## Core Principles
11
+
12
+ - **Prefer `memlab`:** Do NOT attempt to read raw `.heapsnapshot` files directly, as they are extremely large and will consume too many tokens. Always recommend and use `memlab` to process snapshots and identify leak traces.
13
+ - **Isolate the Leak:** Determine if the leak is in the browser (client-side) or Node.js (server-side).
14
+ - **Common Culprits:** Look for detached DOM nodes, unhandled closures, global variables, event listeners not being removed, and caches growing unbounded. _Note: Detached DOM nodes are sometimes intentional caches; always ask the user before nulling them._
15
+
16
+ ## Workflows
17
+
18
+ ### 1. Capturing Snapshots
19
+
20
+ When investigating a frontend web application memory leak, utilize the `chrome-devtools-mcp` tools to interact with the application and take snapshots.
21
+
22
+ - Use tools like `click`, `navigate_page`, `fill`, etc., to manipulate the page into the desired state.
23
+ - Revert the page back to the original state after interactions to see if memory is released.
24
+ - Repeat the same user interactions 10 times to amplify the leak.
25
+ - Use `take_heapsnapshot` to save `.heapsnapshot` files to disk at baseline, target (after actions), and final (after reverting actions) states.
26
+
27
+ ### 2. Using Memlab to Find Leaks (Recommended)
28
+
29
+ Once you have generated `.heapsnapshot` files using `take_heapsnapshot`, use `memlab` to automatically find memory leaks.
30
+
31
+ - Read [references/memlab.md](references/memlab.md) for how to use `memlab` to analyze the generated heapsnapshots.
32
+ - Do **not** read raw `.heapsnapshot` files using `read_file` or `cat`.
33
+
34
+ ### 3. Identifying Common Leaks
35
+
36
+ When you have found a leak trace (e.g., via `memlab` output), you must identify the root cause in the code.
37
+
38
+ - Read [references/common-leaks.md](references/common-leaks.md) for examples of common memory leaks and how to fix them.
39
+
40
+ ### 4. Fallback: Comparing Snapshots Manually
41
+
42
+ If `memlab` is not available, you MUST use the fallback script in the references directory to compare two `.heapsnapshot` files and identify the top growing objects and common leak types.
43
+
44
+ Run the script using Node.js:
45
+
46
+ ```bash
47
+ node skills/memory-leak-debugging/references/compare_snapshots.js <baseline.heapsnapshot> <target.heapsnapshot>
48
+ ```
49
+
50
+ The script will analyze and output the top growing objects by size and highlight the 3 most common types of memory leaks (e.g., Detached DOM nodes, closures, Contexts) if they are present.
@@ -0,0 +1,33 @@
1
+ # Common Memory Leaks
2
+
3
+ When analyzing a retainer trace from `memlab`, look for these common patterns in the codebase:
4
+
5
+ ## 1. Uncleared Event Listeners
6
+
7
+ Event listeners attached to global objects (like `window` or `document`) or long-living objects prevent garbage collection of the objects referenced in their callbacks.
8
+
9
+ **Fix:** Always call `removeEventListener` when a component unmounts or the listener is no longer needed.
10
+
11
+ ## 2. Detached DOM Nodes
12
+
13
+ A DOM node is removed from the document tree but is still referenced by a JavaScript variable. While detachedness is a good signal for a memory leak, it's not always a bug. For example, websites sometimes intentionally cache detached navigation trees.
14
+
15
+ **Fix:** Signal the detached nodes to the user first. **Ask the user first** before nulling the references or changing the code, as the detached nodes might be part of an intentional cache. If confirmed as a leak, ensure variables holding DOM references are set to `null` when the node is removed, or limit their scope.
16
+
17
+ ## 3. Unintentional Global Variables
18
+
19
+ Variables declared without `var`, `let`, or `const` (in non-strict mode) or explicitly attached to `window` remain in memory forever.
20
+
21
+ **Fix:** Use strict mode, properly declare variables, and avoid global state.
22
+
23
+ ## 4. Closures
24
+
25
+ Closures can unintentionally keep references to large objects in their outer scope.
26
+
27
+ **Fix:** Nullify large objects when they are no longer needed, or refactor the closure to not capture unnecessary variables.
28
+
29
+ ## 5. Unbounded Caches or Arrays
30
+
31
+ Data structures used for caching (like objects, Arrays, or Maps) that grow without limits.
32
+
33
+ **Fix:** Implement caching limits, use LRU caches, or use `WeakMap`/`WeakSet` for data associated with object lifecycles.