@kelceyp/chrome-control-mcp 0.2.1 → 0.4.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.
@@ -0,0 +1,903 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
+ import {
6
+ CallToolRequestSchema,
7
+ ListToolsRequestSchema,
8
+ } from '@modelcontextprotocol/sdk/types.js';
9
+ import { execFile } from 'child_process';
10
+ import { promisify } from 'util';
11
+ import pkg from '../package.json' assert { type: 'json' };
12
+
13
+ const execFileAsync = promisify(execFile);
14
+
15
+ class ChromeControlServer {
16
+ constructor() {
17
+ this.server = new Server(
18
+ {
19
+ name: 'chrome-control',
20
+ version: pkg.version,
21
+ },
22
+ {
23
+ capabilities: {
24
+ tools: {},
25
+ },
26
+ }
27
+ );
28
+
29
+ this.setupHandlers();
30
+ }
31
+
32
+ async executeAppleScript(script) {
33
+ try {
34
+ const { stdout, stderr } = await execFileAsync('osascript', ['-e', script]);
35
+ if (stderr) {
36
+ console.error('AppleScript stderr:', stderr);
37
+ }
38
+ return stdout.trim();
39
+ } catch (error) {
40
+ console.error('AppleScript execution error:', error);
41
+
42
+ // Check for common permission-related errors
43
+ if (error.message.includes('(-1743)') ||
44
+ error.message.includes('not allowed assistive access') ||
45
+ error.message.includes('not authorized') ||
46
+ error.message.includes('System Events')) {
47
+ throw new Error(
48
+ 'Permission denied: Chrome control requires automation permissions.\n\n' +
49
+ 'To grant permission:\n' +
50
+ '1. Open System Settings > Privacy & Security > Automation\n' +
51
+ '2. Find "Claude" in the list\n' +
52
+ '3. Enable "Google Chrome" under Claude\n' +
53
+ '4. You may need to restart Claude after granting permission\n\n' +
54
+ 'Note: You\'ll see a permission prompt the first time you use this extension.'
55
+ );
56
+ }
57
+
58
+ // Check for Chrome not running
59
+ if (error.message.includes('(-600)') ||
60
+ error.message.includes('application isn\'t running') ||
61
+ error.message.includes('Google Chrome')) {
62
+ throw new Error(
63
+ 'Google Chrome is not running. Please launch Chrome and try again.'
64
+ );
65
+ }
66
+
67
+ throw new Error(`AppleScript error: ${error.message}`);
68
+ }
69
+ }
70
+
71
+ setupHandlers() {
72
+ this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
73
+ tools: [
74
+ {
75
+ name: 'open_url',
76
+ description: 'Open a URL in Chrome',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: {
80
+ url: { type: 'string', description: 'URL to open' },
81
+ new_tab: { type: 'boolean', description: 'Open in a new tab', default: true }
82
+ },
83
+ required: ['url']
84
+ }
85
+ },
86
+ {
87
+ name: 'get_current_tab',
88
+ description: 'Get information about the current active tab',
89
+ inputSchema: { type: 'object', properties: {} }
90
+ },
91
+ {
92
+ name: 'list_tabs',
93
+ description: 'List all open tabs in Chrome',
94
+ inputSchema: {
95
+ type: 'object',
96
+ properties: {
97
+ window_id: { type: 'number', description: 'Specific window ID to list tabs from' }
98
+ }
99
+ }
100
+ },
101
+ {
102
+ name: 'close_tab',
103
+ description: 'Close a specific tab',
104
+ inputSchema: {
105
+ type: 'object',
106
+ properties: {
107
+ tab_id: { type: 'number', description: 'ID of the tab to close' }
108
+ },
109
+ required: ['tab_id']
110
+ }
111
+ },
112
+ {
113
+ name: 'switch_to_tab',
114
+ description: 'Switch to a specific tab',
115
+ inputSchema: {
116
+ type: 'object',
117
+ properties: {
118
+ tab_id: { type: 'number', description: 'ID of the tab to switch to' }
119
+ },
120
+ required: ['tab_id']
121
+ }
122
+ },
123
+ {
124
+ name: 'reload_tab',
125
+ description: 'Reload a tab',
126
+ inputSchema: {
127
+ type: 'object',
128
+ properties: {
129
+ tab_id: { type: 'number', description: 'ID of the tab to reload' }
130
+ }
131
+ }
132
+ },
133
+ {
134
+ name: 'go_back',
135
+ description: 'Navigate back in browser history',
136
+ inputSchema: {
137
+ type: 'object',
138
+ properties: {
139
+ tab_id: { type: 'number', description: 'ID of the tab' }
140
+ }
141
+ }
142
+ },
143
+ {
144
+ name: 'go_forward',
145
+ description: 'Navigate forward in browser history',
146
+ inputSchema: {
147
+ type: 'object',
148
+ properties: {
149
+ tab_id: { type: 'number', description: 'ID of the tab' }
150
+ }
151
+ }
152
+ },
153
+ {
154
+ name: 'execute_javascript',
155
+ description: 'Execute JavaScript in the current tab',
156
+ inputSchema: {
157
+ type: 'object',
158
+ properties: {
159
+ code: { type: 'string', description: 'JavaScript code to execute' },
160
+ tab_id: { type: 'number', description: 'ID of the tab' }
161
+ },
162
+ required: ['code']
163
+ }
164
+ },
165
+ {
166
+ name: 'get_page_content',
167
+ description: 'Get the text content of the current page',
168
+ inputSchema: {
169
+ type: 'object',
170
+ properties: {
171
+ tab_id: { type: 'number', description: 'ID of the tab' }
172
+ }
173
+ }
174
+ },
175
+ {
176
+ name: 'execute_javascript_async',
177
+ description: 'Execute async JavaScript in the current tab and wait for result',
178
+ inputSchema: {
179
+ type: 'object',
180
+ properties: {
181
+ code: { type: 'string', description: 'JavaScript code to execute (supports await)' },
182
+ tab_id: { type: 'number', description: 'ID of the tab' },
183
+ timeout_ms: { type: 'number', description: 'Timeout in milliseconds', default: 60000 },
184
+ poll_ms: { type: 'number', description: 'Polling interval in milliseconds', default: 200 },
185
+ stringify: { type: 'boolean', description: 'JSON stringify the result', default: true }
186
+ },
187
+ required: ['code']
188
+ }
189
+ },
190
+ {
191
+ name: 'gpt_chat',
192
+ description: 'Send a message to ChatGPT and wait for response (auto-injects adapter)',
193
+ inputSchema: {
194
+ type: 'object',
195
+ properties: {
196
+ message: { type: 'string', description: 'Message to send to ChatGPT' },
197
+ idle_ms: { type: 'number', description: 'Idle time to wait after last DOM change', default: 1200 },
198
+ timeout_ms: { type: 'number', description: 'Maximum time to wait for response', default: 120000 },
199
+ tab_id: { type: 'number', description: 'ID of the tab' }
200
+ },
201
+ required: ['message']
202
+ }
203
+ }
204
+ ]
205
+ }));
206
+
207
+ this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
208
+ const { name, arguments: args } = request.params;
209
+
210
+ try {
211
+ switch (name) {
212
+ case 'open_url': {
213
+ const { url, new_tab = true } = args;
214
+ try {
215
+ new URL(url);
216
+ } catch (error) {
217
+ return {
218
+ content: [{ type: 'text', text: `Error: url is not a valid url - ${error.message}` }],
219
+ isError: true
220
+ };
221
+ }
222
+ const script = new_tab
223
+ ? `tell application "Google Chrome" to open location ${JSON.stringify(url)}`
224
+ : `tell application "Google Chrome" to set URL of active tab of front window to ${JSON.stringify(url)}`;
225
+
226
+ await this.executeAppleScript(script);
227
+ return { content: [{ type: 'text', text: `Opened ${url} in Chrome` }] };
228
+ }
229
+
230
+ case 'get_current_tab': {
231
+ const script = `
232
+ tell application "Google Chrome"
233
+ set currentTab to active tab of front window
234
+ set tabInfo to {URL of currentTab, title of currentTab, id of currentTab}
235
+ return tabInfo
236
+ end tell
237
+ `;
238
+ const result = await this.executeAppleScript(script);
239
+ const [url, title, id] = result.split(', ');
240
+ return {
241
+ content: [{
242
+ type: 'text',
243
+ text: JSON.stringify({ url, title, id: parseInt(id) }, null, 2)
244
+ }]
245
+ };
246
+ }
247
+
248
+ case 'list_tabs': {
249
+ const script = `
250
+ tell application "Google Chrome"
251
+ set tabsList to {}
252
+ repeat with w in windows
253
+ repeat with t in tabs of w
254
+ set end of tabsList to {id of t as string, URL of t, title of t}
255
+ end repeat
256
+ end repeat
257
+ set AppleScript's text item delimiters to "|"
258
+ set output to ""
259
+ repeat with tabInfo in tabsList
260
+ set output to output & (item 1 of tabInfo) & "," & (item 2 of tabInfo) & "," & (item 3 of tabInfo) & "|"
261
+ end repeat
262
+ return output
263
+ end tell
264
+ `;
265
+ const result = await this.executeAppleScript(script);
266
+ const tabs = result.split('|').filter(tab => tab).map(tab => {
267
+ const [id, url, title] = tab.split(',');
268
+ return { id: parseInt(id), url, title };
269
+ });
270
+ return {
271
+ content: [{
272
+ type: 'text',
273
+ text: JSON.stringify(tabs, null, 2)
274
+ }]
275
+ };
276
+ }
277
+
278
+ case 'close_tab': {
279
+ const { tab_id } = args;
280
+ const script = `
281
+ tell application "Google Chrome"
282
+ repeat with w in windows
283
+ repeat with t in tabs of w
284
+ if (id of t as string) is "${tab_id}" then
285
+ close t
286
+ return "Tab closed"
287
+ end if
288
+ end repeat
289
+ end repeat
290
+ return "Tab not found"
291
+ end tell
292
+ `;
293
+ const result = await this.executeAppleScript(script);
294
+ return { content: [{ type: 'text', text: result }] };
295
+ }
296
+
297
+ case 'switch_to_tab': {
298
+ const { tab_id } = args;
299
+ const script = `
300
+ tell application "Google Chrome"
301
+ repeat with w in windows
302
+ repeat with tabIndex from 1 to count of tabs of w
303
+ set t to tab tabIndex of w
304
+ if (id of t as string) is "${tab_id}" then
305
+ set active tab index of w to tabIndex
306
+ set index of w to 1
307
+ activate
308
+ return "Switched to tab"
309
+ end if
310
+ end repeat
311
+ end repeat
312
+ return "Tab not found"
313
+ end tell
314
+ `;
315
+ const result = await this.executeAppleScript(script);
316
+ return { content: [{ type: 'text', text: result }] };
317
+ }
318
+
319
+ case 'reload_tab': {
320
+ const { tab_id } = args;
321
+ const script = tab_id ? `
322
+ tell application "Google Chrome"
323
+ repeat with w in windows
324
+ repeat with t in tabs of w
325
+ if (id of t as string) is "${tab_id}" then
326
+ reload t
327
+ return "Tab reloaded"
328
+ end if
329
+ end repeat
330
+ end repeat
331
+ return "Tab not found"
332
+ end tell
333
+ ` : `
334
+ tell application "Google Chrome"
335
+ reload active tab of front window
336
+ return "Tab reloaded"
337
+ end tell
338
+ `;
339
+ const result = await this.executeAppleScript(script);
340
+ return { content: [{ type: 'text', text: result }] };
341
+ }
342
+
343
+ case 'go_back': {
344
+ const { tab_id } = args;
345
+ const script = tab_id ? `
346
+ tell application "Google Chrome"
347
+ repeat with w in windows
348
+ repeat with t in tabs of w
349
+ if (id of t as string) is "${tab_id}" then
350
+ go back t
351
+ return "Navigated back"
352
+ end if
353
+ end repeat
354
+ end repeat
355
+ return "Tab not found"
356
+ end tell
357
+ ` : `
358
+ tell application "Google Chrome"
359
+ go back active tab of front window
360
+ return "Navigated back"
361
+ end tell
362
+ `;
363
+ const result = await this.executeAppleScript(script);
364
+ return { content: [{ type: 'text', text: result }] };
365
+ }
366
+
367
+ case 'go_forward': {
368
+ const { tab_id } = args;
369
+ const script = tab_id ? `
370
+ tell application "Google Chrome"
371
+ repeat with w in windows
372
+ repeat with t in tabs of w
373
+ if (id of t as string) is "${tab_id}" then
374
+ go forward t
375
+ return "Navigated forward"
376
+ end if
377
+ end repeat
378
+ end repeat
379
+ return "Tab not found"
380
+ end tell
381
+ ` : `
382
+ tell application "Google Chrome"
383
+ go forward active tab of front window
384
+ return "Navigated forward"
385
+ end tell
386
+ `;
387
+ const result = await this.executeAppleScript(script);
388
+ return { content: [{ type: 'text', text: result }] };
389
+ }
390
+
391
+ case 'execute_javascript': {
392
+ const { code, tab_id } = args;
393
+ // For AppleScript strings, we need to escape backslashes and double quotes
394
+ const script = tab_id ? `
395
+ tell application "Google Chrome"
396
+ repeat with w in windows
397
+ repeat with t in tabs of w
398
+ if (id of t as string) is "${tab_id}" then
399
+ set result to execute t javascript ${JSON.stringify(code)}
400
+ return result
401
+ end if
402
+ end repeat
403
+ end repeat
404
+ return "Tab not found"
405
+ end tell
406
+ ` : `
407
+ tell application "Google Chrome"
408
+ execute active tab of front window javascript ${JSON.stringify(code)}
409
+ end tell
410
+ `;
411
+ const result = await this.executeAppleScript(script);
412
+ return { content: [{ type: 'text', text: result || 'JavaScript executed' }] };
413
+ }
414
+
415
+ case 'get_page_content': {
416
+ const { tab_id } = args;
417
+ const script = tab_id ? `
418
+ tell application "Google Chrome"
419
+ repeat with w in windows
420
+ repeat with t in tabs of w
421
+ if (id of t as string) is "${tab_id}" then
422
+ set pageContent to execute t javascript "document.body.innerText"
423
+ return pageContent
424
+ end if
425
+ end repeat
426
+ end repeat
427
+ return "Tab not found"
428
+ end tell
429
+ ` : `
430
+ tell application "Google Chrome"
431
+ execute active tab of front window javascript "document.body.innerText"
432
+ end tell
433
+ `;
434
+ const result = await this.executeAppleScript(script);
435
+ return { content: [{ type: 'text', text: result }] };
436
+ }
437
+
438
+ case 'execute_javascript_async': {
439
+ const {
440
+ code,
441
+ tab_id,
442
+ timeout_ms = 60000,
443
+ poll_ms = 200,
444
+ stringify = true,
445
+ } = args;
446
+
447
+ if (typeof code !== 'string' || !code.trim()) {
448
+ return { content: [{ type: 'text', text: 'Error: code is required (string)' }] };
449
+ }
450
+
451
+ // Build the page-side bootstrap that returns a token and completes later
452
+ // Note: we embed `code` as-is inside an async IIFE, so it can use `await`.
453
+ const bootstrapJs = `
454
+ (() => {
455
+ try {
456
+ window.__MCP_ASYNC_RESULTS = window.__MCP_ASYNC_RESULTS || {};
457
+ const token = 'mcp_' + Date.now() + '_' + Math.random().toString(36).slice(2);
458
+ (async () => {
459
+ try {
460
+ const __result__ = await (async () => { ${code} })();
461
+ window.__MCP_ASYNC_RESULTS[token] = {
462
+ status: 'fulfilled',
463
+ value: ${stringify ? 'JSON.stringify(__result__)' : '__result__'}
464
+ };
465
+ } catch (e) {
466
+ window.__MCP_ASYNC_RESULTS[token] = {
467
+ status: 'rejected',
468
+ error: String(e && e.message || e)
469
+ };
470
+ }
471
+ })();
472
+ return token;
473
+ } catch (e) {
474
+ return 'ERROR_BOOTSTRAP:' + String(e && e.message || e);
475
+ }
476
+ })();
477
+ `.trim();
478
+
479
+ // Escape for AppleScript execute javascript "..."
480
+ const asQuote = (s) =>
481
+ s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
482
+
483
+ const jsBootEsc = asQuote(bootstrapJs);
484
+ const pollSeconds = (Math.max(50, Number(poll_ms)) / 1000).toFixed(3); // >=50ms, to real
485
+ const timeoutMs = Math.max(1000, Number(timeout_ms)); // >=1s
486
+
487
+ const script = tab_id ? `
488
+ set _timeoutMs to ${timeoutMs}
489
+ set _pollSec to ${pollSeconds} as real
490
+ tell application "Google Chrome"
491
+ set _token to ""
492
+ repeat with w in windows
493
+ repeat with t in tabs of w
494
+ if (id of t as string) is "${tab_id}" then
495
+ set _token to execute t javascript "${jsBootEsc}"
496
+ exit repeat
497
+ end if
498
+ end repeat
499
+ if _token is not "" then exit repeat
500
+ end repeat
501
+ if _token is "" then return "Tab not found"
502
+
503
+ set _t0 to (current date)
504
+ repeat
505
+ set _status to execute active tab of front window javascript "(() => { var r = window.__MCP_ASYNC_RESULTS && window.__MCP_ASYNC_RESULTS['\" & _token & \"']; return r ? r.status : 'pending'; })()"
506
+ if _status is "fulfilled" then
507
+ set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
508
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
509
+ return _val
510
+ else if _status is "rejected" then
511
+ set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
512
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
513
+ return "ERROR:" & _err
514
+ end if
515
+
516
+ set _elapsedMs to ((current date) - _t0) * 1000
517
+ if _elapsedMs > _timeoutMs then
518
+ execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
519
+ return "TIMEOUT"
520
+ end if
521
+ delay _pollSec
522
+ end repeat
523
+ end tell
524
+ ` : `
525
+ set _timeoutMs to ${timeoutMs}
526
+ set _pollSec to ${pollSeconds} as real
527
+ tell application "Google Chrome"
528
+ set _token to execute active tab of front window javascript "${jsBootEsc}"
529
+ if _token starts with "ERROR_BOOTSTRAP:" then return _token
530
+ set _t0 to (current date)
531
+ repeat
532
+ set _status to execute active tab of front window javascript "(() => { var r = window.__MCP_ASYNC_RESULTS && window.__MCP_ASYNC_RESULTS['\" & _token & \"']; return r ? r.status : 'pending'; })()"
533
+ if _status is "fulfilled" then
534
+ set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
535
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
536
+ return _val
537
+ else if _status is "rejected" then
538
+ set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
539
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
540
+ return "ERROR:" & _err
541
+ end if
542
+
543
+ set _elapsedMs to ((current date) - _t0) * 1000
544
+ if _elapsedMs > _timeoutMs then
545
+ execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
546
+ return "TIMEOUT"
547
+ end if
548
+ delay _pollSec
549
+ end repeat
550
+ end tell
551
+ `;
552
+
553
+ const result = await this.executeAppleScript(script);
554
+
555
+ // Normalize response: if we JSON-stringified in page, parse here.
556
+ if (typeof result === 'string' && result.startsWith('ERROR:')) {
557
+ return { content: [{ type: 'text', text: result }] };
558
+ }
559
+ if (stringify && typeof result === 'string') {
560
+ try {
561
+ const parsed = JSON.parse(result);
562
+ return { content: [{ type: 'text', text: typeof parsed === 'string' ? parsed : JSON.stringify(parsed) }] };
563
+ } catch {
564
+ // Not JSON (e.g., primitive string); return as-is
565
+ return { content: [{ type: 'text', text: result }] };
566
+ }
567
+ }
568
+ return { content: [{ type: 'text', text: result ?? '' }] };
569
+ }
570
+
571
+ case 'gpt_chat': {
572
+ const { message, idle_ms = 1200, timeout_ms = 120000, tab_id } = args;
573
+
574
+ if (typeof message !== 'string' || !message.trim()) {
575
+ return { content: [{ type: 'text', text: 'Error: message (string) is required' }] };
576
+ }
577
+
578
+ const ADAPTER_VERSION = '1.0.2';
579
+
580
+ // v1.0.2: Hybrid completion detection (text-length polling + button confirmation)
581
+ const ADAPTER_JS = `
582
+ (() => {
583
+ if (window.ChatBridge && window.ChatBridge.version === '${ADAPTER_VERSION}') return;
584
+
585
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms));
586
+ const now = () => performance.now();
587
+ const qAll = (sel, root = document) => Array.from(root.querySelectorAll(sel));
588
+
589
+ const findTextbox = () =>
590
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
591
+ qAll('[contenteditable="true"]').at(-1) || null;
592
+
593
+ const findForm = () => { const tb = findTextbox(); return tb?.closest('form') || null; };
594
+ const findSendButton = () =>
595
+ document.querySelector('button[data-testid*="send"],button[aria-label*="Send"],button[type="submit"]');
596
+ const inputEnabled = () => {
597
+ const tb = findTextbox(); if (!tb) return false;
598
+ return tb.getAttribute('aria-disabled') !== 'true' && !tb.closest('[aria-disabled="true"]');
599
+ };
600
+ const countUser = () =>
601
+ qAll('[data-message-author-role="user"],[data-author-role="user"]').length;
602
+ const countAssistant = () =>
603
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
604
+ const lastAssistantNode = () =>
605
+ qAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').at(-1) || null;
606
+
607
+ const pickText = (node) => {
608
+ const n = node || lastAssistantNode();
609
+ if (!n) return '';
610
+ const c = n.querySelector('.markdown, article') || n;
611
+ const t = c.innerText ?? c.textContent ?? '';
612
+ return (t || '').trim();
613
+ };
614
+
615
+ const lastAssistantTurn = () => {
616
+ const turns = qAll('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]');
617
+ for (let i = turns.length - 1; i >= 0; i--) {
618
+ if (turns[i].querySelector('[data-message-author-role="assistant"], [data-author-role="assistant"]')) {
619
+ return turns[i];
620
+ }
621
+ }
622
+ const content = lastAssistantNode();
623
+ return (
624
+ content?.closest('[data-testid^="conversation-turn"], [data-testid*="conversation-turn"]') ||
625
+ content ||
626
+ null
627
+ );
628
+ };
629
+
630
+ const hasTurnActions = (turn) => {
631
+ if (!turn) return false;
632
+ const toolbar =
633
+ turn.querySelector('[data-testid*="turn-actions"]') ||
634
+ turn.querySelector('[role="toolbar"]') ||
635
+ null;
636
+ if (!toolbar) return false;
637
+ const btns = toolbar.querySelectorAll(
638
+ 'button[aria-label*="Regenerate"],' +
639
+ 'button[aria-label*="Copy"],' +
640
+ 'button[aria-label*="Share"],' +
641
+ 'button[aria-label*="Like"],' +
642
+ 'button[aria-label*="Dislike"],' +
643
+ '[data-testid*="thumb"]'
644
+ );
645
+ return btns.length > 0;
646
+ };
647
+
648
+ const clearInput = async () => {
649
+ const tb = findTextbox(); if (!tb) throw new Error('ChatBridge: textbox not found');
650
+ tb.focus?.({ preventScroll: true }); await sleep(10);
651
+ tb.textContent = '';
652
+ tb.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, inputType: 'deleteContentBackward', data: '' }));
653
+ tb.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'deleteContentBackward', data: '' }));
654
+ tb.dispatchEvent(new Event('change', { bubbles: true }));
655
+ await sleep(10);
656
+ };
657
+
658
+ const setText = async (text) => {
659
+ const tb = findTextbox(); if (!tb) throw new Error('ChatBridge: textbox not found');
660
+ tb.focus?.({ preventScroll: true }); await sleep(10);
661
+ const before = tb.textContent || '';
662
+ tb.textContent = before + text;
663
+ tb.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, inputType: 'insertText', data: text }));
664
+ tb.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text }));
665
+ tb.dispatchEvent(new Event('change', { bubbles: true }));
666
+ await sleep(10);
667
+ };
668
+
669
+ const send = async () => {
670
+ const form = findForm();
671
+ if (form?.requestSubmit) { form.requestSubmit(); await sleep(40); }
672
+ if (inputEnabled()) {
673
+ const btn = findSendButton();
674
+ if (btn) { btn.click(); await sleep(40); }
675
+ }
676
+ };
677
+
678
+ const waitForResponseWithBaseline = async (baseline, { idleMs = 1200, timeoutMs = 120000 } = {}) => {
679
+ const idlePrimaryMs = idleMs;
680
+ const idleConfirmMs = 3300;
681
+ const finalButtonGraceMs = 2000;
682
+
683
+ const t0 = now();
684
+ const preUser = baseline?.user ?? countUser();
685
+ const preAsst = baseline?.asst ?? countAssistant();
686
+
687
+ if (countUser() < preUser + 1) {
688
+ while (now() - t0 < timeoutMs) {
689
+ if (countUser() >= preUser + 1) break;
690
+ await sleep(60);
691
+ }
692
+ if (countUser() < preUser + 1) {
693
+ return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
694
+ }
695
+ }
696
+
697
+ if (countAssistant() < preAsst + 1) {
698
+ while (now() - t0 < timeoutMs) {
699
+ if (countAssistant() >= preAsst + 1) break;
700
+ await sleep(60);
701
+ }
702
+ if (countAssistant() < preAsst + 1) {
703
+ return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
704
+ }
705
+ }
706
+
707
+ let lastLen = -1;
708
+ let lastChange = now();
709
+ let confirmStart = null;
710
+
711
+ while (now() - t0 < timeoutMs) {
712
+ const node = lastAssistantNode();
713
+ const txt = pickText(node);
714
+ const len = txt.length;
715
+
716
+ if (len !== lastLen) {
717
+ lastLen = len;
718
+ lastChange = now();
719
+ confirmStart = null;
720
+ }
721
+
722
+ const idle = now() - lastChange;
723
+
724
+ if (idle >= idlePrimaryMs && inputEnabled()) {
725
+ if (idle >= idleConfirmMs) {
726
+ const turn = lastAssistantTurn();
727
+ if (hasTurnActions(turn)) {
728
+ return { ok: true, text: txt, ms: now() - t0 };
729
+ }
730
+
731
+ if (confirmStart == null) confirmStart = now();
732
+ if (now() - confirmStart >= finalButtonGraceMs) {
733
+ return { ok: true, text: txt, ms: now() - t0, note: 'noButtonsConfirm' };
734
+ }
735
+ }
736
+ }
737
+
738
+ await sleep(100);
739
+ }
740
+
741
+ return { ok: false, reason: 'timeout', ms: now() - t0 };
742
+ };
743
+
744
+ const sendAndWait = async (text, opts) => {
745
+ const baseline = { user: countUser(), asst: countAssistant() };
746
+ await clearInput();
747
+ await setText(text);
748
+ await send();
749
+ return waitForResponseWithBaseline(baseline, opts);
750
+ };
751
+
752
+ window.ChatBridge = Object.freeze({
753
+ version: '${ADAPTER_VERSION}',
754
+ message: {
755
+ sendAndWait
756
+ }
757
+ });
758
+ })();
759
+ `.trim();
760
+
761
+ // Page-side script: ensure adapter, then sendAndWait (wrapped in async IIFE for polling)
762
+ const userCode = `
763
+ ${ADAPTER_JS}
764
+ return await window.ChatBridge.message.sendAndWait(${JSON.stringify(message)}, { idleMs: ${idle_ms}, timeoutMs: ${timeout_ms} });
765
+ `.trim();
766
+
767
+ // Build the bootstrap (same pattern as execute_javascript_async)
768
+ const bootstrapJs = `
769
+ (() => {
770
+ try {
771
+ window.__MCP_ASYNC_RESULTS = window.__MCP_ASYNC_RESULTS || {};
772
+ const token = 'mcp_' + Date.now() + '_' + Math.random().toString(36).slice(2);
773
+ (async () => {
774
+ try {
775
+ const __result__ = await (async () => { ${userCode} })();
776
+ window.__MCP_ASYNC_RESULTS[token] = {
777
+ status: 'fulfilled',
778
+ value: JSON.stringify(__result__)
779
+ };
780
+ } catch (e) {
781
+ window.__MCP_ASYNC_RESULTS[token] = {
782
+ status: 'rejected',
783
+ error: String(e && e.message || e)
784
+ };
785
+ }
786
+ })();
787
+ return token;
788
+ } catch (e) {
789
+ return 'ERROR_BOOTSTRAP:' + String(e && e.message || e);
790
+ }
791
+ })();
792
+ `.trim();
793
+
794
+ // Escape for AppleScript
795
+ const asQuote = (s) =>
796
+ s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
797
+
798
+ const jsBootEsc = asQuote(bootstrapJs);
799
+ const pollSeconds = (200 / 1000).toFixed(3);
800
+ const serverTimeout = timeout_ms + 5000; // Buffer for AppleScript polling
801
+
802
+ // Build AppleScript with polling logic
803
+ const script = tab_id ? `
804
+ set _timeoutMs to ${serverTimeout}
805
+ set _pollSec to ${pollSeconds} as real
806
+ tell application "Google Chrome"
807
+ set _token to ""
808
+ repeat with w in windows
809
+ repeat with t in tabs of w
810
+ if (id of t as string) is "${tab_id}" then
811
+ set _token to execute t javascript "${jsBootEsc}"
812
+ exit repeat
813
+ end if
814
+ end repeat
815
+ if _token is not "" then exit repeat
816
+ end repeat
817
+ if _token is "" then return "Tab not found"
818
+
819
+ set _t0 to (current date)
820
+ repeat
821
+ set _status to execute active tab of front window javascript "(() => { var r = window.__MCP_ASYNC_RESULTS && window.__MCP_ASYNC_RESULTS['\" & _token & \"']; return r ? r.status : 'pending'; })()"
822
+ if _status is "fulfilled" then
823
+ set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
824
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
825
+ return _val
826
+ else if _status is "rejected" then
827
+ set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
828
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
829
+ return "ERROR:" & _err
830
+ end if
831
+
832
+ set _elapsedMs to ((current date) - _t0) * 1000
833
+ if _elapsedMs > _timeoutMs then
834
+ execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
835
+ return "TIMEOUT"
836
+ end if
837
+ delay _pollSec
838
+ end repeat
839
+ end tell
840
+ ` : `
841
+ set _timeoutMs to ${serverTimeout}
842
+ set _pollSec to ${pollSeconds} as real
843
+ tell application "Google Chrome"
844
+ set _token to execute active tab of front window javascript "${jsBootEsc}"
845
+ if _token starts with "ERROR_BOOTSTRAP:" then return _token
846
+ set _t0 to (current date)
847
+ repeat
848
+ set _status to execute active tab of front window javascript "(() => { var r = window.__MCP_ASYNC_RESULTS && window.__MCP_ASYNC_RESULTS['\" & _token & \"']; return r ? r.status : 'pending'; })()"
849
+ if _status is "fulfilled" then
850
+ set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
851
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
852
+ return _val
853
+ else if _status is "rejected" then
854
+ set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
855
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
856
+ return "ERROR:" & _err
857
+ end if
858
+
859
+ set _elapsedMs to ((current date) - _t0) * 1000
860
+ if _elapsedMs > _timeoutMs then
861
+ execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
862
+ return "TIMEOUT"
863
+ end if
864
+ delay _pollSec
865
+ end repeat
866
+ end tell
867
+ `;
868
+
869
+ const result = await this.executeAppleScript(script);
870
+
871
+ // Normalize response
872
+ if (typeof result === 'string' && result.startsWith('ERROR:')) {
873
+ return { content: [{ type: 'text', text: result }] };
874
+ }
875
+ try {
876
+ const parsed = JSON.parse(result);
877
+ return { content: [{ type: 'text', text: typeof parsed === 'string' ? parsed : JSON.stringify(parsed) }] };
878
+ } catch {
879
+ return { content: [{ type: 'text', text: result }] };
880
+ }
881
+ }
882
+
883
+ default:
884
+ throw new Error(`Unknown tool: ${name}`);
885
+ }
886
+ } catch (error) {
887
+ return {
888
+ content: [{ type: 'text', text: `Error: ${error.message}` }],
889
+ isError: true
890
+ };
891
+ }
892
+ });
893
+ }
894
+
895
+ async run() {
896
+ const transport = new StdioServerTransport();
897
+ await this.server.connect(transport);
898
+ console.error('Chrome Control MCP server running on stdio');
899
+ }
900
+ }
901
+
902
+ const server = new ChromeControlServer();
903
+ server.run().catch(console.error);