# Script Return Value Schema All scripts in the skills directory must return a structured JSON object as the IIFE return value. This allows agents using `mcp__chrome-devtools__evaluate_script` to read structured data directly from the return value, rather than parsing human-readable console output. ## Why this matters The console output of a snippet (with `%c` CSS styling, emojis, tables) is meant for humans reading DevTools. The return value is meant for agents. The scripts in the skills are built without console calls, so the return value of `evaluate_script` is the only output an agent gets. ``` // Agent workflow result = evaluate_script(scriptCode) // return value → structured JSON for the agent ``` --- ## Base Shape Every script must return an object matching this shape: ```typescript { // Required in all scripts script: string; // Script name, e.g. "LCP", "TTFB", "Script-Loading" status: "ok" // Script ran, has data | "tracking" // Observer active, data accumulates over time | "error" // Failed or no data available | "unsupported"; // Browser API not supported // Metric scripts (LCP, CLS, INP, TTFB, FCP) metric?: string; // Short metric name: "LCP", "CLS", "INP", "TTFB", "FCP" value?: number; // Always a number, never a formatted string unit?: "ms" // Milliseconds | "score" // Unitless score (CLS) | "count" // Integer count | "bytes" // Raw bytes | "bpp" // Bits per pixel | "fps"; // Frames per second rating?: "good" | "needs-improvement" | "poor"; thresholds?: { good: number; // Upper bound for "good" needsImprovement: number; // Upper bound for "needs-improvement" }; // Audit/inspection scripts (render-blocking, images, scripts) count?: number; // Total number of items found items?: object[]; // Array of individual findings // Audit scripts that read resource sizes or timings hidden by Timing-Allow-Origin corsLimitedAnalysis?: boolean; // true when at least one cross-origin resource could not be analyzed; the result is a lower bound // Script-specific structured data details?: object; // Issues detected (for audit scripts) issues?: Array<{ code: string; // What the issue is, kebab-case, stable across runs and versions (see Issue codes) severity: "error" | "warning" | "info"; message: string; target?: string; // The URL, selector or name the issue is about, when there is one issue per thing }>; // Next steps in plain text, most important first, without emoji (Cache-Strategy-Analysis) recommendations?: string[]; // Tracking scripts (status: "tracking") message?: string; // Human-readable status message getDataFn?: string; // window function to call for data: evaluate_script(`() => ${getDataFn}()`). May be a dotted path such as "loafHelpers.getData" // Error info (status: "error" or "unsupported") error?: string; } ``` A field named `selector`, `element` or `finalElement`, at any level, is a CSS selector that matches only its element in the document, so `document.querySelector()` returns that element and no other: the id when it is unique, otherwise a path of tag, classes and `:nth-of-type()` up to the nearest ancestor with a unique id, such as `div.carousel-item:nth-of-type(8) > img`. A selector of an element inside a shadow root marks the boundary with `>>>` or ends in `(shadow root)`, and cannot be read from the document. `cli/tests/e2e/snippet-contract.test.js` checks it on its pages. --- ## Execution Patterns ### Pattern 1: Fully synchronous Scripts that read DOM or `performance.getEntriesByType()` directly. Return JSON at the end of the IIFE. ```js // Example: TTFB.js (() => { const [nav] = performance.getEntriesByType("navigation"); if (!nav) return { script: "TTFB", status: "error", error: "No navigation entry" }; const value = Math.round(nav.responseStart); const rating = value <= 800 ? "good" : value <= 1800 ? "needs-improvement" : "poor"; // Human output console.log(`TTFB: ${value}ms (${rating})`); // Agent output return { script: "TTFB", status: "ok", metric: "TTFB", value, unit: "ms", rating, thresholds: { good: 800, needsImprovement: 1800 }, }; })(); ``` **Scripts using this pattern:** TTFB, TTFB-Sub-Parts, FCP, Find-render-blocking-resources, Script-Loading, LCP-Video-Candidate, Resource-Hints, Resource-Hints-Validation, Priority-Hints-Audit, Validate-Preload-Async-Defer-Scripts, Fonts-Preloaded, Service-Worker-Analysis, Back-Forward-Cache, Content-Visibility, Critical-CSS-Detection, Inline-CSS-Info-and-Size, Inline-Script-Info-and-Size, First-And-Third-Party-Script-Info, First-And-Third-Party-Script-Timings, Compression-Audit, Third-Party-Impact-by-Domain, JS-Execution-Time-Breakdown, CSS-Media-Queries-Analysis, Client-Side-Redirect-Detection, SSR-Hydration-Data-Analysis, Network-Bandwidth-Connection-Quality, Find-Above-The-Fold-Lazy-Loaded-Images, Find-Images-With-Lazy-and-Fetchpriority, Find-non-Lazy-Loaded-Images-outside-of-the-viewport, SVG-Embedded-Bitmap-Analysis, Prefetch-Resource-Validation, TTFB-Resources. ### Pattern 2: Buffered observer Chrome exposes some entry types only through a `PerformanceObserver`: `largest-contentful-paint`, `layout-shift`, `longtask`, `event` and `first-input`. `performance.getEntriesByType()` returns `[]` for them, so a synchronous read gives an empty result. Collect them with a buffered observer and wait briefly for it to deliver, which makes the script async (Pattern 4). Entry types that `getEntriesByType()` does return can be read synchronously: `navigation`, `resource`, `paint`, `mark`, `measure` and `long-animation-frame`. ```js // Example: LCP.js (async () => { if (!PerformanceObserver.supportedEntryTypes?.includes("largest-contentful-paint")) { return { script: "LCP", status: "unsupported", error: "largest-contentful-paint entries not supported in this browser" }; } // Collect buffered entries; 100ms lets the observer process them on busy pages const lastEntry = await new Promise((resolve) => { const entries = []; const obs = new PerformanceObserver((list) => entries.push(...list.getEntries())); obs.observe({ type: "largest-contentful-paint", buffered: true }); setTimeout(() => { obs.disconnect(); resolve(entries.at(-1) ?? null); }, 100); }); if (!lastEntry) return { script: "LCP", status: "error", error: "No LCP entries yet" }; const activationStart = performance.getEntriesByType("navigation")[0]?.activationStart ?? 0; const value = Math.round(Math.max(0, lastEntry.startTime - activationStart)); const rating = value <= 2500 ? "good" : value <= 4000 ? "needs-improvement" : "poor"; return { script: "LCP", status: "ok", metric: "LCP", value, unit: "ms", rating, thresholds: { good: 2500, needsImprovement: 4000 }, details: { element: selector, elementType: type, url: lastEntry.url, sizePixels: lastEntry.size } }; })(); ``` Always check `PerformanceObserver.supportedEntryTypes` first. On browsers without the entry type a script must return `status: "unsupported"`, not a value that looks like a passing result. A tracking script also defines its `getDataFn`, which returns the same `unsupported` object. When only part of the result depends on an API, the script still runs: it sets a `details.Supported` flag to `false` and reports the fields that depend on the API as `null`, never as `0` or `false`. `loafSupported` (Long Animation Frames) and `renderBlockingSupported` (`renderBlockingStatus` in Resource Timing, Chromium only) follow this rule. The repository enforces this with an ESLint rule (`no-restricted-syntax` in `eslint.config.mjs`) that rejects `getEntriesByType()` for the observer-only types. **Scripts using this pattern:** LCP, CLS, LCP-Subparts, LCP-Trail, LCP-Image-Entropy, LongTask, Layout-Shift-Loading-and-Interaction. ### Pattern 3: Tracking observers Scripts that observe ongoing user interactions cannot return meaningful data synchronously. They return `status: "tracking"` immediately, and expose a `window.getXxx()` function for agents to call later. ```js // Return at the end of the IIFE: return { script: "INP", status: "tracking", message: "INP tracking active. Interact with the page then call getINP() for results.", getDataFn: "getINP", }; ``` **Agent workflow for tracking scripts:** ``` 1. evaluate_script(INP.js) → { status: "tracking", getDataFn: "getINP" } 2. (user interacts with the page) 3. evaluate_script("() => getINP()") → { script: "INP", status: "ok", value: 350, rating: "needs-improvement", ... } ``` **The window function must also return a structured object** matching the same schema, including when nothing has been recorded yet: - `status: "ok"` with `count: 0` when zero is a valid result (no long tasks, no long animation frames). - `status: "tracking"` with a `message` and its `getDataFn` when there is nothing to report yet and someone has to act first (no interactions recorded): nothing failed, the snippet is still recording. `status: "error"` is for a snippet that failed. **Scripts using this pattern:** INP, Interactions, Input-Latency-Breakdown, Layout-Shift-Loading-and-Interaction, Scroll-Performance, Long-Animation-Frames (ongoing tracking), LongTask (ongoing tracking), Long-Animation-Frames-Script-Attribution. ### Pattern 4: Async scripts Scripts that use `async/await` or `setTimeout`. The IIFE returns a Promise, which `evaluate_script` awaits with `format: "script"` (Chrome DevTools `awaitPromise`). Keep the existing `async () => {}` wrapper. Add a `return` statement with structured data at the end. The agent receives the resolved value. A script wrapped in `void (async () => {...})()` discards its return value. Never use `void` on the IIFE. **Scripts using this pattern:** Image-Element-Audit (fetches content-type headers), Video-Element-Audit, SVG-Embedded-Bitmap-Analysis, Service-Worker-Analysis, and every script that collects observer-only entry types (Pattern 2). --- ## Script-Specific Schemas ### Core Web Vitals #### LCP ```json { "script": "LCP", "status": "ok", "metric": "LCP", "value": 1240, "unit": "ms", "rating": "good", "thresholds": { "good": 2500, "needsImprovement": 4000 }, "details": { "element": "img.hero", "elementType": "Image", "url": "https://example.com/hero.jpg", "sizePixels": 756000 } } ``` `details.element` is a CSS selector that matches only the LCP element, so `document.querySelector(details.element)` returns it: the id when it is unique, otherwise a path of tag, classes and `:nth-of-type()` from the nearest ancestor with a unique id, such as `section.intro:nth-of-type(2) > p.copy:nth-of-type(2)`. LCP-Subparts (`details.element`) and LCP-Trail (`finalElement` and each `selector`) build it the same way. In LCP-Trail, a candidate whose element has left the DOM has `selector: null` and `removed: true`, with its `time`, `sizePixels`, `url` for an image and `id` when the element had one, and `finalElement` is `null` when the LCP element itself was removed. `value` is the time of the last entry either way. #### CLS Returns buffered CLS immediately and keeps tracking. Always call `getCLS()` after interactions to get an updated value. ```json { "script": "CLS", "status": "ok", "metric": "CLS", "value": 0.05, "unit": "score", "rating": "good", "thresholds": { "good": 0.1, "needsImprovement": 0.25 }, "message": "CLS tracking active. Call getCLS() for updated value after page interactions.", "getDataFn": "getCLS" } ``` `getCLS()` returns the same shape with the latest accumulated value. #### INP (tracking) ```json { "script": "INP", "status": "tracking", "message": "INP tracking active. Interact with the page then call getINP() for results.", "getDataFn": "getINP" } ``` `getINP()` returns: ```json { "script": "INP", "status": "ok", "metric": "INP", "value": 350, "unit": "ms", "rating": "needs-improvement", "thresholds": { "good": 200, "needsImprovement": 500 }, "details": { "totalInteractions": 5, "worstEvent": "click -> button.submit", "phases": { "inputDelay": 120, "processingTime": 180, "presentationDelay": 50 } } } ``` If no interactions yet, `getINP()` returns `status: "tracking"` with a `message` and `getDataFn: "getINP"`: interact with the page and call it again. An interaction that paints nothing has no frame to be measured to, so the browser measures it to the end of its handlers, often 0 ms, and gives no `event` entry under 16 ms at any `durationThreshold`. The first interaction of a page always has a `first-input` entry, which is how web-vitals reads it too, so `getINP()` returns it as `status: "ok"` with its value, and an `info` issue when the worst value is under 16 ms: ```json { "script": "INP", "status": "ok", "metric": "INP", "value": 0, "unit": "ms", "rating": "good", "thresholds": { "good": 200, "needsImprovement": 500 }, "details": { "totalInteractions": 1, "worstEvent": "pointerdown → h1", "phases": { "inputDelay": 0, "processingTime": 0, "presentationDelay": 0 } }, "issues": [{ "code": "no-paint-measured", "severity": "info", "message": "Worst interaction: 0 ms, under the 16 ms of a frame, so the page most likely painted nothing after it. If it should respond, check that the click or key press reaches an element that does." }] } ``` Later interactions that short have no entry of any kind: they only count in `performance.interactionCount`, and INP does not depend on them. `tracking` after a click means that the document recorded no interaction at all, as with a click inside an iframe, which records its own; the CLI and the MCP server turn that result into `status: "error"`, with an `error` that says a click or key press was sent, so the CLI exits with code `1`. The phases describe the whole interaction, not one of its events. A tap fires `pointerdown`, `pointerup` and `click`, and a key press `keydown` and `keyup`, with one `interactionId`. INP, Interactions and Input-Latency-Breakdown group the entries by `interactionId`, also when they arrive in separate observer callbacks, and measure the interaction over its entries painted in the frame of the longest one: `inputDelay` runs from the first `startTime` to the first `processingStart`, `processingTime` to the last `processingEnd`, and `presentationDelay` from there to the paint (`startTime + duration`, never below zero). The interaction is reported under the event whose handler ran longest, or under the `click` or `keydown` when no handler took a millisecond more than theirs; `worstEvent`, the Interactions `type` and the Input-Latency-Breakdown event type follow that rule. `getINPDetails()` returns the 15 slowest interactions, slowest first, with the total in `count`. `target` is a CSS selector built like `details.element` of LCP, or `null` when the browser reports no target. Use it when `getINP()` shows poor INP and you need to identify patterns across multiple slow interactions. With no interactions yet it returns `status: "tracking"`, a `message`, `count: 0` and no items. ```json { "script": "INP", "status": "ok", "count": 23, "items": [ { "formattedName": "click → button.submit", "eventType": "click", "target": "#checkout > button.submit", "duration": 450, "startTime": 1200, "phases": { "inputDelay": 120, "processingTime": 280, "presentationDelay": 50 } } ] } ``` #### LCP-Subparts ```json { "script": "LCP-Subparts", "status": "ok", "metric": "LCP", "value": 2100, "unit": "ms", "rating": "needs-improvement", "thresholds": { "good": 2500, "needsImprovement": 4000 }, "details": { "element": "img.hero", "url": "hero.jpg", "subParts": { "ttfb": { "value": 450, "percent": 21, "overTarget": false }, "resourceLoadDelay": { "value": 120, "percent": 6, "overTarget": false }, "resourceLoadTime": { "value": 1200, "percent": 57, "overTarget": true, "waiting": 1040, "download": 160 }, "elementRenderDelay": { "value": 330, "percent": 16, "overTarget": true } }, "slowestPhase": "resourceLoadTime" } } ``` `resourceLoadTime.waiting` is the time until the first byte of the response of the LCP resource, and `resourceLoadTime.download` the time to download its body. Both are missing when Resource Timing hides that timing (another origin without `Timing-Allow-Origin`). #### LCP-Trail ```json { "script": "LCP-Trail", "status": "ok", "metric": "LCP", "value": 1240, "unit": "ms", "rating": "good", "thresholds": { "good": 2500, "needsImprovement": 4000 }, "details": { "candidateCount": 2, "finalElement": "img.hero", "candidates": [ { "index": 1, "selector": "h1", "time": 800, "elementType": "Text block" }, { "index": 2, "selector": "img.hero", "time": 1240, "elementType": "Image", "url": "hero.jpg" } ] } } ``` #### LCP-Image-Entropy `items` holds the 50 most relevant images: the LCP image first, then the low-entropy ones, then the lowest bits per pixel. `count` and `details` cover every image. `bpp` follows Chrome's rule: the encoded size in bits over the displayed area in CSS pixels (`displayedWidth` × `displayedHeight`), or over the natural area (`width` × `height`) when the image is upscaled. An image that is not rendered has no displayed area and is left out. ```json { "script": "LCP-Image-Entropy", "status": "ok", "count": 5, "details": { "totalImages": 5, "lowEntropyCount": 1, "lcpImageEligible": true, "lcpImage": { "url": "hero.jpg", "bpp": 1.65, "isLowEntropy": false } }, "items": [ { "url": "hero.jpg", "width": 1200, "height": 630, "displayedWidth": 1200, "displayedHeight": 630, "fileSizeBytes": 156000, "bpp": 1.65, "isLowEntropy": false, "lcpEligible": true, "isLCP": true } ], "issues": [] } ``` #### LCP-Video-Candidate ```json { "script": "LCP-Video-Candidate", "status": "ok", "metric": "LCP", "value": 1800, "unit": "ms", "rating": "good", "thresholds": { "good": 2500, "needsImprovement": 4000 }, "details": { "isVideo": true, "posterUrl": "https://example.com/hero.avif", "posterFormat": "avif", "posterPreloaded": true, "fetchpriorityOnPreload": "high", "isCrossOrigin": false, "videoAttributes": { "autoplay": true, "muted": true, "playsinline": true, "preload": "auto" } }, "issues": [] } ``` ### Loading #### TTFB ```json { "script": "TTFB", "status": "ok", "metric": "TTFB", "value": 245, "unit": "ms", "rating": "good", "thresholds": { "good": 800, "needsImprovement": 1800 } } ``` #### TTFB-Sub-Parts ```json { "script": "TTFB-Sub-Parts", "status": "ok", "metric": "TTFB", "value": 245, "unit": "ms", "rating": "good", "thresholds": { "good": 800, "needsImprovement": 1800 }, "details": { "subParts": { "redirectWait": { "value": 0, "unit": "ms" }, "serviceWorkerCache": { "value": 0, "unit": "ms" }, "dnsLookup": { "value": 5, "unit": "ms" }, "tcpConnection": { "value": 30, "unit": "ms" }, "sslTls": { "value": 45, "unit": "ms" }, "serverResponse": { "value": 165, "unit": "ms" } }, "slowestPhase": "serverResponse" }, "issues": [] } ``` When the rating is not good, `issues` holds one entry that names the TTFB and the slowest phase, a `warning` for `needs-improvement` and an `error` for `poor`: ```json { "issues": [{ "severity": "warning", "message": "TTFB is 996 ms (needs-improvement); server response takes 993 ms of it (100%). Fix: optimize server processing, cache the HTML and check slow queries." }] } ``` #### Find-render-blocking-resources ```json { "script": "Find-render-blocking-resources", "status": "ok", "count": 3, "details": { "totalBlockingUntilMs": 450, "totalSizeBytes": 135000, "byType": { "link": 2, "script": 1 } }, "items": [ { "type": "link", "url": "https://example.com/style.css", "shortName": "style.css", "responseEndMs": 450, "durationMs": 200, "sizeBytes": 45000 } ] } ``` #### Script-Loading `items` holds the 50 scripts to look at first: render-blocking, then third-party, then the largest. `count` and `details` cover every script. `corsLimitedAnalysis` is `true` when `details.sizeUnknownCount` is above zero, so `details.totalSizeBytes` is a lower bound. A classic script with `nomodule` has the strategy `nomodule` and is never blocking: a browser that supports modules does not fetch it, so its size is known (0 bytes). ```json { "script": "Script-Loading", "status": "ok", "count": 8, "rating": "needs-improvement", "details": { "totalSizeBytes": 245000, "sizeUnknownCount": 0, "byStrategy": { "blocking": 2, "async": 4, "defer": 1, "module": 1, "nomodule": 0 }, "byParty": { "firstParty": 5, "thirdParty": 3 }, "thirdPartyBlockingCount": 1 }, "items": [ { "url": "https://example.com/app.js", "shortName": "app.js", "strategy": "blocking", "location": "head", "party": "first", "sizeBytes": 85000, "sizeKnown": true, "durationMs": 120 } ], "issues": [ { "code": "blocking-in-head", "severity": "error", "message": "2 blocking script(s) in " }, { "code": "third-party-blocking", "severity": "error", "message": "1 third-party blocking script(s)" } ] } ``` #### Compression-Audit Synchronous. `count` is the number of uncompressed text resources; `items` holds the 50 with the largest estimated savings, while `details` totals the whole set. A cross-origin resource without `Timing-Allow-Origin` reports zero for every size, so it is counted in `sizeUnknownCount` (left out of `items`) and `corsLimitedAnalysis` is `true`. Resources under 1 KB are counted in `skippedSmallCount`, so the counts add up to `totalTextResources`. `estimatedSavingsBytes` applies a typical gzip/brotli reduction (70% for JS, CSS, HTML, JSON, SVG and XML; 50% for TTF/OTF), so it is an estimate. ```json { "script": "Compression-Audit", "status": "ok", "count": 1, "corsLimitedAnalysis": true, "details": { "totalTextResources": 6, "compressedCount": 4, "uncompressedCount": 1, "sizeUnknownCount": 1, "skippedSmallCount": 0, "totalUncompressedBytes": 61440, "estimatedSavingsBytes": 43008, "byEncoding": { "br": 3, "gzip": 1, "none": 1 }, "contentEncodingSupported": true }, "items": [ { "url": "https://example.com/app.css", "shortName": "app.css", "type": "css", "encoding": "none", "encodedBytes": 61440, "decodedBytes": 61440, "estimatedSavingsBytes": 43008 } ], "issues": [ { "severity": "warning", "message": "1 text resource(s) served without compression; enabling gzip or brotli could save about 42.0 KB" }, { "severity": "info", "message": "1 cross-origin text resource(s) without Timing-Allow-Origin report zero sizes, so their compression is unknown" } ] } ``` #### Third-Party-Impact-by-Domain Synchronous. `count` is the number of third-party root domains; `items` holds the 50 to look at first (render-blocking, then the most main-thread time, then the largest transfer), while `details` totals every domain. `loafMs` is the script time attributed to the domain in `long-animation-frame` entries (sum of `scripts[].duration` by `sourceURL`), or `null` for every item when `details.loafSupported` is `false`. `details.longFrames` counts the long animation frames on the page and `details.unattributedLoafMs` is the time in them that no third-party script accounts for (first-party scripts, scripts under the 5 ms that the API lists, and style, layout and rendering work); both are `null` when `loafSupported` is `false`. `details.renderBlockingSupported` is `false` in browsers without `renderBlockingStatus` (only Chromium has it); then `renderBlocking` is `null` for every item, `details.blockingDomains` is `null` and an `info` issue says so. A cross-origin request without `Timing-Allow-Origin` reports zero for every size, so it is counted in `sizeUnknownCount` (per domain and in `details`), left out of the byte totals, and `corsLimitedAnalysis` is `true`. ```json { "script": "Third-Party-Impact-by-Domain", "status": "ok", "count": 2, "corsLimitedAnalysis": true, "details": { "thirdPartyRequests": 3, "thirdPartyBytes": 5120, "thirdPartyLoafMs": 128, "longFrames": 2, "unattributedLoafMs": 74, "firstPartyRequests": 1, "blockingDomains": 1, "renderBlockingSupported": true, "loafSupported": true, "sizeUnknownCount": 1 }, "items": [ { "domain": "tagmanager.example", "requests": 2, "transferBytes": 5120, "sizeUnknownCount": 0, "renderBlocking": true, "loafMs": 128, "loafScripts": 1 }, { "domain": "metrics.example", "requests": 1, "transferBytes": 0, "sizeUnknownCount": 1, "renderBlocking": false, "loafMs": 0, "loafScripts": 0 } ], "issues": [ { "severity": "warning", "message": "1 third-party domain(s) serve render-blocking resources (tagmanager.example); load them async or defer, or self-host them" }, { "severity": "info", "message": "1 third-party request(s) without Timing-Allow-Origin report zero sizes, so the transfer size is a lower bound" } ] } ``` #### First-And-Third-Party-Script-Info Synchronous. A script is a resource with `initiatorType` `script`, or one whose URL matches a `