chrome-devtools-mcp icon indicating copy to clipboard operation
chrome-devtools-mcp copied to clipboard

Page ids silently rebind to different pages after a browser restart

Open thomasbachem opened this issue 4 months ago • 2 comments

Description of the bug

In --browserUrl mode the server survives a browser restart nicely – tools error cleanly while the browser is down, and the next call reconnects. But the reconnect builds a fresh McpContext, so page ids start over at 1: Whatever pages the restarted browser opens get the same ids the old pages had. A client that re-uses an id from before the restart doesn't get an error – it gets a different page.

The selection fallback note from #2308 doesn't fire either, since the fresh context treats the reconnect as a first connect – so there is no signal at all. And when the browser bounces between two tool calls (a crash, a "Relaunch to update", an app relaunch), the client never even sees a failing call in between. It's the same failure mode as #2304 one level up – for an agent, plausible results from the wrong page are worse than an error.

We happen to hit this daily driving an Electron app that relaunches during development, but there is nothing Electron-specific about it – any browser restart under a long-lived session does the same, and the reproduction below is plain headless Chrome.

Reproduction

Verified with plain headless Chrome:

  1. Connect via --browserUrl, new_page a second page – the listing shows 1: pageA / 2: pageB [selected]
  2. Kill the browser and start a new one on the same port with two different pages (C, D)
  3. select_page with the stale id 2 – succeeds silently, [selected] lands on pageD
  4. evaluate_script with () => document.title – returns "pageD", no error, no note

Expectation

Page ids were introduced as stable handles (#688) – stale ones should fail loudly rather than resolve to unrelated pages, consistent with the "No page found" contract:

  • Seed the new context's page id counter from the previous one on reconnect – an id from before the restart is then simply not found, and the agent re-lists and recovers in one turn
  • Ideally also surface a one-time note in the first response after a reconnect ("reconnected to the browser, page ids have changed"), like the #2308 fallback note

MCP configuration

{
	"command": "npx",
	"args": ["[email protected]", "--browserUrl", "http://127.0.0.1:9339"]
}

Chrome DevTools MCP version

1.5.0 – reproduced identically on current main

Chrome version

Chrome 150 (headless) – originally observed against Electron 43 (Chromium 150)

Coding agent version

n/a – reproduces deterministically with a scripted MCP stdio client

Model version

No response

Chat log

No response

Node version

v22.22.2

Operating system

macOS

Extra checklist

  • [x] I want to provide a PR to fix this bug

thomasbachem avatar Jul 10 '26 06:07 thomasbachem

Hi, i was not able to repro your issue on 1.5.0, for me it shows Error: No page found Maybe you can specify details that will help me verify it?

nattallius avatar Jul 10 '26 17:07 nattallius

Thanks for checking! The restarted browser needs to come back with at least two pages before the stale id is re-used – with a single page, id 2 is genuinely unknown and No page found is the correct result. I get exactly that when I drop the second page from the script below.

One gotcha from my own attempts: A fresh headless Chrome launched with two URL arguments doesn't come up serving CDP for me (ECONNREFUSED), so the script opens the second page via PUT /json/new.

Self-contained repro (Node ≥ 20, spawns the MCP server against a throwaway headless Chrome)
// Usage: node repro-stale-ids.mjs [path-to-chrome-devtools-mcp.js]
import {spawn} from 'node:child_process';
import {existsSync} from 'node:fs';
import {createServer} from 'node:http';
import {setTimeout as wait} from 'node:timers/promises';

const CHROME = process.env.CHROME ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const MCP = process.argv[2] ?? 'node_modules/chrome-devtools-mcp/build/src/bin/chrome-devtools-mcp.js';
const PORT = 9339;
if (!existsSync(MCP) || !existsSync(CHROME)) {
  console.error('Server or Chrome not found – pass the server path as argument, Chrome via CHROME env');
  process.exit(1);
}

// Local pages so the tabs are distinguishable
const server = createServer((req, res) => {
  res.setHeader('content-type', 'text/html');
  res.end(`<title>page${req.url.replace('/', '')}</title>`);
});
server.listen(8898);

let profileN = 0;
const launchChrome = url => spawn(CHROME, ['--headless=new', `--remote-debugging-port=${PORT}`,
  `--user-data-dir=/tmp/stale-ids-${process.pid}-${++profileN}`, '--no-first-run', url], {stdio: 'ignore'});
let chrome = launchChrome('http://127.0.0.1:8898/A');
await wait(2000);

const mcp = spawn(process.execPath, [MCP, '--browserUrl', `http://localhost:${PORT}`], {stdio: ['pipe', 'pipe', 'ignore']});
let buffer = '';
const pending = new Map();
mcp.stdout.on('data', chunk => {
  buffer += chunk;
  for (let nl; (nl = buffer.indexOf('\n')) >= 0; ) {
    const line = buffer.slice(0, nl); buffer = buffer.slice(nl + 1);
    try { const msg = JSON.parse(line); pending.get(msg.id)?.(msg); pending.delete(msg.id); } catch {}
  }
});
let nextId = 1;
const send = (method, params) => new Promise(resolve => {
  const id = nextId++; pending.set(id, resolve);
  mcp.stdin.write(JSON.stringify({jsonrpc: '2.0', id, method, params}) + '\n');
});
const text = r => (r.result?.content?.map(c => c.text).join('\n') ?? '')
  .split('\n').filter(l => /^\d+:|Error|Note/.test(l)).join('\n');

await send('initialize', {protocolVersion: '2024-11-05', capabilities: {}, clientInfo: {name: 'repro', version: '1.0'}});
mcp.stdin.write(JSON.stringify({jsonrpc: '2.0', method: 'notifications/initialized'}) + '\n');

console.log('1. Before – agent works with id 2 (pageB):');
await send('tools/call', {name: 'new_page', arguments: {url: 'http://127.0.0.1:8898/B'}});
console.log(text(await send('tools/call', {name: 'list_pages', arguments: {}})));

console.log('\n2. Browser restarts with two different pages (C, D)...');
chrome.kill('SIGKILL');
await wait(1500);
chrome = launchChrome('http://127.0.0.1:8898/C');
await wait(3000);
// Second page via CDP – passing two URLs to a fresh headless Chrome didn't reliably serve CDP for me
await fetch(`http://127.0.0.1:${PORT}/json/new?http://127.0.0.1:8898/D`, {method: 'PUT'});
await wait(1000);

console.log('\n3. Stale select_page(2) – was pageB:');
console.log(text(await send('tools/call', {name: 'select_page', arguments: {pageId: 2}})));

console.log('\n4. evaluate_script document.title on the "same" page 2:');
const evalResult = await send('tools/call', {name: 'evaluate_script', arguments: {function: '() => document.title'}});
const evalText = evalResult.result?.content?.map(c => c.text).join(' ') ?? '';
console.log('returned ' + (evalText.match(/"[^"]+"/)?.[0] ?? evalText.slice(0, 80)));

mcp.kill(); chrome.kill('SIGKILL'); server.close();
spawn('bash', ['-c', `rm -rf /tmp/stale-ids-${process.pid}-*`]);
process.exit(0);

Output on macOS (Chrome 150, chrome-devtools-mcp 1.5.0) – which of C/D lands on the stale id varies with enumeration order:

1. Before – agent works with id 2 (pageB):
1: pageA (http://127.0.0.1:8898/A)
2: pageB (http://127.0.0.1:8898/B) [selected]

2. Browser restarts with two different pages (C, D)...

3. Stale select_page(2) – was pageB:
1: pageD (http://127.0.0.1:8898/D)
2: pageC (http://127.0.0.1:8898/C) [selected]

4. evaluate_script document.title on the "same" page 2:
returned "pageC"

thomasbachem avatar Jul 11 '26 04:07 thomasbachem