@kelceyp/chrome-control-mcp 0.2.0 → 0.3.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/server/index.js +259 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kelceyp/chrome-control-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "MCP server for controlling Google Chrome on macOS via AppleScript with async JavaScript support",
5
5
  "main": "server/index.js",
6
6
  "type": "module",
package/server/index.js CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  } from '@modelcontextprotocol/sdk/types.js';
9
9
  import { execFile } from 'child_process';
10
10
  import { promisify } from 'util';
11
+ import pkg from '../package.json' assert { type: 'json' };
11
12
 
12
13
  const execFileAsync = promisify(execFile);
13
14
 
@@ -16,7 +17,7 @@ class ChromeControlServer {
16
17
  this.server = new Server(
17
18
  {
18
19
  name: 'chrome-control',
19
- version: '0.1.0',
20
+ version: pkg.version,
20
21
  },
21
22
  {
22
23
  capabilities: {
@@ -185,6 +186,20 @@ class ChromeControlServer {
185
186
  },
186
187
  required: ['code']
187
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
+ }
188
203
  }
189
204
  ]
190
205
  }));
@@ -553,6 +568,249 @@ class ChromeControlServer {
553
568
  return { content: [{ type: 'text', text: result ?? '' }] };
554
569
  }
555
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.0';
579
+
580
+ // Strict-core adapter with versioning
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
+
588
+ const findTextbox = () =>
589
+ document.querySelector('[role="textbox"][contenteditable="true"]') ||
590
+ [...document.querySelectorAll('[contenteditable="true"]')].at(-1) || null;
591
+
592
+ const findForm = () => { const tb = findTextbox(); return tb?.closest('form') || null; };
593
+ const findSendButton = () =>
594
+ document.querySelector('button[data-testid*="send"],button[aria-label*="Send"],button[type="submit"]');
595
+ const inputEnabled = () => {
596
+ const tb = findTextbox(); if (!tb) return false;
597
+ return tb.getAttribute('aria-disabled') !== 'true' && !tb.closest('[aria-disabled="true"]');
598
+ };
599
+ const countUser = () =>
600
+ document.querySelectorAll('[data-message-author-role="user"],[data-author-role="user"]').length;
601
+ const countAssistant = () =>
602
+ document.querySelectorAll('[data-message-author-role="assistant"],[data-author-role="assistant"]').length;
603
+ const lastAssistantNode = () =>
604
+ [...document.querySelectorAll('[data-message-author-role="assistant"],[data-author-role="assistant"]')].at(-1) || null;
605
+
606
+ const clearInput = async () => {
607
+ const tb = findTextbox(); if (!tb) throw new Error('ChatBridge: textbox not found');
608
+ tb.focus?.({ preventScroll: true }); await sleep(10);
609
+ tb.textContent = '';
610
+ tb.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, inputType: 'deleteContentBackward', data: '' }));
611
+ tb.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'deleteContentBackward', data: '' }));
612
+ tb.dispatchEvent(new Event('change', { bubbles: true }));
613
+ await sleep(10);
614
+ };
615
+
616
+ const setText = async (text) => {
617
+ const tb = findTextbox(); if (!tb) throw new Error('ChatBridge: textbox not found');
618
+ tb.focus?.({ preventScroll: true }); await sleep(10);
619
+ const before = tb.textContent || '';
620
+ tb.textContent = before + text;
621
+ tb.dispatchEvent(new InputEvent('beforeinput', { bubbles: true, inputType: 'insertText', data: text }));
622
+ tb.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text }));
623
+ tb.dispatchEvent(new Event('change', { bubbles: true }));
624
+ await sleep(10);
625
+ };
626
+
627
+ const send = async () => {
628
+ const form = findForm();
629
+ if (form?.requestSubmit) { form.requestSubmit(); await sleep(40); }
630
+ if (inputEnabled()) {
631
+ const btn = findSendButton();
632
+ if (btn) { btn.click(); await sleep(40); }
633
+ }
634
+ };
635
+
636
+ const waitForResponseWithBaseline = async (baseline, { idleMs = 1200, timeoutMs = 120000 } = {}) => {
637
+ const t0 = now();
638
+ const preUser = baseline?.user ?? countUser();
639
+ const preAsst = baseline?.asst ?? countAssistant();
640
+
641
+ if (countUser() < preUser + 1) {
642
+ while (now() - t0 < timeoutMs) {
643
+ if (countUser() >= preUser + 1) break;
644
+ await new Promise(r => setTimeout(r, 60));
645
+ }
646
+ if (countUser() < preUser + 1) return { ok: false, reason: 'userMessageNotCommitted', ms: now() - t0 };
647
+ }
648
+
649
+ if (countAssistant() < preAsst + 1) {
650
+ while (now() - t0 < timeoutMs) {
651
+ if (countAssistant() >= preAsst + 1) break;
652
+ await new Promise(r => setTimeout(r, 60));
653
+ }
654
+ if (countAssistant() < preAsst + 1) return { ok: false, reason: 'assistantNeverStarted', ms: now() - t0 };
655
+ }
656
+
657
+ const node = lastAssistantNode();
658
+ let lastChange = now();
659
+ const obs = node ? new MutationObserver(() => { lastChange = now(); }) : null;
660
+ if (node && obs) obs.observe(node, { subtree: true, childList: true, characterData: true });
661
+
662
+ while (now() - t0 < timeoutMs) {
663
+ const idle = now() - lastChange >= idleMs;
664
+ if (idle && inputEnabled()) {
665
+ if (obs) obs.disconnect();
666
+ const text = (node?.innerText ?? node?.textContent ?? '').trim();
667
+ return { ok: true, text, ms: now() - t0 };
668
+ }
669
+ await new Promise(r => setTimeout(r, 80));
670
+ }
671
+ if (obs) obs.disconnect();
672
+ return { ok: false, reason: 'timeout', ms: now() - t0 };
673
+ };
674
+
675
+ const sendAndWait = async (text, opts) => {
676
+ const baseline = { user: countUser(), asst: countAssistant() };
677
+ await clearInput();
678
+ await setText(text);
679
+ await send();
680
+ return waitForResponseWithBaseline(baseline, opts);
681
+ };
682
+
683
+ window.ChatBridge = Object.freeze({
684
+ version: '${ADAPTER_VERSION}',
685
+ message: {
686
+ sendAndWait
687
+ }
688
+ });
689
+ })();
690
+ `.trim();
691
+
692
+ // Page-side script: ensure adapter, then sendAndWait (wrapped in async IIFE for polling)
693
+ const userCode = `
694
+ ${ADAPTER_JS}
695
+ return await window.ChatBridge.message.sendAndWait(${JSON.stringify(message)}, { idleMs: ${idle_ms}, timeoutMs: ${timeout_ms} });
696
+ `.trim();
697
+
698
+ // Build the bootstrap (same pattern as execute_javascript_async)
699
+ const bootstrapJs = `
700
+ (() => {
701
+ try {
702
+ window.__MCP_ASYNC_RESULTS = window.__MCP_ASYNC_RESULTS || {};
703
+ const token = 'mcp_' + Date.now() + '_' + Math.random().toString(36).slice(2);
704
+ (async () => {
705
+ try {
706
+ const __result__ = await (async () => { ${userCode} })();
707
+ window.__MCP_ASYNC_RESULTS[token] = {
708
+ status: 'fulfilled',
709
+ value: JSON.stringify(__result__)
710
+ };
711
+ } catch (e) {
712
+ window.__MCP_ASYNC_RESULTS[token] = {
713
+ status: 'rejected',
714
+ error: String(e && e.message || e)
715
+ };
716
+ }
717
+ })();
718
+ return token;
719
+ } catch (e) {
720
+ return 'ERROR_BOOTSTRAP:' + String(e && e.message || e);
721
+ }
722
+ })();
723
+ `.trim();
724
+
725
+ // Escape for AppleScript
726
+ const asQuote = (s) =>
727
+ s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
728
+
729
+ const jsBootEsc = asQuote(bootstrapJs);
730
+ const pollSeconds = (200 / 1000).toFixed(3);
731
+ const serverTimeout = timeout_ms + 5000; // Buffer for AppleScript polling
732
+
733
+ // Build AppleScript with polling logic
734
+ const script = tab_id ? `
735
+ set _timeoutMs to ${serverTimeout}
736
+ set _pollSec to ${pollSeconds} as real
737
+ tell application "Google Chrome"
738
+ set _token to ""
739
+ repeat with w in windows
740
+ repeat with t in tabs of w
741
+ if (id of t as string) is "${tab_id}" then
742
+ set _token to execute t javascript "${jsBootEsc}"
743
+ exit repeat
744
+ end if
745
+ end repeat
746
+ if _token is not "" then exit repeat
747
+ end repeat
748
+ if _token is "" then return "Tab not found"
749
+
750
+ set _t0 to (current date)
751
+ repeat
752
+ 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'; })()"
753
+ if _status is "fulfilled" then
754
+ set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
755
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
756
+ return _val
757
+ else if _status is "rejected" then
758
+ set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
759
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
760
+ return "ERROR:" & _err
761
+ end if
762
+
763
+ set _elapsedMs to ((current date) - _t0) * 1000
764
+ if _elapsedMs > _timeoutMs then
765
+ execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
766
+ return "TIMEOUT"
767
+ end if
768
+ delay _pollSec
769
+ end repeat
770
+ end tell
771
+ ` : `
772
+ set _timeoutMs to ${serverTimeout}
773
+ set _pollSec to ${pollSeconds} as real
774
+ tell application "Google Chrome"
775
+ set _token to execute active tab of front window javascript "${jsBootEsc}"
776
+ if _token starts with "ERROR_BOOTSTRAP:" then return _token
777
+ set _t0 to (current date)
778
+ repeat
779
+ 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'; })()"
780
+ if _status is "fulfilled" then
781
+ set _val to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].value"
782
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
783
+ return _val
784
+ else if _status is "rejected" then
785
+ set _err to execute active tab of front window javascript "window.__MCP_ASYNC_RESULTS['\" & _token & \"'].error"
786
+ execute active tab of front window javascript "delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
787
+ return "ERROR:" & _err
788
+ end if
789
+
790
+ set _elapsedMs to ((current date) - _t0) * 1000
791
+ if _elapsedMs > _timeoutMs then
792
+ execute active tab of front window javascript "if (window.__MCP_ASYNC_RESULTS) delete window.__MCP_ASYNC_RESULTS['\" & _token & \"']"
793
+ return "TIMEOUT"
794
+ end if
795
+ delay _pollSec
796
+ end repeat
797
+ end tell
798
+ `;
799
+
800
+ const result = await this.executeAppleScript(script);
801
+
802
+ // Normalize response
803
+ if (typeof result === 'string' && result.startsWith('ERROR:')) {
804
+ return { content: [{ type: 'text', text: result }] };
805
+ }
806
+ try {
807
+ const parsed = JSON.parse(result);
808
+ return { content: [{ type: 'text', text: typeof parsed === 'string' ? parsed : JSON.stringify(parsed) }] };
809
+ } catch {
810
+ return { content: [{ type: 'text', text: result }] };
811
+ }
812
+ }
813
+
556
814
  default:
557
815
  throw new Error(`Unknown tool: ${name}`);
558
816
  }