给 Agent 接上 Chrome DevTools:报错它全抓到了,CLS 的锅却甩错了人

我故意写了个满是坑的订单看板:一个 500,一个跨域失败,一个卡住渲染 1.5 秒的脚本,一个占着主线程 700 毫秒的长任务,再加一个晚到的横幅把内容顶下去。然后我把 chrome-devtools-mcp 接给 Codex,让它自己开页面、看控制台、录 trace、点按钮。控制台和网络的毛病它一条没漏,可 trace 把布局偏移怪在一张图片头上,Agent 也原样写进了修复清单。我只照着改图片,CLS 一点没动。让 Agent 去读 DevTools 的时候,它给出的"根因"到底能信几成?
这篇是我从源码构建开始跑完的记录:CLI 会话、trace、Lighthouse、Codex 接入、改完复测,以及它哪几处不能直接信。命令和输出都是在全新的 HOME 目录里按文中顺序重放的。
文章目录
- [给 Agent 接上 Chrome DevTools:报错它全抓到了,CLS 的锅却甩错了人](#给 Agent 接上 Chrome DevTools:报错它全抓到了,CLS 的锅却甩错了人)
-
- [一、它是什么:一个 MCP server,外加一个常驻的命令行](#一、它是什么:一个 MCP server,外加一个常驻的命令行)
-
- [1. 链路只有三段](#1. 链路只有三段)
- [2. 返回的是摘要和文件路径,不是原始数据](#2. 返回的是摘要和文件路径,不是原始数据)
- [3. 默认开着的几件事](#3. 默认开着的几件事)
- 二、上手实战:从源码构建到修复复测
-
- [1. 克隆、构建、包一层启动脚本](#1. 克隆、构建、包一层启动脚本)
- [2. 用最原始的 JSON-RPC 数一数工具](#2. 用最原始的 JSON-RPC 数一数工具)
- [3. 搭一个埋了坑的页面](#3. 搭一个埋了坑的页面)
- [4. 不用模型:命令行会话里把页面查一遍](#4. 不用模型:命令行会话里把页面查一遍)
- [5. 录 trace,看 insight,跑 Lighthouse](#5. 录 trace,看 insight,跑 Lighthouse)
- [6. 接进 Codex:同一个任务,跑两遍](#6. 接进 Codex:同一个任务,跑两遍)
- [7. 堆快照和录屏](#7. 堆快照和录屏)
- [8. 按它说的改,再测一遍](#8. 按它说的改,再测一遍)
- 三、实测复盘:它抓得准的,和三件不能直接信的
-
- [1. 抓得准的部分](#1. 抓得准的部分)
- [2. 归因层面:CLS 的 insight 把锅甩给了图片](#2. 归因层面:CLS 的 insight 把锅甩给了图片)
- [3. 看不见的两样:长任务和请求耗时](#3. 看不见的两样:长任务和请求耗时)
- [4. 一次完整的 Agent 会话是怎么走的](#4. 一次完整的 Agent 会话是怎么走的)
- [5. 工具层面的几处不整齐](#5. 工具层面的几处不整齐)
- 四、我没跑的,和跑不了的
- 五、我的判断:它是个靠谱的观察员,不是个靠谱的诊断员
- 六、写在最后
一、它是什么:一个 MCP server,外加一个常驻的命令行
1. 链路只有三段
chrome-devtools-mcp 说白了是一个本机 Node 进程。Agent 通过 MCP 发工具调用,它用 puppeteer 经 CDP 去控制 Chrome,再把 DevTools 自己的 trace 分析和 Lighthouse 打包在里面,把结果整理成文本还给 Agent。你自己写 puppeteer 脚本也能拿到控制台和网络,区别在于这里把 DevTools 自带的 trace 引擎和 Lighthouse 一起装进来,解析好的 insight 可以直接用。同一份能力还有一个叫 chrome-devtools 的命令行,它会起一个后台 daemon,通过 Unix socket 连着,浏览器常驻,所以你一条一条敲命令,页面状态是接得上的。

我跑的版本是 1.14.0,默认暴露 33 个工具,大致分成输入自动化、导航、模拟、性能、网络、调试几类,再加内存类里的 take_heapsnapshot;加 --slim 只剩 evaluate、navigate、screenshot 三个。堆快照分析、扩展、PWA 这些类别要加参数才会打开。
浏览器的 profile 有个默认值得知道:MCP server 不加 --isolated 的话,会用 $HOME/.cache/chrome-devtools-mcp/chrome-profile 这个固定目录,多次运行共享 cookie 和登录态;加了就每次起一个临时 profile,浏览器一关就清掉。我所有命令都加了 --isolated。命令行 daemon 则默认就是 headless 加 isolated,除非你自己传 --userDataDir。
2. 返回的是摘要和文件路径,不是原始数据
仓库的设计文档列了七条原则,我读下来在实测里反复应验的是两条。一条是 Token-Optimized:重的东西(截图、trace、视频)返回文件路径,回答尽量是语义摘要,比如"LCP 是 3.2 秒",而不是五万行 JSON。另一条是 Self-Healing Errors:报错要带上下文和修复提示,后面敲错命令时会看到这一条的实物。
摘要的好处是省上下文,代价是细节要靠追问,追问的入口是 insight 名字和 evaluate_script。比如录一次 trace,返回里只有 LCP、CLS 和七个可追问的 insight 名字(LCPBreakdown、LCPDiscovery、CLSCulprits、RenderBlocking、NetworkDependencyTree、ImageDelivery、Cache),想看哪个再单独调 performance_analyze_insight。Lighthouse 也是这个套路,lighthouse_audit 把完整报告写成 report.json 和 report.html,返回里只给分数和没通过的项。这个"追问才有细节"的设计,正好是第三节几个坑的来源。
3. 默认开着的几件事
README 里写明三件事:Google 默认收集使用统计,要加 --no-usage-statistics 关;性能工具可能把 trace 里的 URL 发给 CrUX API 取真实用户数据,要加 --no-performance-crux 关;server 会检查 npm 上有没有新版,设环境变量 CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS=1 可以关。我下面所有命令都关了这三样,是为了不往外发东西,不是因为它们有问题;你要是拿它去开公司内网的页面,该自己决定开不开。
文件系统也有一笔账:文档说命令行默认不限制可读写的路径,要用 --workspace 收紧;MCP server 的文件类工具默认只允许系统临时目录。我只验证了命令行这一边,确实能把截图和 trace 写到任意路径。
二、上手实战:从源码构建到修复复测
环境前提:Linux,Node 20.19 以上(我用 24),git、python3、curl,一个装好的 Chrome(我这台是 156,非 root 用户,不加 --no-sandbox 就能跑 headless),磁盘留 6 GB。我从源码构建,因为这次要跑的是仓库本身;只想用的话直接 npx chrome-devtools-mcp@latest,那条路我没跑。接 Codex 要有账号,不想花钱就跳过,命令行会话已经用到同一批工具,只是少了模型。
每个新开的终端先执行这两行,后面的命令都默认它们生效:
bash
export PATH=$HOME/bin:$PATH
export CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS=1
1. 克隆、构建、包一层启动脚本
bash
mkdir -p ~/cdt && cd ~/cdt
node -v
npm -v
google-chrome --version
git clone --depth 1 https://github.com/ChromeDevTools/chrome-devtools-mcp.git repo 2>&1 | tail -1
cd repo && git log --oneline | head -1 && grep '"version"' package.json
你应该看到:
text
v24.22.1
11.21.1
Google Chrome 156.0.8078.47
Cloning into 'repo'...
6270b82 fix: wait for all running queues in TaskRunner.pause() (#3650)
"version": "1.14.0",
npm run sync 会 npm ci、更新 DevTools 前端子模块、用 gclient 拉依赖;我跳过了 puppeteer 自带的 Chrome 下载。
bash
START=$(date +%s)
PUPPETEER_SKIP_DOWNLOAD=1 npm run sync 2>&1 | grep -E "^Cloning depot_tools|Running gclient sync|Linking DevTools|^Done\."
echo "elapsed $(( $(date +%s) - START )) s"
du -sh ~/cdt/repo | awk '{print $1}'
你应该看到:
text
Cloning depot_tools...
Running gclient sync...
Linking DevTools DEPS and generating GN build files...
Done. Made 5552 targets from 439 files in 313ms
elapsed 120 s
5.5G
两分钟,占 5.5 GB。接着构建,gn 加 ninja,十几秒。
bash
START=$(date +%s)
npm run build 2>&1 | tail -3
echo "elapsed $(( $(date +%s) - START )) s"
ls out/Default/gen/src/bin | grep -E '^chrome-devtools(-mcp)?\.js$'
你应该看到:
text
[388/390] ACTION //src:bin_checked(//build/toolchain/linux:x64)
[389/390] ACTION //tests:tests_checked(//build/toolchain/linux:x64)
[390/390] ACTION //tests:run_chrome_devtools_mcp_tests(//build/toolchain/linux:x64)
elapsed 13 s
chrome-devtools-mcp.js
chrome-devtools.js
最后一行说明构建顺带跑了仓库自己的测试,我只看了尾巴,没有逐条核对。为了让后面的命令和 npx 版长得一样,我在 ~/bin 里各放一个启动脚本:
bash
mkdir -p ~/bin
for name in chrome-devtools-mcp chrome-devtools; do
printf '#!/bin/sh\nexec node %s/cdt/repo/out/Default/gen/src/bin/%s.js "$@"\n' "$HOME" "$name" > ~/bin/$name
chmod +x ~/bin/$name
done
cat ~/bin/chrome-devtools-mcp
chrome-devtools-mcp --version
npm view chrome-devtools-mcp version
你应该看到(路径是你自己的 HOME,这里和后面的输出里都缩写成 ~;最后一行是 npm 上的最新版,和仓库一致):
text
#!/bin/sh
exec node ~/cdt/repo/out/Default/gen/src/bin/chrome-devtools-mcp.js "$@"
1.14.0
1.14.0
2. 用最原始的 JSON-RPC 数一数工具
在接任何客户端之前,我先用二十几行 Python 直接和 server 握手,看它到底暴露了什么。
bash
cd ~/cdt
cat > listtools.py <<'EOF'
"""用最原始的方式和 MCP server 握手并列出工具:python listtools.py [server 的额外参数...]"""
import json, subprocess, sys, textwrap
cmd = ["chrome-devtools-mcp", "--headless", "--isolated", "--no-usage-statistics", "--no-performance-crux", *sys.argv[1:]]
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
def send(message):
proc.stdin.write(json.dumps(message) + "\n")
proc.stdin.flush()
def read(want_id):
while True:
message = json.loads(proc.stdout.readline())
if message.get("id") == want_id:
return message["result"]
send({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "probe", "version": "0"}}})
info = read(1)["serverInfo"]
send({"jsonrpc": "2.0", "method": "notifications/initialized"})
send({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
tools = read(2)["tools"]
proc.terminate()
print(f"{info['name']} {info['version']},暴露 {len(tools)} 个工具(参数:{' '.join(sys.argv[1:]) or '默认'})")
print(textwrap.fill(" ".join(sorted(t["name"] for t in tools)), 100))
EOF
python3 listtools.py
python3 listtools.py --slim
你应该看到:
text
chrome_devtools 1.14.0,暴露 33 个工具(参数:默认)
click close_page drag emulate evaluate_script fill fill_form get_console_message get_css_styles
get_network_request handle_dialog hover lighthouse_audit list_console_messages list_network_requests
list_pages navigate_page new_page performance_analyze_insight performance_start_trace
performance_stop_trace press_key resize_page screencast_start screencast_stop select_page
set_logpoints take_heapsnapshot take_screenshot take_snapshot type_text upload_file wait_for
chrome_devtools 1.14.0,暴露 3 个工具(参数:--slim)
evaluate navigate screenshot
默认 33 个,--slim 三个。仓库的工具参考文档里列的比 33 多,多出来的是要加参数才打开的可选类别,我没有逐个打开。
3. 搭一个埋了坑的页面
坑都是我故意埋的。服务端:/api/orders 慢 2.4 秒,/api/stats 返回 500,第二个 origin 的 /rates 不带 CORS 头,vendor.js 卡 1.5 秒。页面:700 毫秒的同步循环,1.2 秒后才插进来的横幅,没写宽高的大图,没名字的按钮,对比度很低的灰字,点退款会抛 TypeError 的处理函数。
bash
mkdir -p ~/cdt/site/public && cd ~/cdt/site
cat > server.mjs <<'EOF'
// 带埋点 bug 的演示站:node server.mjs,主站 :4173,第二个 origin :4174(故意不带 CORS 头)
// 环境变量:PUBLIC 换静态目录,MAIN_PORT 换主站端口,OTHER=off 不起第二个 origin
import http from 'node:http';
import {readFile} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import path from 'node:path';
const dir = path.dirname(fileURLToPath(import.meta.url));
const pub = process.env.PUBLIC || 'public';
const mainPort = Number(process.env.MAIN_PORT || 4173);
const sleep = ms => new Promise(r => setTimeout(r, ms));
const types = {'.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.png': 'image/png'};
const main = http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
const send = (code, body, type = 'application/json') => {
res.writeHead(code, {'content-type': type});
res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body));
};
if (url.pathname === '/api/orders') { // 慢接口:2.4 秒
await sleep(2400);
return send(200, {orders: [{id: 1, total: 120}, {id: 2, total: 85}, {id: 3, total: 40}]});
}
if (url.pathname === '/api/stats') return send(500, {error: 'stats backend down'}); // 500
if (url.pathname === '/vendor.js') { // 阻塞渲染的第三方脚本:1.5 秒
await sleep(1500);
return send(200, 'window.vendorReady = true;', 'text/javascript');
}
const file = url.pathname === '/' ? '/index.html' : url.pathname;
try {
return send(200, await readFile(path.join(dir, pub, file)), types[path.extname(file)] || 'application/octet-stream');
} catch {
return send(404, 'not found', 'text/plain');
}
});
const other = http.createServer((req, res) => { // 另一个 origin,没有 Access-Control-Allow-Origin
res.writeHead(200, {'content-type': 'application/json'});
res.end(JSON.stringify({rates: {USD: 1, EUR: 0.92}}));
});
main.listen(mainPort, '127.0.0.1', () => console.log('main http://127.0.0.1:' + mainPort));
if (process.env.OTHER !== 'off') other.listen(4174, '127.0.0.1', () => console.log('other http://127.0.0.1:4174'));
EOF
页面本身三个文件:
bash
cat > public/index.html <<'EOF'
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>Orders Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/style.css">
<script src="/vendor.js"></script>
</head>
<body>
<header><h1>Orders Dashboard</h1></header>
<div id="banner-slot"></div>
<main>
<img src="/hero.png" class="hero">
<section id="orders"><p id="status">loading...</p><ul id="list"></ul></section>
<button id="export"><svg width="16" height="16"><circle cx="8" cy="8" r="6"/></svg></button>
<button id="refund">Refund last order</button>
<p class="hint">Rates and stats load in the background.</p>
</main>
<script src="/app.js"></script>
</body>
</html>
EOF
cat > public/style.css <<'EOF'
body { font-family: sans-serif; margin: 0; background: #fff; color: #222; }
header { padding: 16px 24px; background: #243b53; color: #fff; }
main { padding: 24px; }
.hero { max-width: 100%; }
#banner { background: #ffe9a8; padding: 64px; text-align: center; font-size: 22px; }
.hint { color: #bbb; }
button { padding: 8px 14px; margin-right: 8px; }
EOF
cat > public/app.js <<'EOF'
// 埋点 1:加载时同步干 700ms 的活(长任务)
function heavySetup() {
const start = performance.now();
let x = 0;
while (performance.now() - start < 700) { x += Math.sqrt(x + 1); }
return x;
}
heavySetup();
// 埋点 2:横幅 1.2 秒后插到内容上方(布局偏移)
setTimeout(() => {
const el = document.createElement('div');
el.id = 'banner';
el.textContent = 'Black Friday: free shipping on all orders';
document.getElementById('banner-slot').appendChild(el);
}, 1200);
// 埋点 3:慢接口 + 500 + 跨域失败
fetch('/api/orders')
.then(r => r.json())
.then(d => {
document.getElementById('status').textContent = d.orders.length + ' orders';
document.getElementById('list').innerHTML = d.orders.map(o => '<li>#' + o.id + ' --- $' + o.total + '</li>').join('');
});
fetch('/api/stats').then(r => r.json()).then(s => console.log('stats', s.total.count));
fetch('http://127.0.0.1:4174/rates').then(r => r.json()).then(r => console.log('rates', r));
// 埋点 4:点击退款时读一个不存在的对象(运行时异常)
document.getElementById('refund').addEventListener('click', () => {
const order = window.lastOrder;
console.error('Refund failed for order', order.id);
});
console.warn('legacy checkout flow is deprecated');
EOF
大图用一个标准库脚本生成,带噪点,压不动,这样才像一张"忘了压缩的 hero 图":
bash
cat > make_hero.py <<'EOF'
"""生成一张故意不压缩的大图(1600x1000,带噪点的渐变,约 4~5 MB):python make_hero.py public/hero.png"""
import random, struct, sys, zlib
w, h = 1600, 1000
rng = random.Random(7)
rows = bytearray()
for y in range(h):
rows.append(0)
noise = rng.randbytes(w * 3)
for x in range(w):
base = (60 + 90 * x // w, 110 + 80 * y // h, 170 - 60 * x // w)
i = x * 3
rows += bytes(min(255, max(0, base[k] + noise[i + k] // 9 - 14)) for k in range(3))
def chunk(tag, data):
body = tag + data
return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body))
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) \
+ chunk(b"IDAT", zlib.compress(bytes(rows), 1)) + chunk(b"IEND", b"")
open(sys.argv[1], "wb").write(png)
print("wrote", sys.argv[1], len(png) // 1024, "KB")
EOF
python3 make_hero.py public/hero.png
你应该看到:
text
wrote public/hero.png 3923 KB
起服务,用 curl 验证埋的坑都在。
bash
setsid nohup node server.mjs > ~/cdt/server.log 2>&1 &
sleep 1
cat ~/cdt/server.log
你应该看到:
text
main http://127.0.0.1:4173
other http://127.0.0.1:4174
bash
for p in / /api/orders /api/stats /vendor.js; do curl -s -o /dev/null -w "%{http_code} %{time_total}s $p\n" http://127.0.0.1:4173$p; done
你应该看到:
text
200 0.006790s /
200 2.403531s /api/orders
500 0.001023s /api/stats
200 1.502104s /vendor.js
4. 不用模型:命令行会话里把页面查一遍
文档说命令行支持所有工具,我拿它的帮助和 MCP 的工具清单对了一下。
bash
cd ~/cdt
chrome-devtools --help 2>&1 | grep -oE "^ chrome-devtools [a-z_0-9]+" | awk '{print $2}' | sort > cli.txt
python3 listtools.py | tail -n +2 | tr ' ' '\n' | grep -v '^$' | sort > mcp.txt
wc -l < cli.txt
comm -23 mcp.txt cli.txt
你应该看到:
text
64
fill_form
wait_for
64 条命令里包含 start、status、stop 这几个管理命令,比默认的 33 个工具多不少,多出来的是 MCP 里要加参数才打开的类别;但缺了 fill_form 和 wait_for。没有 wait_for,等页面加载只能自己 sleep。它们的真实报错是这样:
bash
chrome-devtools wait_for "Orders" 2>&1 | head -1
chrome-devtools take_heapsnapshot 2 2>&1 | head -1
你应该看到:
text
Error: Unknown arguments: wait_for, Orders
Error: Not enough non-option arguments: got 1, need at least 2
第二条是另一个坑:必填参数得写成位置参数,take_heapsnapshot 要 pageId 和路径两个,少一个就这样报。报错后面跟着一段写给 AI Agent 的提示,教它别用 --pageId 这种写法。启动 daemon:
bash
chrome-devtools start --headless --isolated --no-usage-statistics --no-performance-crux 2>&1
chrome-devtools status
你应该看到:
text
chrome-devtools-mcp exposes content of the browser instance to the MCP clients allowing them to inspect,
debug, and modify any data in the browser or DevTools.
Avoid sharing sensitive or personal information that you do not want to share with MCP clients.
chrome-devtools-mcp daemon is running.
pid=985503 socket=/tmp/xdg-runtime-box-6/chrome-devtools-mcp/server.sock start-date=2026-12-01T08:51:01.492Z version=1.14.0
args=["--viaCli","--headless","--isolated","--no-performance-crux","--no-usage-statistics"]
前两行是安全提示:它把整个浏览器暴露给客户端。接着打开页面,new_page 的返回里已经带了加载期间的控制台错误。
bash
chrome-devtools new_page "http://127.0.0.1:4173/"
你应该看到:
text
## Pages
1: about:blank
2: Orders Dashboard (http://127.0.0.1:4173/) [selected]
## Third-party developer tools
No third-party developer tools available.
## Console errors during this call
msgid=3 [error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (0 args)
msgid=4 [error] Access to fetch at 'http://127.0.0.1:4174/rates' from origin 'http://127.0.0.1:4173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. (0 args)
msgid=5 [error] Failed to load resource: net::ERR_FAILED (0 args)
msgid=6 [error] Uncaught (in promise) TypeError: Failed to fetch (0 args)
msgid=7 [error] Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'count') (0 args)
msgid=8 [error] Failed to load resource: the server responded with a status of 404 (Not Found) (0 args)
六条错误,对应我埋的 500、跨域、count 读空、favicon 404。再用 list_console_messages 看全量,挑那条 TypeError 取堆栈。
bash
chrome-devtools list_console_messages 2
id=$(chrome-devtools list_console_messages 2 | grep "reading 'count'" | sed -E 's/^msgid=([0-9]+).*/\1/')
chrome-devtools get_console_message 2 $id
你应该看到:
text
## Console messages
Showing 1-8 of 8 (Page 1 of 1).
msgid=1 [warn] legacy checkout flow is deprecated (1 args)
msgid=2 [issue] Ensure CORS response header values are valid (count: 1)
msgid=3 [error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (0 args)
msgid=4 [error] Access to fetch at 'http://127.0.0.1:4174/rates' from origin 'http://127.0.0.1:4173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. (0 args)
msgid=5 [error] Failed to load resource: net::ERR_FAILED (0 args)
msgid=6 [error] Uncaught (in promise) TypeError: Failed to fetch (0 args)
msgid=7 [error] Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'count') (0 args)
msgid=8 [error] Failed to load resource: the server responded with a status of 404 (Not Found) (0 args)
ID: 7
Message: error> Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'count')
### Stack trace
at (app.js:25:80)
--- Promise.then -----------------------
at (app.js:25:41)
Note: line and column numbers use 1-based indexing
堆栈指到 app.js:25:80,正是 s.total.count 那一行。网络请求这边:
bash
chrome-devtools list_network_requests 2
chrome-devtools get_network_request 2 --reqid 7 | sed -n '1,2p;/### Response Body/,$p'
你应该看到:
text
## Network requests
Showing 1-9 of 9 (Page 1 of 1).
reqid=1 GET http://127.0.0.1:4173/ [200]
reqid=2 GET http://127.0.0.1:4173/style.css [200]
reqid=3 GET http://127.0.0.1:4173/vendor.js [200]
reqid=4 GET http://127.0.0.1:4173/hero.png [200]
reqid=5 GET http://127.0.0.1:4173/app.js [200]
reqid=6 GET http://127.0.0.1:4173/api/orders [pending]
reqid=7 GET http://127.0.0.1:4173/api/stats [500]
reqid=8 GET http://127.0.0.1:4174/rates [net::ERR_FAILED]
reqid=9 GET http://127.0.0.1:4173/favicon.ico [404]
## Request http://127.0.0.1:4173/api/stats
Status: 500
### Response Body
{"error":"stats backend down"}
/api/orders 是 [pending],因为 new_page 一返回我就去列了,2.4 秒的请求还在路上。而且列表里没有耗时,"哪个请求慢"它答不了,我换成页面里的 Resource Timing,先 sleep 3 等请求落地(evaluate_script 的输出外面还裹着一层 markdown 围栏,下面两处我把围栏行去掉了,免得和文章的代码块打架):
bash
sleep 3
chrome-devtools evaluate_script '() => performance.getEntriesByType("resource").map(e => ({name: e.name.replace(location.origin, ""), ms: Math.round(e.duration)}))' --pageId 2
你应该看到:
text
Script ran on page and returned:
[{"name":"/style.css","ms":5},{"name":"/vendor.js","ms":1506},{"name":"/app.js","ms":5},{"name":"/hero.png","ms":14},{"name":"/api/orders","ms":2405},{"name":"http://127.0.0.1:4174/rates","ms":2},{"name":"/api/stats","ms":3},{"name":"/favicon.ico","ms":1}]
vendor.js 1506 毫秒,/api/orders 2405 毫秒,和服务端埋的延迟吻合。主线程的 700 毫秒长任务,同样要靠 evaluate_script 加 PerformanceObserver 去抓:
bash
chrome-devtools evaluate_script '() => new Promise(resolve => { const seen = []; new PerformanceObserver(list => seen.push(...list.getEntries())).observe({type: "longtask", buffered: true}); setTimeout(() => resolve(seen.map(e => ({start: Math.round(e.startTime), ms: Math.round(e.duration)}))), 300); })' --pageId 2
你应该看到:
text
Script ran on page and returned:
[{"start":1514,"ms":702}]
702 毫秒,从 1514 毫秒开始。记住这两个数字,后面它们会合在一起解释 LCP。接着用无障碍树快照找到退款按钮并点击:
bash
chrome-devtools take_snapshot 2
uid=$(chrome-devtools take_snapshot 2 | grep 'Refund last order' | sed -E 's/.*uid=([0-9_]+).*/\1/')
chrome-devtools click 2 $uid
你应该看到:
text
## Latest page snapshot
uid=1_0 RootWebArea "Orders Dashboard" url="http://127.0.0.1:4173/"
uid=1_1 banner
uid=1_2 heading "Orders Dashboard" level="1"
uid=1_3 "Black Friday: free shipping on all orders"
uid=1_4 main
uid=1_5 "3 orders"
uid=1_6 "#1 --- $120"
uid=1_7 "#2 --- $85"
uid=1_8 "#3 --- $40"
uid=1_9 button
uid=1_10 button "Refund last order"
uid=1_11 "Rates and stats load in the background."
Successfully clicked on the element
## Console errors during this call
msgid=9 [error] Uncaught TypeError: Cannot read properties of undefined (reading 'id') (0 args)
快照里有一行 uid=1_9 button,没有名字,是我埋的圆形按钮。点击后控制台新增了一条 reading 'id' 的 TypeError。最后截一张整页图:
bash
mkdir -p ~/cdt/out
chrome-devtools take_screenshot 2 --filePath ~/cdt/out/dashboard.png --fullPage
ls -l ~/cdt/out/dashboard.png | awk '{print $5, $9}'
你应该看到:
text
Took a screenshot of the full current page.
Saved screenshot to ~/cdt/out/dashboard.png.
3487310 ~/cdt/out/dashboard.png

红色标注是我后加的,标 1 和标 2 下一节会打架。
5. 录 trace,看 insight,跑 Lighthouse
performance_start_trace 默认会重新加载页面并自动停止,LCP、CLS 和可追问的 insight 名字都在返回里。
bash
cd ~/cdt
chrome-devtools performance_start_trace 2 --filePath ~/cdt/out/trace.json.gz 2>&1 | grep -E "saved|stopped|^URL|throttling|LCP:|Render delay|TTFB|CLS:|insight name"
你应该看到:
text
The raw trace data was saved to ~/cdt/out/trace.json.gz.
The performance trace has been stopped.
URL: http://127.0.0.1:4173/
CPU throttling: 1x
Network throttling: none
URL: http://127.0.0.1:4173/
- LCP: 2273 ms, event: (eventKey: r-5829, ts: 70362495864), nodeId: 4
- TTFB: 3 ms, bounds: {min: 70360222817µs, max: 70360225353.00002µs}
- Render delay: 2,255 ms, bounds: {min: 70360240463µs, max: 70362495864µs}
- CLS: 0.05, event: (eventKey: c-6526, ts: 70363637382)
- insight name: LCPBreakdown
- insight name: LCPDiscovery
- insight name: CLSCulprits
- insight name: RenderBlocking
- insight name: NetworkDependencyTree
- insight name: ImageDelivery
- insight name: Cache
LCP 2273 毫秒,渲染延迟占了 2255 毫秒,几乎全是等。CLS 0.05。trace 文件也检查一下,是合法的 JSON,可以导入 DevTools 的 Performance 面板再看:
bash
ls -l ~/cdt/out/trace.json.gz | awk '{print $5, $9}'
zcat ~/cdt/out/trace.json.gz | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d['traceEvents']), 'trace events')"
你应该看到:
text
208321 ~/cdt/out/trace.json.gz
10473 trace events
再追问渲染阻塞的 insight,输出表很长,我用 grep 只留标题、URL 表和两行数据,数据行截到 200 个字符。
bash
chrome-devtools performance_analyze_insight 2 NAVIGATION_0 RenderBlocking 2>&1 | grep -E "^## Insight Title|^allUrls|^[02];s-" | cut -c1-200
你应该看到:
text
## Insight Title: Render-blocking requests
allUrls = [0: http://127.0.0.1:4173/vendor.js, 1: http://127.0.0.1:4173/, 2: http://127.0.0.1:4173/style.css]
0;s-759;6 ms;7 ms;1,510 ms;1,510 ms;1,504 ms;0.4 ms;0.6 ms;200;text/javascript;High;High;High;t;http/1.1;f;1;[];[Transfer-Encoding: chunked|Keep-Alive: <redacted>|Date: Tue, 01 Dec 2026 08:51:1
2;s-755;6 ms;7 ms;9 ms;11 ms;5 ms;0.2 ms;2 ms;200;text/css;VeryHigh;VeryHigh;VeryHigh;t;http/1.1;f;1;[];[Transfer-Encoding: chunked|Keep-Alive: <redacted>|Date: Tue, 01 Dec 2026 08:51:11 GMT|co
vendor.js 阻塞 1510 毫秒,被点了名。再看 CLS 的 insight:
bash
chrome-devtools performance_analyze_insight 2 NAVIGATION_0 CLSCulprits 2>&1 | grep -E "worst|score for|Impacted|^ - |Potential|unsized|Start time"
你应该看到:
text
The worst layout shift cluster was the cluster that started at 3,417 ms and ended at 4,417 ms, with a duration of 1,000 ms.
The score for this cluster is 0.0518.
- Impacted elements:
- MAIN
- Start time: 3,417 ms
- Potential root causes:
- An unsized image (IMG class='hero') (url: http://127.0.0.1:4173/hero.png (eventKey: s-760, ts: 70360228986)).
最后一行是重点:它说潜在原因是一张没写尺寸的图片,IMG class='hero'。先记下,后面验证。接着跑 Lighthouse:
bash
chrome-devtools lighthouse_audit 2 --outputDirPath ~/cdt/out/lh 2>&1 | grep -E "^- (Accessibility|Best|SEO|Agentic)|^Passed|^Failed|^- [a-z-]+ \[|^- .*report\." | cut -c1-170
你应该看到:
text
- Accessibility: 72 (accessibility)
- Best Practices: 96 (best-practices)
- SEO: 82 (seo)
- Agentic Browsing: 45 (agentic-browsing)
Passed: 33
Failed: 7
- cumulative-layout-shift [agentic-browsing]: Cumulative Layout Shift (0.103) (score: 0.89)
- errors-in-console [best-practices]: Browser errors were logged to the console (score: 0)
- button-name [accessibility]: Buttons do not have an accessible name (score: 0)
- color-contrast [accessibility]: Background and foreground colors do not have a sufficient contrast ratio. (score: 0)
- image-alt [accessibility, seo]: Image elements do not have `[alt]` attributes (score: 0)
- meta-description [seo]: Document does not have a meta description (score: 0)
- agent-accessibility-tree [agentic-browsing]: Accessibility tree is not well-formed (score: 0)
- ~/cdt/out/lh/report.json
- ~/cdt/out/lh/report.html
七项没过,对比度那项我翻了 report.json,灰字是 1.91:1,要求 4.5:1。CLS 在这里是 0.103,和 trace 的 0.05 差了一倍。再模拟差一点的设备,4 倍 CPU 降速加 Slow 4G,重新录一次:
bash
chrome-devtools emulate 2 --cpuThrottlingRate 4 --networkConditions "Slow 4G"
chrome-devtools performance_start_trace 2 2>&1 | grep -E "throttling|LCP:|Render delay|CLS:"
chrome-devtools emulate 2
chrome-devtools stop
你应该看到:
text
Emulation configured successfully
Emulating network conditions: Slow 4G
Default navigation timeout set to 100000 ms
Emulating CPU throttling: 4x slowdown
Emulating CPU throttling: 4x slowdown
CPU throttling: 4x
Network throttling: Slow 4G
- LCP: 2907 ms, event: (eventKey: r-7379, ts: 70380358203), nodeId: 9
- Render delay: 2,905 ms, bounds: {min: 70377453588µs, max: 70380358203µs}
- CLS: 0.05, event: (eventKey: c-10652, ts: 70381473081)
Emulation configured successfully
LCP 2273 变成 2907,CLS 仍是 0.05。单次运行,只说明限速命令生效了。
6. 接进 Codex:同一个任务,跑两遍
先写任务和一个把 codex exec --json 事件流压成摘要的小脚本。
bash
mkdir -p ~/cdt/agent && cd ~/cdt/agent
cat > prompt.txt <<'EOF'
Use only the chrome-devtools MCP tools (do not read local files and do not use the shell).
The page http://127.0.0.1:4173/ is a small orders dashboard that feels slow and has errors.
1. Open it and list every console error and warning.
2. List the network requests and tell me which ones failed.
3. Record a performance trace with a reload and report LCP, CLS and the main causes the trace points to.
4. Click the "Refund last order" button and report what happens in the console.
Finish with a short, prioritized fix list. Quote the tool outputs you rely on.
EOF
cat > summarize.py <<'EOF'
"""把 codex exec --json 的事件流压成一份摘要:python summarize.py <jsonl> [最多显示的最终回答行数]"""
import json, sys
limit = int(sys.argv[2]) if len(sys.argv) > 2 else 60
final = ""
for line in open(sys.argv[1]):
event = json.loads(line)
item = event.get("item", {})
if event["type"] != "item.completed":
continue
if item["type"] == "mcp_tool_call":
args = json.dumps(item["arguments"], ensure_ascii=False)
error = f" <- {item['error']['message']}" if item.get("error") else ""
print(f"[{item['status']}] {item['tool']} {args[:110]}{error}")
elif item["type"] == "agent_message":
final = item["text"]
print("--- 最终回答 ---")
print("\n".join(final.splitlines()[:limit]))
EOF
MCP server 用 -c 在命令行里临时注册,不改 Codex 的配置文件。我的 HOME 是临时的,所以命令前借了真实 HOME 去读登录,你在自己机器上去掉 HOME=/home/box 就行;Codex 还会清掉子进程的环境变量,所以要显式给 server 传 PATH。第一遍什么都不加:
bash
HOME=/home/box timeout 600 codex exec --skip-git-repo-check -s read-only -C "$PWD" --json \
-c 'mcp_servers.cdt.command="chrome-devtools-mcp"' \
-c 'mcp_servers.cdt.args=["--headless","--isolated","--no-usage-statistics","--no-performance-crux"]' \
-c "mcp_servers.cdt.env={PATH=\"$PATH\"}" \
- < prompt.txt > run_deny.jsonl 2> run_deny.err
python3 summarize.py run_deny.jsonl 8
你应该看到:
text
[failed] new_page {"url": "http://127.0.0.1:4173/"} <- MCP tool call requires approval, but approval policy is never
[completed] list_pages {}
[failed] navigate_page {"pageId": 1, "type": "url", "url": "http://127.0.0.1:4173/"} <- MCP tool call requires approval, but approval policy is never
[failed] navigate_page {"pageId": 1} <- MCP tool call requires approval, but approval policy is never
--- 最终回答 ---
I couldn't open `http://127.0.0.1:4173/` through Chrome DevTools. Both `new_page` and `navigate_page` returned:
> MCP tool call requires approval, but approval policy is never
`list_pages` showed only `1: about:blank [selected]`. No dashboard console messages or network requests were captured, no reload trace was recorded, and "Refund last order" was never clicked. There's no evidence yet for an LCP or CLS value or a prioritized dashboard fix list.
The immediate unblock is to allow Chrome DevTools navigation to the local URL or open the dashboard in the connected Chrome session.
new_page 和 navigate_page 都被拒了,错误原文是 MCP tool call requires approval, but approval policy is never,Agent 老实报告"打不开页面"。原因在工具元数据里,我写了个脚本看哪些工具声明了 readOnlyHint:
bash
cd ~/cdt
cat > readonly.py <<'EOF'
"""看每个工具有没有声明 readOnlyHint:python readonly.py。这决定了 Codex 在 exec 模式下哪些工具能直接放行"""
import json, subprocess, textwrap
proc = subprocess.Popen(["chrome-devtools-mcp", "--headless", "--isolated", "--no-usage-statistics", "--no-performance-crux"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
def call(message, want_id=None):
proc.stdin.write(json.dumps(message) + "\n")
proc.stdin.flush()
while want_id is not None:
reply = json.loads(proc.stdout.readline())
if reply.get("id") == want_id:
return reply["result"]
call({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "probe", "version": "0"}}}, 1)
call({"jsonrpc": "2.0", "method": "notifications/initialized"})
tools = call({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, 2)["tools"]
proc.terminate()
read_only = sorted(t["name"] for t in tools if t.get("annotations", {}).get("readOnlyHint") is True)
others = sorted(t["name"] for t in tools if t["name"] not in read_only)
print(f"{len(tools)} 个工具里,声明 readOnlyHint=true 的有 {len(read_only)} 个")
print(textwrap.fill("只读:" + " ".join(read_only), 100))
print(textwrap.fill("其余:" + " ".join(others), 100))
EOF
python3 readonly.py
你应该看到:
text
33 个工具里,声明 readOnlyHint=true 的有 8 个
只读:get_console_message get_css_styles list_console_messages list_network_requests list_pages
performance_analyze_insight select_page wait_for
其余:click close_page drag emulate evaluate_script fill fill_form get_network_request handle_dialog
hover lighthouse_audit navigate_page new_page performance_start_trace performance_stop_trace
press_key resize_page screencast_start screencast_stop set_logpoints take_heapsnapshot
take_screenshot take_snapshot type_text upload_file
33 个里只有 8 个声明只读,new_page、performance_start_trace、take_snapshot 都不在其中,非交互的 codex exec 对没声明的一律不放行。解法是把这个 server 的审批模式设成 approve:
bash
cd ~/cdt/agent
HOME=/home/box timeout 700 codex exec --skip-git-repo-check -s read-only -C "$PWD" --json \
-c 'mcp_servers.cdt.command="chrome-devtools-mcp"' \
-c 'mcp_servers.cdt.args=["--headless","--isolated","--no-usage-statistics","--no-performance-crux"]' \
-c "mcp_servers.cdt.env={PATH=\"$PATH\"}" \
-c 'mcp_servers.cdt.default_tools_approval_mode="approve"' \
- < prompt.txt > run_allow.jsonl 2> run_allow.err
python3 summarize.py run_allow.jsonl 80
最终回答有几十行,下面只摘工具调用列表、几段结论和修复清单,每行都是原文:
text
[completed] list_pages {}
[completed] navigate_page {"pageId": 1, "url": "http://127.0.0.1:4173/", "type": "url"}
[completed] list_console_messages {"pageId": 1, "types": ["error", "warn"], "includeStackTraces": true}
[completed] list_network_requests {"pageId": 1}
[completed] performance_start_trace {"pageId": 1, "reload": true, "autoStop": true, "ignoreCache": true}
[completed] performance_analyze_insight {"pageId": 1, "insightSetId": "NAVIGATION_0", "insightName": "LCPBreakdown"}
[completed] take_snapshot {"pageId": 1}
[completed] performance_analyze_insight {"pageId": 1, "insightSetId": "NAVIGATION_0", "insightName": "LCPDiscovery"}
[completed] performance_analyze_insight {"pageId": 1, "insightSetId": "NAVIGATION_0", "insightName": "CLSCulprits"}
[completed] performance_analyze_insight {"pageId": 1, "insightSetId": "NAVIGATION_0", "insightName": "RenderBlocking"}
[completed] performance_analyze_insight {"pageId": 1, "insightSetId": "NAVIGATION_0", "insightName": "ImageDelivery"}
[completed] click {"pageId": 1, "uid": "1_10"}
[completed] get_console_message {"pageId": 1, "msgid": 16}
[completed] list_network_requests {"pageId": 1}
--- 最终回答 ---
One cache-bypassed reload with no CPU or network throttling recorded **LCP of 2,281 ms** and **CLS of 0.05**.
- **LCP was dominated by render delay.** The LCP element was `hero.png`. DevTools reported `Download complete at: 21 ms` and `Element render delay: 2,261 ms (99.1% of total LCP time)`.
- **`vendor.js` was the longest render-blocking request.** The trace lists `1,504 ms` for `vendor.js` and `5 ms` for `style.css`. The insight reports `Estimated savings: FCP 0 ms, LCP 0 ms`, so the script is a lead to investigate and the trace does not quantify how much of the hero's render delay it explains.
- **`MAIN` shifted at 3,417 ms.** The layout-shift insight reports `Score: 0.0518` and flags `An unsized image (IMG class='hero')` as a potential root cause.
- **The hero has a substantial transfer-size opportunity.** Image Delivery reports `Potential savings: 3.8 MB` for `hero.png`, with zero estimated LCP savings on this local run.
1. Fix the refund handler's order lookup and disable the button when no refundable order is available.
2. Fix the `/api/stats` 500 and the `/rates` CORS configuration. Handle failed responses and missing stats in the UI so both fetch paths fail gracefully.
3. Profile what keeps the hero from painting after download. Start with the render-blocking `vendor.js` and defer it if initial rendering can proceed independently.
4. Reserve space for the hero with explicit dimensions or an aspect ratio, then serve a smaller WebP or AVIF.
5. Restore the favicon and migrate the deprecated checkout flow.
14 次工具调用,顺序是它自己定的。六个控制台错误加一个警告一个没少,退款按钮的 TypeError 也定位到了 app.js:31:50。它把 vendor.js 列为要去查的线索,还老实说 trace 没量化它能解释多少渲染延迟,这比我预期的克制。但第 4 条修复建议写的是 "Reserve space for the hero with explicit dimensions or an aspect ratio",接的正是 CLSCulprits,700 毫秒的长任务它整段没提。这是我第二次完整重放,两次的调用顺序和措辞都不一样,但都把 CLS 归给了图片,也都没提长任务。
7. 堆快照和录屏
这两个我只做了冒烟测试。堆快照存成文件,再让工具给一份摘要:
bash
cd ~/cdt
chrome-devtools start --headless --isolated --no-usage-statistics --no-performance-crux > /dev/null 2>&1
chrome-devtools new_page "http://127.0.0.1:4173/" > /dev/null 2>&1
chrome-devtools take_heapsnapshot 2 ~/cdt/out/page.heapsnapshot
ls -l ~/cdt/out/page.heapsnapshot | awk '{print $5, $9}'
chrome-devtools get_heapsnapshot_summary ~/cdt/out/page.heapsnapshot | sed -n '1,4p;/"nodeCount"/p'
你应该看到:
text
Heap snapshot saved to ~/cdt/out/page.heapsnapshot
3450701 ~/cdt/out/page.heapsnapshot
## Heap Snapshot Data
Statistics: {
"total": 1253678,
"native": {
"nodeCount": 36627,
录屏会存成 mp4,需要机器上有 ffmpeg(我这台本来就有,没装的情况我没试)。
bash
chrome-devtools screencast_start 2 --filePath ~/cdt/out/reload.mp4
chrome-devtools navigate_page 2 --type reload | head -1
sleep 4
chrome-devtools screencast_stop 2
ffprobe -v error -show_entries format=duration -of csv=p=0 ~/cdt/out/reload.mp4
chrome-devtools stop
你应该看到:
text
Screencast recording started. The recording will be saved to ~/cdt/out/reload.mp4. Use screencast_stop to stop recording.
Successfully reloaded the page.
The screencast recording has been stopped and saved to ~/cdt/out/reload.mp4.
6.509367
screencast_stop 也要 pageId,文件扩展名只认 .mp4。
8. 按它说的改,再测一遍
回到那句"未设置尺寸的图片"。在原版之外,我再做三个版本:全部修复、只给图片加宽高、只给横幅留位置。全部修复包括 vendor.js 加 defer,图片加宽高和 alt,横幅槽位留 154 像素高,删掉 700 毫秒的同步循环。
bash
cd ~/cdt/site
cat > fix.sh <<'EOF'
set -e
rm -rf public-fixed && cp -r public public-fixed
sed -i 's#<script src="/vendor.js">#<script defer src="/vendor.js">#' public-fixed/index.html
sed -i 's#<img src="/hero.png" class="hero">#<img src="/hero.png" class="hero" width="1600" height="1000" alt="dashboard hero">#' public-fixed/index.html
sed -i 's#<div id="banner-slot"></div>#<div id="banner-slot" style="min-height:154px"></div>#' public-fixed/index.html
sed -i '/^heavySetup();$/d' public-fixed/app.js
diff -ru public public-fixed || true
EOF
bash fix.sh
你应该看到:
text
diff -ru public/app.js public-fixed/app.js
--- public/app.js 2026-12-01 08:50:54.438616265 +0000
+++ public-fixed/app.js 2026-12-01 08:53:31.132395845 +0000
bash
rm -rf public-img public-banner
cp -r public public-img && sed -i 's#<img src="/hero.png" class="hero">#<img src="/hero.png" class="hero" width="1600" height="1000" alt="dashboard hero">#' public-img/index.html
cp -r public public-banner && sed -i 's#<div id="banner-slot"></div>#<div id="banner-slot" style="min-height:154px"></div>#' public-banner/index.html
for spec in public-fixed:4175 public-img:4176 public-banner:4177; do
PUBLIC=${spec%%:*} MAIN_PORT=${spec##*:} OTHER=off setsid nohup node server.mjs > ~/cdt/server-${spec%%:*}.log 2>&1 &
done
sleep 1
cat ~/cdt/server-public-fixed.log ~/cdt/server-public-img.log ~/cdt/server-public-banner.log
你应该看到:
text
main http://127.0.0.1:4175
main http://127.0.0.1:4176
main http://127.0.0.1:4177
四个端口各录一次 trace,只留 LCP 和 CLS:
bash
cd ~/cdt
chrome-devtools start --headless --isolated --no-usage-statistics --no-performance-crux > /dev/null 2>&1
chrome-devtools new_page "http://127.0.0.1:4173/" > /dev/null 2>&1
for spec in "没改:4173" "全部修复:4175" "只给图片加宽高:4176" "只给横幅留位置:4177"; do
echo "== ${spec%%:*} (端口 ${spec##*:})"
chrome-devtools navigate_page 2 --url "http://127.0.0.1:${spec##*:}/" > /dev/null 2>&1
chrome-devtools performance_start_trace 2 2>&1 | grep -E "LCP:|Render delay|CLS:" | sed -E 's/, event:.*//; s/, bounds:.*//'
done
你应该看到:
text
== 没改 (端口 4173)
- LCP: 2292 ms
- Render delay: 2,275 ms
- CLS: 0.05
== 全部修复 (端口 4175)
- LCP: 84 ms
- Render delay: 82 ms
- CLS: 0.00
== 只给图片加宽高 (端口 4176)
- LCP: 2303 ms
- Render delay: 2,288 ms
- CLS: 0.05
== 只给横幅留位置 (端口 4177)
- LCP: 2285 ms
- Render delay: 2,268 ms
- CLS: 0.00

全部修复后 LCP 从 2292 毫秒掉到 84 毫秒,CLS 归零。只给图片加宽高,CLS 仍是 0.05;只给横幅留位置,CLS 归零。trace 点名的那张图不是原因,真凶是 JS 晚插进来的横幅。
bash
chrome-devtools navigate_page 2 --url "http://127.0.0.1:4175/" > /dev/null 2>&1
chrome-devtools lighthouse_audit 2 2>&1 | grep -E "^- (Accessibility|Best|SEO|Agentic)|^Passed|^Failed|^- [a-z-]+ \[" | cut -c1-150
你应该看到:
text
- Accessibility: 82 (accessibility)
- Best Practices: 92 (best-practices)
- SEO: 91 (seo)
- Agentic Browsing: 50 (agentic-browsing)
Passed: 34
Failed: 6
- errors-in-console [best-practices]: Browser errors were logged to the console (score: 0)
- image-aspect-ratio [best-practices]: Displays images with incorrect aspect ratio (score: 0)
- button-name [accessibility]: Buttons do not have an accessible name (score: 0)
- color-contrast [accessibility]: Background and foreground colors do not have a sufficient contrast ratio. (score: 0)
- meta-description [seo]: Document does not have a meta description (score: 0)
- agent-accessibility-tree [agentic-browsing]: Accessibility tree is not well-formed (score: 0)
CLS 那项没了,但 Best Practices 从 96 掉到 92,原因是 image-aspect-ratio:CSS 只写了 max-width: 100%,窗口窄时宽度缩了、高度还按属性撑着,比例就歪了。这是我自己改出来的错。补一行 height: auto 再测:
bash
sed -i 's#.hero { max-width: 100%; }#.hero { max-width: 100%; height: auto; }#' ~/cdt/site/public-fixed/style.css
grep -n 'hero' ~/cdt/site/public-fixed/style.css
chrome-devtools lighthouse_audit 2 2>&1 | grep -E "^- (Accessibility|Best|SEO|Agentic)|^Passed|^Failed|^- [a-z-]+ \[" | cut -c1-150
chrome-devtools stop
pkill -f "node server.mjs"
你应该看到:
text
4:.hero { max-width: 100%; height: auto; }
- Accessibility: 82 (accessibility)
- Best Practices: 96 (best-practices)
- SEO: 91 (seo)
- Agentic Browsing: 50 (agentic-browsing)
Passed: 35
Failed: 5
- errors-in-console [best-practices]: Browser errors were logged to the console (score: 0)
- button-name [accessibility]: Buttons do not have an accessible name (score: 0)
- color-contrast [accessibility]: Background and foreground colors do not have a sufficient contrast ratio. (score: 0)
- meta-description [seo]: Document does not have a meta description (score: 0)
- agent-accessibility-tree [agentic-browsing]: Accessibility tree is not well-formed (score: 0)
pkill 会杀掉所有 node server.mjs,机器上有同名进程的话请按端口杀。无障碍 72 到 82,SEO 82 到 91,Best Practices 回到 96,没过的从 7 项降到 5 项,剩下的几项我没改。
接下来可以把 prompt.txt 换成你自己页面的 URL 和一个具体问题,再把 trace 加 Lighthouse 放进 CI 当回归检查;想看源码,工具定义在仓库 src/tools 目录下,每个工具的 readOnlyHint 就写在那里。
三、实测复盘:它抓得准的,和三件不能直接信的
1. 抓得准的部分
事实层面,它几乎没出过错:六条控制台错误、500 的响应体、跨域被拦的原文、favicon 404、vendor.js 阻塞 1510 毫秒、按钮没名字、对比度 1.91,全部和我埋的一一对上,堆栈能精确到行列。这一层的输出是"浏览器自己看到了什么",没有推理的环节,每一条我都能在服务端日志或页面源码里对上,所以可信度很高。Lighthouse 那几项同理,它是规则检查,不是判断,我拿它和自己埋的坑逐条对账,没有误报,也没漏掉控制台和网络类的问题。有一个我没读懂的地方:这版 Lighthouse 多了一个 Agentic Browsing 类别,我的页面得 45 分,修复后 50 分,CLS 和 agent-accessibility-tree 都算在这一类里,后者始终没过。我没去读它的规则,不敢解释它在查什么。
2. 归因层面:CLS 的 insight 把锅甩给了图片
先说一个容易漏掉的事实:trace 里的 CLS 只有 0.05,在 0.1 的"良好"线以内,在 trace 眼里这页的偏移算不上问题;Lighthouse 给的 0.103 才刚过线。所以我的页面严格说是个边界案例,下面的结论在偏移严重的页面上会不会成立,我没有数据。
CLSCulprits 的结论是"一张没写尺寸的图片"。图片确实没写尺寸,这句话单看没错,但它不是这个页面偏移的原因,变量实验已经给出答案:只修图片,CLS 不动;只给横幅留位置,CLS 归零。我读了输出的措辞,它说的是 "Potential root causes",工具本身没有骗人,问题出在 Agent 把潜在原因当成了结论,写进修复清单。我没去读它的归因规则,只能说它的结论和实验对不上。
这件事我也没法替人类辩护,换一个工程师多半也会先去改那张图。区别在于人改完会再看一眼数字,Agent 在这次任务里没有这一步。验证办法很笨但有效:每个可疑因素单独做一个版本,各录一次 trace,数字动了才算数。
3. 看不见的两样:长任务和请求耗时
700 毫秒的长任务没有出现在任何一个 insight 里,网络请求列表里也没有耗时,慢请求在进行中只显示 [pending]。这两样我都靠 evaluate_script 现写代码补上。我的理解是 trace 里数据是有的:渲染延迟 2255 毫秒,和 vendor.js 的 1.5 秒加长任务的 0.7 秒大致吻合,只是默认的 insight 没把它们摆出来。这两个问题各占多少,我没有单独验证,只验证了全部修复后 LCP 掉到 84 毫秒。
另外 trace 里的"预计节省 0 毫秒"是 localhost 的假象,本地回环没有网络开销,别当真。如果你打算让 Agent 做性能排查,我的建议是把上面那段 PerformanceObserver 做成固定模板,每次都让它跑一遍,不要指望 insight 自己会提。
4. 一次完整的 Agent 会话是怎么走的
回头看 Codex 那十四次调用,有个细节:它追问了 LCPBreakdown、LCPDiscovery、CLSCulprits、RenderBlocking、ImageDelivery 五个 insight,没问 NetworkDependencyTree 和 Cache;evaluate_script 和 lighthouse_audit 一次也没调。上一次完整重放里它的追问顺序和这次不同,也一样没调这两个。能补上长任务和耗时这两个洞的工具就在 33 个里面,它没用。我的解读是,insight 的返回里没有任何东西提示"这里还有没看到的东西",Agent 只会在已有的线索里往下追,线索断了就停。这是两次运行得出的印象,不是统计结论。
5. 工具层面的几处不整齐
命令行少两个工具,文档却写着支持全部。33 个工具里只有 8 个声明只读,所以 Agent 想无人值守地跑,要么手动逐个放行,要么像我这样整体设成 approve。approve 之后包括 evaluate_script 在内的所有工具都不再问,Agent 在你的浏览器里想执行什么脚本就执行什么脚本。我在 --isolated 的临时 profile 里这么做问题不大,换成真实登录态的浏览器就是另一回事了,而 --autoConnect 的文档也提醒过:它会连上用户的默认 profile,能访问该 profile 下所有打开的窗口。
还有 Codex 那次是单次运行。Agent 的步骤顺序、追问哪个 insight、最后怎么写,每次都可能不一样,我这篇里关于"Agent 复述了 trace 的误判"只对这一次成立,只是它和我手工查的结果一致。
四、我没跑的,和跑不了的
没跑的先说清楚。npx chrome-devtools-mcp@latest 这条官方推荐的安装路径我没跑,只用 npm view 看了版本,所以安装耗时只能估计:不用克隆和 gclient,应该比我的两分钟快得多,但我没计时。--autoConnect 和带登录态的 profile 需要一个真正开着的 Chrome(要在 chrome://inspect 里开远程调试),那是图形界面加人工点击的流程,我的机器没有桌面,跑不了;同理,headful 模式、需要登录的页面也没测。
可选类别里的扩展、PWA、WebAuthn、WebMCP、第三方开发者工具、网络请求模拟,set_logpoints 和堆快照的其他分析工具,我都没有打开。客户端只试了 Codex 一个,Gemini、Claude、Cursor 等没试。CrUX 的真实用户数据和使用统计我关掉了,所以不知道开着时返回会多出什么。平台只有 Linux,Windows 和 macOS 上的路径、沙箱行为我不知道。
还有几处是数据缺口。我没统计 token 消耗,所以一次完整会话花多少 token 说不出来。我的页面只有一页、一百多行,真实大站录出的 trace 有多大、Agent 的上下文会不会被撑爆,没有数据。Codex 之外的客户端里,工具返回的文本是被原样展示还是被截断,我没看过,所以"摘要够不够用"的判断只来自这一个客户端。我也没在同一页面上跑过 Playwright MCP 之类的同类工具,下面的比较只能是定性的;prompt 我只写了一版,明确要求"每个怀疑项单独验证"会不会让 Agent 自己做变量实验,同样没试。
五、我的判断:它是个靠谱的观察员,不是个靠谱的诊断员
先说好的地方。输出克制,摘要加路径的设计在实际使用里确实省了上下文,十几次调用里没有刷屏;一个进程里能同时拿到控制台、网络、trace、Lighthouse、堆快照,Agent 不用在几个工具之间倒腾;失败时的报错对 Agent 友好,我敲错参数那次它直接告诉我正确写法。
缺点也很具体。CLSCulprits 给出的潜在原因会被 Agent 当成结论,我这页里它是错的。长任务和请求耗时默认看不见,要自己补 evaluate_script。只读标注太少,让无人值守的 Agent 要么卡住要么被整体放权。命令行和 MCP 的工具集对不上,文档却写着支持全部。源码构建要 5.5 GB 和两分钟,不适合想随手试试的人。还有默认开着的使用统计和 CrUX 上报,用之前要先决定。
有一点是我事先没想到的:命令行这一半不接模型也很好用。daemon 常驻,页面状态接得上,我这篇里大半步骤是用 shell 一条条敲出来的,这意味着你可以把它当成一个可脚本化的浏览器遥控器,在 CI 里取 trace 和 Lighthouse 分数,不用让模型参与。适用场景我划得比较窄:开发期的页面自测和回归检查。相比手动开 DevTools 面板,它的好处是可重复、可脚本化,缺点是少了人眼的探索;相比单独跑 Lighthouse,它多了控制台、网络、点击和 trace 的交互。具体到团队里,我会把它放在三个位置:前端改完后让 Agent 打开本地页面扫一遍控制台和网络,当成提 PR 前的自测;用户报了页面问题,让它先复现并留下截图和控制台记录,这一步只需要事实层;性能回归,用命令行在 CI 里录 trace 和 Lighthouse 分数。这三处都不要求它下结论。我不建议把它的 insight 当最终诊断去交付,也不建议在真实登录态的浏览器上给它 approve 权限。所以我的用法是:让它负责收集事实,让人,或者再给 Agent 一个变量实验的任务,负责归因。
六、写在最后
回头看这一路,Agent 加 DevTools 的组合,在"发生了什么"上很省事:十四次调用,控制台、网络、trace、点击一次走完,每一条都能对上我埋的坑。但在"为什么发生"上,它和我一样,第一反应都是去改那张图,而且它不会自己去做变量实验。工具把现场搬得越完整,越容易让人觉得结论也是现成的,可结论这一步,从头到尾没有被工具接手。还有一点是我这次才注意到的:给 Agent 用的观测工具,输出的措辞本身就成了接口的一部分。人读到 "Potential root causes" 会下意识打个问号,模型读到的是一条可以直接抄进修复清单的原因,这个落差得由使用者去补。
开头那个问题,我现在的答案是:事实层可以信到十成,归因层只能当线索。线索的意思,是把它给的原因当成一个待验证的假设,改一个变量,再测一遍,数字动了才算数。我这次就是靠四个端口的对照,才给那张图洗清了嫌疑。另外,这类工具的价值很大程度取决于你怎么给任务。我这次的 prompt 只说了"报告原因",没说"证明原因",它就停在了线索上。往后我给 Agent 派这类活,会把"每个怀疑项单独做一个版本再比数字"写进任务本身,而不是等它自己想到。
工具能把现场原样搬给你,谁是真凶,还得你亲手改一遍才知道。