chrome-bridge-mcp 1.26.0 → 1.28.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.
@@ -13,7 +13,8 @@ import { computeTiles } from './lib/tile-layout.js';
13
13
  import { classifyDownload } from './lib/download-state.js';
14
14
  import { findTextInPage } from './lib/find-text.js';
15
15
  import { elementOutcome, watchNavErrors, navErrorMessage } from './lib/command-outcome.js';
16
- import { withDebugger, keyEvents, mouseClickEvents } from './lib/trusted-input.js';
16
+ import { withDebugger, keyEvents, mouseClickEvents, holdDebugger, releaseDebugger, debuggerHeld } from './lib/trusted-input.js';
17
+ import { emulationCommands } from './lib/emulation.js';
17
18
  const { pushError } = globalThis.__cbTelemetry;
18
19
 
19
20
  const DEFAULT_PORT = 8765;
@@ -98,7 +99,38 @@ const KEEPALIVE_ALARM = 'chrome-bridge-keepalive';
98
99
  let ws = null;
99
100
  let reconnectTimer = null;
100
101
  let reconnectDelay = RECONNECT_BASE_MS;
101
- let connectionState = 'disconnected'; // 'connected' | 'connecting' | 'disconnected'
102
+ let connectionState = 'disconnected'; // 'connected' | 'connecting' | 'disconnected' | 'refused'
103
+ // Rifiutata perché un altro browser tiene la porta: si riprova piano, senza
104
+ // riempire il log del server a ogni secondo.
105
+ const REFUSED_RETRY_MS = 15000;
106
+ let refusedBy = null;
107
+
108
+ // Identità del browser per il server: un id che resta fra un riavvio e
109
+ // l'altro (lo stesso browser che si riconnette sostituisce la sua vecchia
110
+ // connessione, un altro browser no) e un'etichetta leggibile in get_status.
111
+ // Calcolata una volta: all'apertura del socket l'ext_init deve partire
112
+ // subito, o il server chiude la connessione non identificata (sotto carico lo
113
+ // storage può metterci secondi). Prima di loadConfig launchMode non è noto:
114
+ // si chiede dopo il primo connect.
115
+ let identityPromise = null;
116
+ function cachedIdentity() {
117
+ identityPromise ??= browserIdentity().catch(() => ({ id: null, label: 'Chromium-based browser' }));
118
+ return identityPromise;
119
+ }
120
+
121
+ async function browserIdentity() {
122
+ let { browserId } = await chrome.storage.local.get({ browserId: null });
123
+ if (!browserId) {
124
+ browserId = crypto.randomUUID();
125
+ await chrome.storage.local.set({ browserId });
126
+ }
127
+ const brands = navigator.userAgentData?.brands ?? [];
128
+ const brand = brands.find((b) => !/Not.?A.?Brand|^Chromium$/i.test(b.brand)) ?? brands.find((b) => /Chromium/i.test(b.brand));
129
+ const os = (await chrome.runtime.getPlatformInfo().catch(() => null))?.os ?? navigator.userAgentData?.platform ?? '';
130
+ const label = [brand ? `${brand.brand} ${brand.version}` : 'Chromium-based browser', os && `on ${os}`, launchMode && '(launch mode)']
131
+ .filter(Boolean).join(' ');
132
+ return { id: browserId, label };
133
+ }
102
134
 
103
135
  let serverVersion = null;
104
136
  let sessionStats = { toolCallCount: 0, lastTool: null, lastToolTs: null, recentErrors: [] };
@@ -183,6 +215,7 @@ function connect() {
183
215
  }
184
216
 
185
217
  setConnectionState('connecting');
218
+ cachedIdentity();
186
219
 
187
220
  try {
188
221
  ws = new WebSocket(wsUrl);
@@ -194,12 +227,14 @@ function connect() {
194
227
 
195
228
  const socket = ws;
196
229
 
197
- ws.onopen = () => {
230
+ ws.onopen = async () => {
198
231
  console.log('[chrome-bridge] Connected to MCP server');
199
- const init = { type: 'ext_init', version: chrome.runtime.getManifest().version };
232
+ const init = { type: 'ext_init', version: chrome.runtime.getManifest().version, browser: await cachedIdentity() };
200
233
  if (extToken) init.token = extToken;
201
- ws.send(JSON.stringify(init));
234
+ if (socket.readyState !== WebSocket.OPEN) return;
235
+ socket.send(JSON.stringify(init));
202
236
  setConnectionState('connected');
237
+ refusedBy = null;
203
238
  reconnectDelay = RECONNECT_BASE_MS; // Reset backoff
204
239
  };
205
240
 
@@ -208,7 +243,7 @@ function connect() {
208
243
  console.log('[chrome-bridge] Disconnected from MCP server');
209
244
  ws = null;
210
245
  serverVersion = null;
211
- setConnectionState('disconnected');
246
+ setConnectionState(refusedBy ? 'refused' : 'disconnected');
212
247
  scheduleReconnect();
213
248
  };
214
249
 
@@ -232,6 +267,12 @@ function connect() {
232
267
  return;
233
268
  }
234
269
 
270
+ if (msg.type === 'ext_init_refused') {
271
+ refusedBy = msg.connected || 'another browser';
272
+ console.warn(`[chrome-bridge] Refused: ${msg.reason}`);
273
+ return;
274
+ }
275
+
235
276
  // Handshake: il server dichiara la sua versione
236
277
  if (msg.type === 'ext_init_ok') {
237
278
  serverVersion = msg.version || null;
@@ -270,7 +311,7 @@ function scheduleReconnect() {
270
311
  reconnectTimer = setTimeout(() => {
271
312
  reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
272
313
  connect();
273
- }, reconnectDelay);
314
+ }, refusedBy ? REFUSED_RETRY_MS : reconnectDelay);
274
315
  }
275
316
 
276
317
  function sendMessage(obj) {
@@ -449,6 +490,18 @@ async function executeCommand(msg) {
449
490
  return await cmdScreenshotDiff(params);
450
491
  case 'web_vitals':
451
492
  return await cmdWebVitals(params);
493
+ case 'motion':
494
+ return await cmdMotion(params);
495
+ case 'perf_trace':
496
+ return await cmdPerfTrace(params);
497
+ case 'screencast':
498
+ return await cmdScreencast(params);
499
+ case 'cdp_target':
500
+ return await cmdCdpTarget(params);
501
+ case 'upload_chunk':
502
+ return await cmdUploadChunk(params);
503
+ case 'handoff_end':
504
+ return await cmdHandoffEnd(params);
452
505
  case 'list_event_listeners':
453
506
  return await cmdListEventListeners(params);
454
507
  case 'monitor_websocket':
@@ -940,7 +993,10 @@ async function trustedTarget(tabId, frame_id, selector, what) {
940
993
  const el = sel ? deepQuery(sel) : (document.activeElement || document.body);
941
994
  if (!el) return { missing: true };
942
995
  if (kind === 'point') {
943
- el.scrollIntoView({ block: 'center', inline: 'center' });
996
+ // instant: con scroll-behavior: smooth nella pagina il rettangolo letto
997
+ // subito dopo è a metà scorrimento, e il puntatore finiva su un altro
998
+ // elemento (francescosorrentino.com/strumenti, 01/10/2026).
999
+ el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
944
1000
  const r = el.getBoundingClientRect();
945
1001
  const x = r.left + r.width / 2; const y = r.top + r.height / 2;
946
1002
  const top = document.elementFromPoint(x, y);
@@ -973,6 +1029,15 @@ async function trustedClick(tabId, { selector, frame_id, force, button, count })
973
1029
  return { clicked: true, trusted: true, button, count, tagName: t.tagName, text: t.text };
974
1030
  }
975
1031
 
1032
+ // Passaggio del mouse fidato: solo un mouseMoved del browser accende il
1033
+ // :hover del CSS; gli eventi sintetici di cmdHover lo lasciano spento, e una
1034
+ // transizione al passaggio del mouse non parte (animations sul sito, 01/10).
1035
+ async function trustedHover(tabId, { selector, frame_id }) {
1036
+ const t = await trustedTarget(tabId, frame_id, selector, 'point');
1037
+ await withDebugger(tabId, (send) => send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: t.x, y: t.y }));
1038
+ return { hovered: true, trusted: true, tagName: t.tagName, ...(t.occluded && { occluded_by: t.occluder }) };
1039
+ }
1040
+
976
1041
  async function trustedType(tabId, { selector, text, frame_id }) {
977
1042
  const t = await trustedTarget(tabId, frame_id, selector, 'select');
978
1043
  await withDebugger(tabId, (send) => send('Input.insertText', { text }));
@@ -2741,6 +2806,19 @@ async function cmdHandoff({ message, pick_element = false, ask = false, pick_max
2741
2806
  });
2742
2807
  }
2743
2808
 
2809
+ // handoff_end: l'utente ha risposto nel terminale (elicitation MCP) prima che
2810
+ // nella pagina. Il banner va tolto e l'handoff in attesa finisce con quella
2811
+ // risposta, così la chiamata handoff originale ritorna una sola volta.
2812
+ async function cmdHandoffEnd({ action = 'done', answer, tab_id }) {
2813
+ const tabId = await resolveTabId(tab_id);
2814
+ const entry = handoffs.get(tabId);
2815
+ if (!entry) return { ended: false };
2816
+ try { await chrome.scripting.executeScript({ target: { tabId }, func: () => document.getElementById('cb-handoff-host')?.remove() }); } catch { /* tab chiusa */ }
2817
+ const tab = await chrome.tabs.get(tabId).catch(() => null);
2818
+ entry.resolve({ done: action === 'done', action, url: tab?.url ?? null, via: 'terminal', ...(typeof answer === 'string' && { answer }) });
2819
+ return { ended: true };
2820
+ }
2821
+
2744
2822
  // --- keyboard_walk ---
2745
2823
  // Ordine di tabulazione calcolato (tabindex>0 crescente, poi ordine DOM) e
2746
2824
  // focus programmatico elemento per elemento. NON sono veri tasti Tab: un
@@ -3263,8 +3341,53 @@ async function cmdWatchDom({ selector = 'body', attributes = true, childList = t
3263
3341
 
3264
3342
  // --- emulate_media ---
3265
3343
 
3266
- async function cmdEmulateMedia({ colorScheme, reducedMotion, printMode = false, user_agent = null, reset = false, tab_id }) {
3344
+ // Emulazione via debugger: vive finché il debugger resta agganciato, quindi la
3345
+ // scheda è «tenuta» fino a reset (o finché l'utente annulla la barra). Lo stato
3346
+ // si accumula fra le chiamate e si rimanda per intero: setEmulatedMedia
3347
+ // sostituisce l'elenco delle preferenze, non lo integra.
3348
+ const emulationState = new Map();
3349
+ const CDP_ONLY = ['contrast', 'cpu_throttle', 'network', 'device', 'touch'];
3350
+
3351
+ async function cmdEmulateMedia(params) {
3352
+ const { via, reset = false, user_agent = null, tab_id } = params;
3267
3353
  const tabId = await resolveTabId(tab_id);
3354
+ if (reset) {
3355
+ const released = await releaseDebugger(tabId, 'emulation');
3356
+ emulationState.delete(tabId);
3357
+ await cmdEmulateMediaPage({ reset: true, tabId });
3358
+ return { reset: true, ...(released && { debugger_released: true }) };
3359
+ }
3360
+ const cdpOnly = CDP_ONLY.filter((k) => params[k] != null);
3361
+ const useDebugger = via === 'debugger' || (via !== 'page' && cdpOnly.length > 0);
3362
+ if (!useDebugger) {
3363
+ if (cdpOnly.length) throw new Error(`${cdpOnly.join(', ')} need via: "debugger"`);
3364
+ return cmdEmulateMediaPage({ ...params, tabId });
3365
+ }
3366
+ if (params.reducedMotion || params.colorScheme || params.printMode) {
3367
+ // Il ripiego nella pagina sovrascriverebbe le regole del sito: via
3368
+ // debugger si toglie, così valgono le @media vere.
3369
+ await cmdEmulateMediaPage({ reset: true, tabId }).catch(() => {});
3370
+ }
3371
+ if (!debuggerHeld(tabId).held) emulationState.delete(tabId);
3372
+ const prev = emulationState.get(tabId) ?? {};
3373
+ const pick = Object.fromEntries(['colorScheme', 'reducedMotion', 'contrast', 'cpu_throttle', 'network', 'device', 'touch']
3374
+ .filter((k) => params[k] != null).map((k) => [k, params[k]]));
3375
+ if (params.printMode) pick.printMode = true;
3376
+ const merged = { ...prev, ...pick };
3377
+ const { commands, emulated } = emulationCommands(merged);
3378
+ const send = await holdDebugger(tabId, 'emulation', 'emulate_media via debugger');
3379
+ for (const [method, p] of commands) await send(method, p);
3380
+ emulationState.set(tabId, merged);
3381
+ const out = {
3382
+ emulated,
3383
+ via: 'debugger',
3384
+ debugger_bar: 'Chrome shows a "started debugging this browser" bar until emulate_media reset: true; cancelling it ends the emulation',
3385
+ };
3386
+ if (user_agent) out.user_agent = (await cmdEmulateMediaPage({ user_agent, tabId })).emulated?.userAgent ?? user_agent;
3387
+ return out;
3388
+ }
3389
+
3390
+ async function cmdEmulateMediaPage({ colorScheme, reducedMotion, printMode = false, user_agent = null, reset = false, tabId }) {
3268
3391
 
3269
3392
  const results = await chrome.scripting.executeScript({
3270
3393
  target: { tabId },
@@ -3383,9 +3506,10 @@ async function cmdEmulateMedia({ colorScheme, reducedMotion, printMode = false,
3383
3506
 
3384
3507
  // --- hover ---
3385
3508
 
3386
- async function cmdHover({ selector, tab_id, frame_id }) {
3509
+ async function cmdHover({ selector, tab_id, frame_id, trusted = false }) {
3387
3510
  if (!selector) throw new Error('Missing required parameter: selector');
3388
3511
  const tabId = await resolveTabId(tab_id);
3512
+ if (trusted) return trustedHover(tabId, { selector, frame_id });
3389
3513
 
3390
3514
  const results = await chrome.scripting.executeScript({
3391
3515
  target: scriptTarget(tabId, frame_id),
@@ -3508,27 +3632,55 @@ async function cmdGetFrames({ tab_id }) {
3508
3632
 
3509
3633
  // --- upload_file ---
3510
3634
 
3511
- async function cmdUploadFile({ selector, name, mime_type, content_b64, tab_id }) {
3635
+ // upload_chunk: i file oltre 6 MB arrivano a pezzi (server/upload.js). La
3636
+ // pagina li tiene in window.__cbUploads finché upload_file li monta, o un
3637
+ // abort li butta.
3638
+ async function cmdUploadChunk({ upload_id, index, total, content_b64, abort = false, tab_id }) {
3639
+ if (!upload_id) throw new Error('Missing required parameter: upload_id');
3640
+ const tabId = await resolveTabId(tab_id);
3641
+ const results = await chrome.scripting.executeScript({
3642
+ target: { tabId },
3643
+ func: (id, i, n, b64, drop) => {
3644
+ const all = (window.__cbUploads ??= {});
3645
+ if (drop) { delete all[id]; return { aborted: true }; }
3646
+ const u = (all[id] ??= { parts: [], total: n });
3647
+ u.parts[i] = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
3648
+ return { received: i + 1, total: n };
3649
+ },
3650
+ args: [upload_id, index ?? 0, total ?? 1, content_b64 ?? '', abort],
3651
+ world: 'MAIN',
3652
+ });
3653
+ return results?.[0]?.result ?? { received: 0 };
3654
+ }
3655
+
3656
+ async function cmdUploadFile({ selector, name, mime_type, content_b64, upload_id, size, tab_id }) {
3512
3657
  if (!selector) throw new Error('Missing required parameter: selector');
3513
- if (!content_b64) throw new Error('Missing required parameter: content_b64');
3658
+ if (!content_b64 && !upload_id) throw new Error('Missing required parameter: content_b64');
3514
3659
  const tabId = await resolveTabId(tab_id);
3515
3660
  const results = await chrome.scripting.executeScript({
3516
3661
  target: { tabId },
3517
- func: (sel, fname, mime, b64) => {
3662
+ func: (sel, fname, mime, b64, id, expected) => {
3663
+ const pieces = id ? window.__cbUploads?.[id] : null;
3664
+ if (id) delete window.__cbUploads?.[id];
3518
3665
  const el = document.querySelector(sel);
3519
3666
  if (!el) throw new Error(`Element not found: ${sel}`);
3520
3667
  // Un throw qui si perderebbe (elementOutcome lo leggerebbe come «not found»): esito esplicito.
3521
3668
  if (!(el instanceof HTMLInputElement) || el.type !== 'file') return { uploaded: false, error: 'Element is not an input[type=file]' };
3522
- const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
3669
+ if (id && (!pieces || pieces.parts.filter(Boolean).length !== pieces.total)) {
3670
+ return { uploaded: false, error: `Upload ${id} incomplete: ${pieces ? pieces.parts.filter(Boolean).length : 0}/${pieces?.total ?? '?'} pieces (page reloaded meanwhile?)` };
3671
+ }
3672
+ const bytes = id ? new Blob(pieces.parts) : Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
3673
+ const length = id ? bytes.size : bytes.length;
3674
+ if (id && expected != null && length !== expected) return { uploaded: false, error: `Upload ${id}: ${length} bytes arrived, ${expected} expected` };
3523
3675
  const file = new File([bytes], fname, { type: mime });
3524
3676
  const dt = new DataTransfer();
3525
3677
  dt.items.add(file);
3526
3678
  el.files = dt.files;
3527
3679
  el.dispatchEvent(new Event('input', { bubbles: true }));
3528
3680
  el.dispatchEvent(new Event('change', { bubbles: true }));
3529
- return { uploaded: fname, size: bytes.length, mime };
3681
+ return { uploaded: fname, size: length, mime, ...(id && { pieces: pieces.total }) };
3530
3682
  },
3531
- args: [selector, name, mime_type, content_b64],
3683
+ args: [selector, name, mime_type, content_b64 ?? null, upload_id ?? null, size ?? null],
3532
3684
  world: 'MAIN',
3533
3685
  });
3534
3686
  return elementOutcome(results, selector);
@@ -3986,6 +4138,164 @@ async function cmdWebVitals({ tab_id }) {
3986
4138
  return results?.[0]?.result ?? { available: false };
3987
4139
  }
3988
4140
 
4141
+ // --- motion (animations, frames) ---
4142
+
4143
+ // lib/motion.js tiene la logica (testata in Node); qui solo l'iniezione. Una
4144
+ // finestra di registrazione su pagina nascosta misurerebbe il nulla: rAF e
4145
+ // osservatori si fermano, quindi start rifiuta invece di restituire zeri.
4146
+ async function cmdMotion({ op, scope = null, limit, threshold_ms, tab_id, frame_id }) {
4147
+ const tabId = await resolveTabId(tab_id);
4148
+ if (op === 'start' && await pageHidden(tabId)) throw new Error(`Not recording: ${HIDDEN_HINT}`);
4149
+ const target = scriptTarget(tabId, frame_id);
4150
+ if (op !== 'stop') await chrome.scripting.executeScript({ target, files: ['lib/motion.js'], world: 'MAIN' });
4151
+ const results = await chrome.scripting.executeScript({
4152
+ target,
4153
+ func: (o, opts) => {
4154
+ const m = globalThis.__cbMotion;
4155
+ if (!m) return { error: 'No recording in this page: it was never started, or the page navigated and lost it.' };
4156
+ return m[o](opts);
4157
+ },
4158
+ args: [op, { scope, ...(limit != null && { limit }), ...(threshold_ms != null && { threshold_ms }) }],
4159
+ world: 'MAIN',
4160
+ });
4161
+ const out = results?.[0]?.result;
4162
+ if (out?.error) throw new Error(out.error);
4163
+ return out;
4164
+ }
4165
+
4166
+ // --- perf_trace ---
4167
+
4168
+ // Categorie del pannello Performance di DevTools (come chrome-devtools-mcp),
4169
+ // senza gli screenshot che gonfiano il file. Il trace torna come stream: il
4170
+ // server lo legge a pezzi (op read) e lo scrive su disco, così nel service
4171
+ // worker non resta mai tutto in memoria.
4172
+ const TRACE_CATEGORIES = [
4173
+ '-*', 'blink.console', 'blink.user_timing', 'devtools.timeline', 'disabled-by-default-devtools.timeline',
4174
+ 'disabled-by-default-devtools.timeline.frame', 'disabled-by-default-devtools.timeline.stack',
4175
+ 'disabled-by-default-devtools.timeline.invalidationTracking', 'disabled-by-default-v8.cpu_profiler',
4176
+ 'latencyInfo', 'loading', 'disabled-by-default-lighthouse', 'v8.execute', 'v8',
4177
+ ];
4178
+ const traces = new Map(); // tabId → { complete: Promise<handle>, stream }
4179
+
4180
+ chrome.debugger.onEvent.addListener((source, method, params) => {
4181
+ if (method === 'Tracing.tracingComplete') {
4182
+ const t = traces.get(source.tabId);
4183
+ if (t) t.resolveComplete(params.stream);
4184
+ } else if (method === 'Page.screencastFrame') {
4185
+ const c = casts.get(source.tabId);
4186
+ // L'ack va mandato sempre, o Chrome smette di inviare fotogrammi.
4187
+ chrome.debugger.sendCommand({ tabId: source.tabId }, 'Page.screencastFrameAck', { sessionId: params.sessionId }).catch(() => {});
4188
+ if (!c) return;
4189
+ c.frames.push({ data: params.data, t: params.metadata?.timestamp ?? Date.now() / 1000 });
4190
+ c.total += 1;
4191
+ // Il server drena ogni 400 ms: se smette (server caduto), il buffer non
4192
+ // cresce senza limite.
4193
+ if (c.frames.length > CAST_BUFFER_MAX) { c.frames.shift(); c.dropped += 1; }
4194
+ }
4195
+ });
4196
+
4197
+ // --- screencast ---
4198
+
4199
+ // I fotogrammi arrivano solo se la scheda è attiva e visibile (prova del
4200
+ // 01/10: zero in secondo piano), e solo quando la pagina cambia.
4201
+ const casts = new Map(); // tabId → { frames, total, dropped }
4202
+ const CAST_BUFFER_MAX = 600;
4203
+
4204
+ async function cmdScreencast({ op, quality = 70, max_width, max_height, every_nth = 1, tab_id }) {
4205
+ const tabId = await resolveTabId(tab_id);
4206
+ if (op === 'start') {
4207
+ if (casts.has(tabId)) throw new Error('A screencast is already running on this tab: screencast stop first');
4208
+ const tab = await chrome.tabs.get(tabId);
4209
+ if (!tab.active) throw new Error('Screencast needs the tab active in its window: Chrome sends no frames for a background tab. Use tab_action activate first.');
4210
+ if (await pageHidden(tabId)) throw new Error(`Not recording: ${HIDDEN_HINT}`);
4211
+ const send = await holdDebugger(tabId, 'screencast', 'screencast');
4212
+ casts.set(tabId, { frames: [], total: 0, dropped: 0 });
4213
+ try {
4214
+ await send('Page.startScreencast', { format: 'jpeg', quality, everyNthFrame: every_nth, ...(max_width && { maxWidth: max_width }), ...(max_height && { maxHeight: max_height }) });
4215
+ } catch (e) {
4216
+ casts.delete(tabId);
4217
+ await releaseDebugger(tabId, 'screencast');
4218
+ throw e;
4219
+ }
4220
+ return { recording: true };
4221
+ }
4222
+ const c = casts.get(tabId);
4223
+ if (!c) throw new Error('No screencast running on this tab: screencast start first');
4224
+ if (op === 'drain') {
4225
+ const frames = c.frames.splice(0);
4226
+ return { frames, total: c.total, dropped: c.dropped, held: debuggerHeld(tabId).held };
4227
+ }
4228
+ if (op === 'stop') {
4229
+ await chrome.debugger.sendCommand({ tabId }, 'Page.stopScreencast', {}).catch(() => {});
4230
+ casts.delete(tabId);
4231
+ await releaseDebugger(tabId, 'screencast');
4232
+ return { frames: c.frames.splice(0), total: c.total, dropped: c.dropped };
4233
+ }
4234
+ throw new Error(`Unknown screencast op ${op}`);
4235
+ }
4236
+
4237
+ async function cmdPerfTrace({ op, reload = false, screenshots = false, size = 4 * 1024 * 1024, tab_id }) {
4238
+ const tabId = await resolveTabId(tab_id);
4239
+ const send = (m, p) => chrome.debugger.sendCommand({ tabId }, m, p);
4240
+ if (op === 'start') {
4241
+ if (traces.has(tabId)) throw new Error('A trace is already recording on this tab: perf_trace stop first');
4242
+ if (await pageHidden(tabId)) throw new Error(`Not tracing: ${HIDDEN_HINT}`);
4243
+ await holdDebugger(tabId, 'trace', 'perf_trace');
4244
+ let resolveComplete;
4245
+ const complete = new Promise((r) => { resolveComplete = r; });
4246
+ traces.set(tabId, { complete, resolveComplete });
4247
+ try {
4248
+ await send('Tracing.start', {
4249
+ transferMode: 'ReturnAsStream', streamFormat: 'json', streamCompression: 'none',
4250
+ traceConfig: { recordMode: 'recordAsMuchAsPossible', includedCategories: [...TRACE_CATEGORIES, ...(screenshots ? ['disabled-by-default-devtools.screenshot'] : [])] },
4251
+ });
4252
+ } catch (e) {
4253
+ traces.delete(tabId);
4254
+ await releaseDebugger(tabId, 'trace');
4255
+ throw e;
4256
+ }
4257
+ if (reload) await chrome.tabs.reload(tabId, { bypassCache: false });
4258
+ return { tracing: true, debugger_bar: true };
4259
+ }
4260
+ if (op === 'stop') {
4261
+ const t = traces.get(tabId);
4262
+ if (!t) throw new Error('No trace recording on this tab: perf_trace start first');
4263
+ if (!debuggerHeld(tabId).held) { traces.delete(tabId); throw new Error('The debugger was detached (bar cancelled or tab closed): the trace is lost'); }
4264
+ await send('Tracing.end', {});
4265
+ const stream = await Promise.race([t.complete, new Promise((_, rej) => setTimeout(() => rej(new Error('Trace did not complete within 30 s')), 30000))]);
4266
+ t.stream = stream;
4267
+ return { stream };
4268
+ }
4269
+ if (op === 'read') {
4270
+ const t = traces.get(tabId);
4271
+ if (!t?.stream) throw new Error('No finished trace to read: perf_trace stop first');
4272
+ const chunk = await send('IO.read', { handle: t.stream, size });
4273
+ if (chunk.eof) {
4274
+ await send('IO.close', { handle: t.stream }).catch(() => {});
4275
+ traces.delete(tabId);
4276
+ await releaseDebugger(tabId, 'trace');
4277
+ }
4278
+ return { data: chunk.data, base64: Boolean(chunk.base64Encoded), eof: Boolean(chunk.eof) };
4279
+ }
4280
+ if (op === 'abort') {
4281
+ traces.delete(tabId);
4282
+ await send('Tracing.end', {}).catch(() => {});
4283
+ return { aborted: await releaseDebugger(tabId, 'trace') };
4284
+ }
4285
+ throw new Error(`Unknown perf_trace op ${op}`);
4286
+ }
4287
+
4288
+ // --- cdp_target ---
4289
+
4290
+ // Id CDP della scheda, per i tool che in modalità launch parlano con la porta
4291
+ // di debug (heap_snapshot): l'id della scheda di chrome.tabs non vale lì.
4292
+ async function cmdCdpTarget({ tab_id }) {
4293
+ const tabId = await resolveTabId(tab_id);
4294
+ const target = (await chrome.debugger.getTargets()).find((t) => t.tabId === tabId);
4295
+ if (!target) throw new Error(`No debugger target for tab ${tabId}`);
4296
+ return { target_id: target.id, url: target.url };
4297
+ }
4298
+
3989
4299
  // --- list_event_listeners ---
3990
4300
 
3991
4301
  async function cmdListEventListeners({ type, limit = 100, tab_id }) {
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "chrome-bridge-mcp",
3
3
  "mcpName": "io.github.frsorrentino/chrome-bridge",
4
- "version": "1.26.0",
4
+ "version": "1.28.0",
5
5
  "type": "module",
6
- "description": "Chrome Bridge by frsorrentino: MCP server that lets Claude Code borrow a tab from your own logged-in Chrome and hand it back — logins, 2FA and CAPTCHAs stay with you (handoff). 60 tools; 2.8-4.3× cheaper and up to 9.3× fewer turns than Claude in Chrome, measured; ChromeOS included.",
6
+ "description": "Chrome Bridge by frsorrentino: MCP server that lets Claude Code borrow a tab from your own logged-in Chrome and hand it back — logins, 2FA and CAPTCHAs stay with you (handoff). 66 tools; 2.8-4.3× cheaper and up to 9.3× fewer turns than Claude in Chrome, measured; ChromeOS included.",
7
7
  "main": "server/index.js",
8
8
  "bin": {
9
9
  "chrome-bridge-mcp": "server/index.js",
@@ -57,5 +57,13 @@
57
57
  "@modelcontextprotocol/sdk": "^1.12.0",
58
58
  "node-html-parser": "^9.0.0",
59
59
  "ws": "^8.18.0"
60
+ },
61
+ "peerDependencies": {
62
+ "@paulirish/trace_engine": ">=0.0.65"
63
+ },
64
+ "peerDependenciesMeta": {
65
+ "@paulirish/trace_engine": {
66
+ "optional": true
67
+ }
60
68
  }
61
69
  }
package/server/cli.js CHANGED
@@ -13,6 +13,7 @@
13
13
  * chrome-bridge screenshot --out /tmp/shot.png
14
14
  */
15
15
 
16
+ import { uploadBuffer } from './upload.js';
16
17
  import WebSocket from 'ws';
17
18
  import { readFile, writeFile, mkdir } from 'node:fs/promises';
18
19
  import { basename, extname, join } from 'node:path';
@@ -421,11 +422,9 @@ async function run(client, command, params, opts) {
421
422
  // Comandi con file I/O lato CLI
422
423
  if (command === 'upload_file') {
423
424
  const buf = await readFile(params.path);
424
- if (buf.length > 10 * 1024 * 1024) throw new Error(`File too large: ${buf.length} bytes (max 10MB)`);
425
425
  const mime = params.mime_type || MIME_BY_EXT[extname(params.path).toLowerCase()] || 'application/octet-stream';
426
- const data = await client.sendCommand(MessageType.UPLOAD_FILE, {
427
- selector: params.selector, name: basename(params.path), mime_type: mime,
428
- content_b64: buf.toString('base64'), tab_id: params.tab_id,
426
+ const data = await uploadBuffer((t, p) => client.sendCommand(t, p), {
427
+ selector: params.selector, name: basename(params.path), mime_type: mime, buf, tab_id: params.tab_id,
429
428
  });
430
429
  return JSON.stringify(data);
431
430
  }
package/server/heap.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * heap_snapshot: istantanea dell'heap JS dalla porta CDP del browser lanciato
3
+ * (HeapProfiler non è ammesso a chrome.debugger), sintesi per classe e
4
+ * confronto fra due istantanee.
5
+ *
6
+ * Il formato .heapsnapshot è quello di DevTools: nodi in un array piatto con
7
+ * i campi descritti in snapshot.meta.node_fields, nomi in strings. Il file si
8
+ * apre anche in DevTools > Memory.
9
+ */
10
+ import { createWriteStream } from 'node:fs';
11
+ import WebSocket from 'ws';
12
+
13
+ /** Client CDP minimo su un target della porta di debug. */
14
+ export function cdpConnect(wsUrl) {
15
+ return new Promise((resolve, reject) => {
16
+ const ws = new WebSocket(wsUrl, { perMessageDeflate: false, maxPayload: 512 * 1024 * 1024 });
17
+ let id = 0;
18
+ const pending = new Map();
19
+ const listeners = new Map();
20
+ ws.on('message', (raw) => {
21
+ const m = JSON.parse(raw.toString());
22
+ if (m.id && pending.has(m.id)) {
23
+ const { res, rej } = pending.get(m.id);
24
+ pending.delete(m.id);
25
+ if (m.error) rej(new Error(`${m.error.message} (${m.error.code})`)); else res(m.result);
26
+ } else if (m.method) {
27
+ for (const fn of listeners.get(m.method) ?? []) fn(m.params);
28
+ }
29
+ });
30
+ ws.on('error', reject);
31
+ ws.on('open', () => resolve({
32
+ send: (method, params = {}) => new Promise((res, rej) => {
33
+ const i = ++id;
34
+ pending.set(i, { res, rej });
35
+ ws.send(JSON.stringify({ id: i, method, params }));
36
+ }),
37
+ on: (method, fn) => { if (!listeners.has(method)) listeners.set(method, []); listeners.get(method).push(fn); },
38
+ close: () => ws.close(),
39
+ }));
40
+ });
41
+ }
42
+
43
+ /** WebSocket del target con quell'id sulla porta locale. */
44
+ export async function targetWsUrl(port, targetId) {
45
+ const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
46
+ const t = list.find((x) => x.id === targetId);
47
+ if (!t?.webSocketDebuggerUrl) throw new Error(`Target ${targetId} not found on the DevTools port`);
48
+ return t.webSocketDebuggerUrl;
49
+ }
50
+
51
+ /** Scrive l'istantanea su file man mano che arrivano i pezzi. Restituisce i byte scritti. */
52
+ export async function takeHeapSnapshot(cdp, path) {
53
+ const out = createWriteStream(path);
54
+ let bytes = 0;
55
+ cdp.on('HeapProfiler.addHeapSnapshotChunk', ({ chunk }) => { bytes += Buffer.byteLength(chunk); out.write(chunk); });
56
+ await cdp.send('HeapProfiler.enable');
57
+ // Un garbage collection prima: senza, l'istantanea conta anche oggetti già
58
+ // irraggiungibili e il confronto fra due istantanee è rumore.
59
+ await cdp.send('HeapProfiler.collectGarbage');
60
+ await cdp.send('HeapProfiler.takeHeapSnapshot', { reportProgress: false, captureNumericValue: false });
61
+ await new Promise((res, rej) => out.end((err) => (err ? rej(err) : res())));
62
+ return bytes;
63
+ }
64
+
65
+ /**
66
+ * Sintesi per classe: conteggio e dimensione propria. Gli oggetti si
67
+ * raggruppano per costruttore, il resto per tipo, come la vista Summary di
68
+ * DevTools; i nodi DOM staccati sono il segnale classico di una perdita.
69
+ */
70
+ export function summarizeHeap(snapshot, { top = 15 } = {}) {
71
+ const meta = snapshot.snapshot.meta;
72
+ const f = meta.node_fields;
73
+ const width = f.length;
74
+ const iType = f.indexOf('type'); const iName = f.indexOf('name'); const iSize = f.indexOf('self_size');
75
+ const iDetached = f.indexOf('detachedness');
76
+ const types = meta.node_types[iType];
77
+ const { nodes, strings } = snapshot;
78
+ const byClass = new Map();
79
+ let total = 0; let detached = 0; let count = 0;
80
+ for (let i = 0; i < nodes.length; i += width) {
81
+ const type = types[nodes[i + iType]];
82
+ const size = nodes[i + iSize];
83
+ const key = type === 'object' || type === 'native' ? strings[nodes[i + iName]] : `(${type})`;
84
+ const c = byClass.get(key) ?? { count: 0, self_size: 0 };
85
+ c.count += 1; c.self_size += size;
86
+ byClass.set(key, c);
87
+ total += size; count += 1;
88
+ if (iDetached >= 0 && nodes[i + iDetached] === 2) detached += 1;
89
+ }
90
+ const classes = [...byClass.entries()].map(([name, c]) => ({ name, ...c })).sort((a, b) => b.self_size - a.self_size);
91
+ return { nodes: count, total_self_size: total, detached_dom_nodes: detached, top: classes.slice(0, top), _all: byClass };
92
+ }
93
+
94
+ /** Confronto: le classi cresciute di più fra la prima istantanea e la seconda. */
95
+ export function diffHeap(before, after, { top = 15 } = {}) {
96
+ const names = new Set([...before._all.keys(), ...after._all.keys()]);
97
+ const rows = [];
98
+ for (const name of names) {
99
+ const a = before._all.get(name) ?? { count: 0, self_size: 0 };
100
+ const b = after._all.get(name) ?? { count: 0, self_size: 0 };
101
+ const d = { name, count_delta: b.count - a.count, size_delta: b.self_size - a.self_size };
102
+ if (d.count_delta || d.size_delta) rows.push(d);
103
+ }
104
+ rows.sort((x, y) => y.size_delta - x.size_delta);
105
+ return {
106
+ total_size_delta: after.total_self_size - before.total_self_size,
107
+ nodes_delta: after.nodes - before.nodes,
108
+ detached_dom_delta: after.detached_dom_nodes - before.detached_dom_nodes,
109
+ grown: rows.filter((r) => r.size_delta > 0).slice(0, top),
110
+ };
111
+ }
package/server/index.js CHANGED
@@ -39,6 +39,7 @@ function parseSecurity() {
39
39
  noJs: process.argv.includes('--no-js') || on(process.env.CHROME_BRIDGE_NO_JS),
40
40
  writeRoot: argValue('--write-root') ?? process.env.CHROME_BRIDGE_WRITE_ROOT ?? null,
41
41
  readRoot: argValue('--read-root') ?? process.env.CHROME_BRIDGE_READ_ROOT ?? null,
42
+ alwaysLoad: argValue('--always-load') ?? process.env.CHROME_BRIDGE_ALWAYS_LOAD ?? null,
42
43
  };
43
44
  }
44
45
 
@@ -80,7 +81,7 @@ async function main() {
80
81
  // finestra era dietro un'altra.
81
82
  // Il 42% delle sessioni reali caricava i tool con 2+ ToolSearch (media 2,0).
82
83
  'When tools are deferred, batch every tool needed for the next workflow into ONE ToolSearch call using exact names (select:name1,name2,...); do not search one tool at a time.',
83
- 'Missing optional tools: call get_status({enable:["group",...]}) once for all required groups (audits, visual, network, storage, dom, files; "all" enables all). After tools/list_changed, use them next turn; if still deferred, batch-search their names once. No restart or user configuration needed.',
84
+ 'Missing optional tools: call get_status({enable:["group",...]}) once for all required groups (audits, visual, network, storage, dom, files, perf; "all" enables all). After tools/list_changed, use them next turn; if still deferred, batch-search their names once. No restart or user configuration needed.',
84
85
  'A tab in a minimized, covered or background window does not render: screenshots fail, timers slow down. get_page_info reports visibility (page_hidden in a result means the same); bring the window on screen, or create_tab new_window with bounds.',
85
86
  ].join(' '),
86
87
  });
@@ -128,7 +129,7 @@ async function main() {
128
129
  // Errori dei tool annotati in locale (formato claude-observe) quando nessun
129
130
  // hook del plugin li vede: vedi server/observe.js.
130
131
  const observe = createObserver({ version: VERSION });
131
- session.tools = registerTools(mcpServer, wsManager, parseCaps(), { ...parseSecurity(), observe });
132
+ session.tools = registerTools(mcpServer, wsManager, parseCaps(), { ...parseSecurity(), observe, cdpPort: browser ? browser.cdpPort : null });
132
133
 
133
134
  // 4. Avvia il trasporto stdio MCP
134
135
  const transport = new StdioServerTransport();