DEV Community

Cover image for Using AI and Chrome MCP to Automate Core Web Vitals
Mariano Álvarez 🇨🇷
Mariano Álvarez 🇨🇷

Posted on

Using AI and Chrome MCP to Automate Core Web Vitals

One of the hardest and most tiring parts of working on web performance is the number of edge cases you need to consider. Some optimizations are purely code-related, while others require running real tests and analyzing the results.

The main challenge is keeping all of this in mind at the same time. This becomes even harder when you work with a team, where not everyone has the same level of experience or knowledge of performance best practices.

This is a great use case for AI. You can introduce a step where an LLM runs performance tests, uses ChromeMCP, executes the latest checks, gathers the results, and summarizes them in a way that works for your workflow.

The key piece here is ChromeMCP, which provides a wide range of functions that allow an LLM to access a page, interact with it, and run Chrome DevTools programmatically.

Prompts

The following two prompts are designed to gather performance data and then apply fixes based on what was found.

Get Core Web Vitals report

This prompt generates a Core Web Vitals report for a specific URL. It performs the following steps:

  1. Navigate to the URL
  2. Change the network to Slow 4G
  3. Start a performance trace
  4. Take a screenshot of the page
  5. Click interactive elements to test INP
  6. Analyze the results
  7. Generate the report and close the page

The report is stored in the /reports directory along with the screenshot.

# Core Web Vitals Performance Test

Test the page at `<url>` and generate a Core Web Vitals report.

## Instructions

1. **Navigate to the page:**
   - Use `mcp__chrome-devtools__new_page` or `mcp__chrome-devtools__navigate_page` to go to `<url>`

2. **Apply network throttling:**
   - Use `mcp__chrome-devtools__emulate_network` with "Slow 4G" throttling to simulate real-world conditions

3. **Run performance trace:**
   - Use `mcp__chrome-devtools__performance_start_trace` with `reload: true` and `autoStop: true`
   - This will measure LCP, CLS, and other performance metrics

4. **Take a screenshot:**
   - Use `mcp__chrome-devtools__take_screenshot` with `fullPage: true` to capture the page
   - Save it to the `reports/` folder using the `filePath` parameter
   - Name it using the pattern: `screenshot-{domain}-{timestamp}.png`

5. **Test interactions (for INP):**
   - Use `mcp__chrome-devtools__take_snapshot` to identify interactive elements
   - Click on buttons/links using `mcp__chrome-devtools__click` to test interaction responsiveness

6. **Analyze results:**
   - Review the performance trace data
   - Identify LCP, CLS, INP scores
   - Look for performance insights and warnings

7. **Generate report:**
   - Create a markdown file in the `reports/` folder
   - Name it using the pattern: `core-vitals-{domain}-{timestamp}.md`
   - Include all findings, metrics, and actionable recommendations

8. **Clean up:**
   - Use `mcp__chrome-devtools__close_page` to close the browser tab after testing is complete
   - This ensures proper cleanup and prevents memory leaks

## Report Format

The report should be concise and easy to read, including:

- **Test Conditions**: Network throttling, URL tested
- **Core Web Vitals Scores**: LCP, CLS, INP with brief breakdowns
- **Additional Performance Insights**: Key findings from Chrome DevTools
- **Critical Problems Summary**: Top issues prioritized
- **Optimization Opportunities**: High-impact and medium-impact recommendations with estimated improvements

Keep the report focused and actionable. Avoid excessive detail or lengthy code examples.

---

## Example Report

# 🔴 Core Web Vitals Report: /products Page

**Test Conditions:**
- Network: Slow 4G throttling
- URL: https://example.com/products
- Test Date: 2025-01-29 10:30:00 UTC

---

## Core Web Vitals Scores

### 1. LCP (Largest Contentful Paint): 3,245ms 🔴

**Status:** Poor (Target: < 2,500ms for "Good")

**LCP Element:** Hero banner image

**Breakdown:**
- TTFB (Time to First Byte): 850ms ⚠️
- Load Delay: 1,200ms 🔴 (37% of LCP - time before image starts loading)
- Load Duration: 450ms ⚠️ (actual download time)
- Render Delay: 745ms ⚠️ (23% of LCP - time after download before paint)

**Key Issues:**
- Hero image is not discoverable immediately from HTML
- No preload hint for critical image
- Image served at 4MB uncompressed (3000x2000px)
- No modern image format (WebP/AVIF)

---

### 2. CLS (Cumulative Layout Shift): 0.25 🔴

**Status:** Poor (Target: < 0.1)

**Major Shifts:**
1. Hero image load: 0.15 shift (no width/height attributes)
2. Ad insertion: 0.08 shift (dynamic content injection)
3. Web font loading: 0.02 shift (FOUT)

**Key Issues:**
- Images missing explicit dimensions
- Dynamic content inserted without reserved space
- Fonts loaded asynchronously causing text reflow

---

### 3. INP (Interaction to Next Paint): 580ms 🔴

**Tested Interaction:** "Add to Cart" button click

**Status:** Poor (Target: < 200ms)

**Key Issues:**
- Heavy synchronous JavaScript execution on click (450ms)
- Main thread blocked during state update
- No visual feedback during processing
- Long tasks preventing quick response

---

## Additional Performance Insights

### Render Blocking Resources
- 3 CSS files blocking render (total 245KB)
- 2 JavaScript bundles blocking initial paint (total 890KB)
- **Estimated savings:** 1,200ms on LCP

### Network Dependency Chain
- Long chain of sequential resource requests (5 levels deep)
- Hero image depends on CSS → JS → API call

### Third-Party Impact
- Google Analytics: 180ms execution time
- Facebook Pixel: 220ms execution time

---

## Critical Problems Summary

1. **LCP Problem (3,245ms):**
   - 1,200ms load delay + 745ms render delay = 1,945ms of preventable delay
   - Image optimization and preloading are critical

2. **CLS Problem (0.25):**
   - Missing image dimensions causing major layout shifts
   - Dynamic content injection without space reservation

3. **INP Problem (580ms):**
   - Synchronous blocking operation prevents quick interaction response
   - Violates the 200ms INP threshold for good user experience

---

## Optimization Opportunities

### High Impact:
- Convert hero image to WebP/AVIF and compress to < 200KB
- Add `fetchpriority="high"` and preload hint to hero image
- Add explicit width/height to all images
- Use non-blocking state updates for button interactions
- **Estimated LCP improvement:** < 1,500ms (54% faster)
- **Estimated CLS improvement:** < 0.05 (80% better)
- **Estimated INP improvement:** < 180ms (69% faster)

### Medium Impact:
- Implement code splitting for JavaScript bundles
- Defer non-critical third-party scripts
- Reserve space for dynamic content (ads, widgets)
- Optimize font loading strategy
- Enable Brotli/Gzip compression

---

**Report generated:** 2025-01-29 10:30:00 UTC

---

## Usage

Replace `<url>` with the actual URL to test:

Test the page at http://localhost:3000/unoptimized and generate a comprehensive Core Web Vitals report.
Enter fullscreen mode Exit fullscreen mode

Fix the issues found in the report

Once you have the report, you know exactly what needs to be fixed. The prompt below takes the report as part of the context and attempts to apply the recommended improvements.

# Optimize Code for Core Web Vitals

Read the Core Web Vitals report at `<path>` and implement the recommended optimizations to improve performance.

## Instructions

1. **Read the report:**
   - Use the Read tool to load the report file at `<path>`
   - Identify all issues and recommendations
   - Prioritize high-impact optimizations first

2. **Analyze the page:**
   - Identify the files that need to be modified
   - Use Glob and Grep tools to find relevant code
   - Read the current implementation

3. **Implement optimizations:**
   - Start with high-impact fixes (LCP, then CLS, then INP)
   - Make code changes using the Edit tool
   - Add clear comments explaining each optimization
   - Follow the recommendations from the report

4. **Common optimizations to implement:**

   **For LCP Issues:**
   - Convert `<img>` tags to Next.js `Image` component
   - Add `priority={true}` to hero/above-fold images
   - Add explicit `width` and `height` props
   - Set appropriate `quality` (e.g., 75 instead of 100)
   - Add responsive `sizes` attribute

   **For CLS Issues:**
   - Add explicit dimensions to all images
   - Add `aspect-ratio` CSS or container dimensions
   - Reserve space for dynamic content
   - Optimize font loading with `font-display`

   **For INP Issues:**
   - Replace blocking operations with async/non-blocking code
   - Use React's `useTransition` for state updates
   - Add loading states for immediate user feedback
   - Move heavy computations to Web Workers or defer them

   **General Optimizations:**
   - Add lazy loading (`loading="lazy"`) to below-fold images
   - Implement code splitting where appropriate
   - Defer non-critical scripts
   - Add preload hints for critical resources

5. **Document changes:**
   - Create a summary document in `reports/`
   - Name it: `optimization-summary-{timestamp}.md`
   - List all files modified
   - Describe each change made
   - Include expected performance impact

6. **Verify changes:**
   - Ensure no syntax errors were introduced
   - Check that imports are correct
   - Verify that the code follows best practices

## Optimization Guidelines

- **Be precise:** Only modify the code that needs optimization
- **Add comments:** Explain why each optimization was made
- **Follow patterns:** Use existing code style and conventions
- **Test safety:** Don't break existing functionality
- **High impact first:** Prioritize optimizations with the biggest performance gains

## Example Usage

Read the Core Web Vitals report at reports/core-vitals-localhost-1738166400.md and implement the recommended optimizations to improve performance.


---

## Example Optimization Summary

# Core Web Vitals Optimization Summary

**Date:** 2025-01-29 14:30:00 UTC
**Report Used:** reports/core-vitals-example-1738166400.md
**Page Optimized:** /products

---

## Issues Identified from Report

Based on the report analysis, the following high-priority issues were found:

1. **LCP (3,245ms):** Hero image not optimized, no preload hints
2. **CLS (0.25):** Missing image dimensions, dynamic content shifts
3. **INP (580ms):** Blocking JavaScript execution on button click

---

## Changes Made

### 1. LCP Optimization - Hero Image

**File:** `app/products/page.tsx` (lines 45-52)

**Issue from report:**
- Hero image served at 4MB uncompressed
- No preload hint for critical image
- Image not discoverable from HTML immediately

**Changes applied:**
- [Specific changes based on report recommendations]
- [Added necessary props/attributes]
- [Modified relevant code sections]

**Expected Impact:** -1,200ms on LCP

---

### 2. CLS Optimization - Image Dimensions

**File:** `app/products/page.tsx` (lines 78-120)

**Issue from report:**
- Images missing explicit dimensions causing 0.15 shift
- Dynamic ad insertion causing 0.08 shift

**Changes applied:**
- [Specific changes based on report recommendations]
- [Added dimension specifications]
- [Reserved space for dynamic content]

**Expected Impact:** -0.23 CLS (from 0.25 to 0.02)

---

### 3. INP Optimization - Button Interactions

**File:** `app/products/page.tsx` (lines 156-168)

**Issue from report:**
- Heavy synchronous JavaScript execution (450ms)
- Main thread blocked during state update

**Changes applied:**
- [Specific changes based on report recommendations]
- [Refactored blocking code]
- [Added non-blocking patterns]

**Expected Impact:** -400ms on INP (from 580ms to ~180ms)

---

## Files Modified

- `app/products/page.tsx` - Optimized images and interactions
- [Additional files if needed]

---

## Expected Performance Results

### Before Optimization (from report):
- LCP: 3,245ms 🔴
- CLS: 0.25 🔴
- INP: 580ms 🔴

### After Optimization (estimated):
- LCP: ~2,045ms ⚠️ (37% improvement)
- CLS: ~0.02 ✅ (92% improvement)
- INP: ~180ms ✅ (69% improvement)

**Note:** Run a new performance test to verify actual improvements.

---

**Optimization completed:** 2025-01-29 14:30:00 UTC

---

## Important Notes

- Always read the entire report before making changes
- Focus on high-impact optimizations first (those with largest expected improvements)
- Test after each major change to ensure nothing broke
- Keep the original unoptimized version for comparison
- Add detailed comments to explain each optimization
- If the report mentions issues that don't apply to the current code, skip them
- Don't over-optimize - focus on the specific issues identified in the report
Enter fullscreen mode Exit fullscreen mode

Tips and ideas to improve your development flow

These prompts can be used with any AI tool such as GeminiCLI, Claude Code, Cursor, or Antigravity. You will need to adapt and tweak them depending on the tool and setup you are using.

Some ideas:

  • Create custom slash commands in GeminiCLI and pass the URL directly, for example: @test-core-vitals url:/products

  • Create a sub-agent in Claude Code and call it in a similar way. The AI is smart enough to understand that url is a variable and replace it in the context.

  • Add a Git hook that triggers these prompts automatically to detect performance issues and apply fixes early.

The optimization prompt is focused on React applications, but it can be adapted to any framework. For Angular projects, you can combine this approach with the Angular MCP to get better and more consistent results.


If you want to see more of my content, follow me on LinkedIn.

Don't forget to like and share ❤️

Top comments (0)