@mindstone/mcp-server-google-workspace 0.1.5 → 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 (96) hide show
  1. package/README.md +28 -9
  2. package/dist/modules/accounts/manager.js +20 -2
  3. package/dist/modules/accounts/token.d.ts +13 -0
  4. package/dist/modules/accounts/token.js +73 -58
  5. package/dist/modules/accounts/types.d.ts +1 -0
  6. package/dist/modules/calendar/service.js +9 -0
  7. package/dist/modules/chat/index.d.ts +12 -0
  8. package/dist/modules/chat/index.js +18 -0
  9. package/dist/modules/chat/scopes.d.ts +14 -0
  10. package/dist/modules/chat/scopes.js +32 -0
  11. package/dist/modules/chat/types.d.ts +88 -0
  12. package/dist/modules/chat/types.js +14 -0
  13. package/dist/modules/comments/service.js +26 -5
  14. package/dist/modules/contacts/scopes.d.ts +1 -0
  15. package/dist/modules/contacts/scopes.js +2 -2
  16. package/dist/modules/contacts/types.d.ts +34 -0
  17. package/dist/modules/docs/index.js +2 -1
  18. package/dist/modules/docs/service.js +36 -7
  19. package/dist/modules/drive/activity-service.d.ts +45 -0
  20. package/dist/modules/drive/activity-service.js +114 -0
  21. package/dist/modules/drive/index.d.ts +4 -0
  22. package/dist/modules/drive/index.js +12 -0
  23. package/dist/modules/drive/scopes.d.ts +1 -0
  24. package/dist/modules/drive/scopes.js +3 -0
  25. package/dist/modules/drive/service.d.ts +2 -1
  26. package/dist/modules/drive/service.js +29 -0
  27. package/dist/modules/drive/types.d.ts +8 -0
  28. package/dist/modules/forms/service.js +16 -3
  29. package/dist/modules/gmail/services/attachment.js +2 -1
  30. package/dist/modules/gmail/services/base.d.ts +5 -1
  31. package/dist/modules/gmail/services/base.js +10 -1
  32. package/dist/modules/gmail/services/draft.js +13 -7
  33. package/dist/modules/gmail/services/email.js +4 -3
  34. package/dist/modules/gmail/services/label.js +10 -9
  35. package/dist/modules/gmail/services/settings.d.ts +14 -1
  36. package/dist/modules/gmail/services/settings.js +96 -1
  37. package/dist/modules/gmail/types.d.ts +36 -0
  38. package/dist/modules/meet/index.d.ts +12 -0
  39. package/dist/modules/meet/index.js +18 -0
  40. package/dist/modules/meet/scopes.d.ts +9 -0
  41. package/dist/modules/meet/scopes.js +25 -0
  42. package/dist/modules/meet/types.d.ts +97 -0
  43. package/dist/modules/meet/types.js +14 -0
  44. package/dist/modules/sheets/service.js +49 -0
  45. package/dist/modules/slides/service.js +31 -6
  46. package/dist/modules/tasks/service.js +31 -6
  47. package/dist/resources/compose-email-template.d.ts +1 -1
  48. package/dist/resources/compose-email-template.js +388 -19
  49. package/dist/services/base/BaseGoogleService.d.ts +9 -1
  50. package/dist/services/base/BaseGoogleService.js +33 -1
  51. package/dist/services/chat/index.d.ts +34 -0
  52. package/dist/services/chat/index.js +120 -0
  53. package/dist/services/contacts/index.d.ts +19 -1
  54. package/dist/services/contacts/index.js +124 -0
  55. package/dist/services/meet/index.d.ts +35 -0
  56. package/dist/services/meet/index.js +116 -0
  57. package/dist/tools/calendar-handlers.js +28 -23
  58. package/dist/tools/chat-handlers.d.ts +14 -0
  59. package/dist/tools/chat-handlers.js +126 -0
  60. package/dist/tools/contacts-handlers.d.ts +31 -0
  61. package/dist/tools/contacts-handlers.js +96 -23
  62. package/dist/tools/definitions/account.js +8 -1
  63. package/dist/tools/definitions/chat.d.ts +3 -0
  64. package/dist/tools/definitions/chat.js +137 -0
  65. package/dist/tools/definitions/contacts.js +82 -0
  66. package/dist/tools/definitions/destructive-overrides.json +12 -0
  67. package/dist/tools/definitions/drive.js +132 -6
  68. package/dist/tools/definitions/gmail.js +94 -0
  69. package/dist/tools/definitions/index.d.ts +2 -0
  70. package/dist/tools/definitions/index.js +6 -0
  71. package/dist/tools/definitions/meet.d.ts +3 -0
  72. package/dist/tools/definitions/meet.js +149 -0
  73. package/dist/tools/definitions/open-world-overrides.json +12 -0
  74. package/dist/tools/drive-handlers.d.ts +27 -0
  75. package/dist/tools/drive-handlers.js +93 -2
  76. package/dist/tools/forms-handlers.js +5 -12
  77. package/dist/tools/gmail-handlers.d.ts +31 -1
  78. package/dist/tools/gmail-handlers.js +167 -35
  79. package/dist/tools/meet-handlers.d.ts +42 -0
  80. package/dist/tools/meet-handlers.js +144 -0
  81. package/dist/tools/server.js +67 -5
  82. package/dist/tools/tasks-handlers.js +7 -18
  83. package/dist/tools/type-guards.d.ts +3 -1
  84. package/dist/tools/type-guards.js +22 -2
  85. package/dist/tools/types.d.ts +13 -0
  86. package/dist/utils/apiError.d.ts +49 -0
  87. package/dist/utils/apiError.js +96 -0
  88. package/dist/utils/scope-hierarchy.js +10 -0
  89. package/dist/utils/service-initializer.js +9 -0
  90. package/dist/utils/untrusted-content.d.ts +37 -1
  91. package/dist/utils/untrusted-content.js +61 -6
  92. package/package.json +5 -1
  93. package/dist/services/calendar/index.d.ts +0 -27
  94. package/dist/services/calendar/index.js +0 -146
  95. package/dist/services/gmail/index.d.ts +0 -39
  96. package/dist/services/gmail/index.js +0 -337
@@ -1,4 +1,6 @@
1
- // NOTE: Keep this template in sync with compose-email.html.
1
+ // GENERATED by scripts/gen-compose-html.mjs — do not edit by hand.
2
+ // Regenerate with "npm run compose:template"; "npm test" runs the --check drift gate.
3
+ // The generator also writes compose-email.html, keeping the two in sync.
2
4
  export const COMPOSE_EMAIL_HTML = `
3
5
  <!DOCTYPE html>
4
6
  <html lang="en">
@@ -284,6 +286,10 @@ export const COMPOSE_EMAIL_HTML = `
284
286
  opacity: 0.85;
285
287
  }
286
288
 
289
+ .blocked-actions {
290
+ margin-top: 8px;
291
+ }
292
+
287
293
  .collapsed {
288
294
  border: 1px solid var(--border);
289
295
  border-radius: 10px;
@@ -299,6 +305,49 @@ export const COMPOSE_EMAIL_HTML = `
299
305
  .hidden {
300
306
  display: none !important;
301
307
  }
308
+
309
+ .sent-header {
310
+ display: flex;
311
+ align-items: center;
312
+ gap: 8px;
313
+ flex-wrap: wrap;
314
+ }
315
+
316
+ .sent-badge {
317
+ display: inline-flex;
318
+ align-items: center;
319
+ background: var(--success-bg);
320
+ color: var(--success-text);
321
+ border: 1px solid var(--success-border);
322
+ border-radius: 999px;
323
+ padding: 2px 10px;
324
+ font-size: 12px;
325
+ font-weight: 600;
326
+ }
327
+
328
+ .sent-timestamp {
329
+ color: var(--muted);
330
+ font-size: 12px;
331
+ }
332
+
333
+ .sent-value {
334
+ color: var(--text);
335
+ font-size: 14px;
336
+ word-break: break-word;
337
+ }
338
+
339
+ .sent-body {
340
+ color: var(--text);
341
+ font-size: 14px;
342
+ white-space: pre-wrap;
343
+ word-break: break-word;
344
+ max-height: 260px;
345
+ overflow: auto;
346
+ border: 1px solid var(--border);
347
+ border-radius: 8px;
348
+ padding: 10px 12px;
349
+ background: var(--input-bg);
350
+ }
302
351
  </style>
303
352
  </head>
304
353
  <body>
@@ -308,7 +357,7 @@ export const COMPOSE_EMAIL_HTML = `
308
357
  <button id="reopenButton" type="button" class="button button-secondary">Reopen</button>
309
358
  </div>
310
359
 
311
- <form id="composeForm" class="card" novalidate>
360
+ <form id="composeForm" class="card" novalidate aria-label="Compose email">
312
361
  <div class="field from-field">
313
362
  <label>From</label>
314
363
  <span id="fromValue" class="from-value"></span>
@@ -321,8 +370,8 @@ export const COMPOSE_EMAIL_HTML = `
321
370
  </div>
322
371
 
323
372
  <div class="toggles">
324
- <button id="toggleCcButton" type="button" class="link-button">Add CC</button>
325
- <button id="toggleBccButton" type="button" class="link-button">Add BCC</button>
373
+ <button id="toggleCcButton" type="button" class="link-button" aria-expanded="false" aria-controls="ccRow">Add CC</button>
374
+ <button id="toggleBccButton" type="button" class="link-button" aria-expanded="false" aria-controls="bccRow">Add BCC</button>
326
375
  </div>
327
376
 
328
377
  <div id="ccRow" class="field hidden">
@@ -345,12 +394,19 @@ export const COMPOSE_EMAIL_HTML = `
345
394
  <textarea id="bodyInput" class="textarea" placeholder="Write your email"></textarea>
346
395
  </div>
347
396
 
348
- <div id="errorBox" class="status error hidden">
397
+ <div id="errorBox" class="status error hidden" role="alert">
349
398
  <span id="errorText"></span>
350
399
  <button id="retryButton" type="button" class="link-button">Retry</button>
351
400
  </div>
352
401
 
353
- <div id="successBox" class="status success hidden"></div>
402
+ <div id="blockedBox" class="status warning hidden" role="status" aria-live="polite">
403
+ <span id="blockedText"></span>
404
+ <div class="blocked-actions">
405
+ <button id="openComposeButton" type="button" class="button button-secondary">Open in Gmail</button>
406
+ </div>
407
+ </div>
408
+
409
+ <div id="successBox" class="status success hidden" role="status" aria-live="polite"></div>
354
410
 
355
411
  <div id="unknownBox" class="status warning hidden" role="status" aria-live="polite">
356
412
  <strong id="unknownTitle"></strong>
@@ -365,6 +421,48 @@ export const COMPOSE_EMAIL_HTML = `
365
421
  </button>
366
422
  </div>
367
423
  </form>
424
+
425
+ <div id="sentView" class="card hidden" role="status" aria-live="polite">
426
+ <div class="sent-header">
427
+ <span class="sent-badge">Sent</span>
428
+ <span id="sentTimestamp" class="sent-timestamp"></span>
429
+ </div>
430
+
431
+ <div class="field">
432
+ <label>From</label>
433
+ <span id="sentFrom" class="sent-value"></span>
434
+ </div>
435
+
436
+ <div class="field">
437
+ <label>To</label>
438
+ <span id="sentTo" class="sent-value"></span>
439
+ </div>
440
+
441
+ <div id="sentCcField" class="field hidden">
442
+ <label>CC</label>
443
+ <span id="sentCc" class="sent-value"></span>
444
+ </div>
445
+
446
+ <div id="sentBccField" class="field hidden">
447
+ <label>BCC</label>
448
+ <span id="sentBcc" class="sent-value"></span>
449
+ </div>
450
+
451
+ <div class="field">
452
+ <label>Subject</label>
453
+ <span id="sentSubject" class="sent-value"></span>
454
+ </div>
455
+
456
+ <div class="field">
457
+ <label>Message</label>
458
+ <div id="sentBody" class="sent-body"></div>
459
+ </div>
460
+
461
+ <div class="actions">
462
+ <button id="openGmailButton" type="button" class="button button-secondary hidden">Open in Gmail</button>
463
+ <button id="sentCollapseButton" type="button" class="button button-secondary">Collapse</button>
464
+ </div>
465
+ </div>
368
466
  </div>
369
467
 
370
468
  <script>
@@ -373,15 +471,23 @@ export const COMPOSE_EMAIL_HTML = `
373
471
 
374
472
  var RESOURCE_URI = 'ui://google-workspace/compose-email';
375
473
  var currentEmail = '';
474
+ // The host prefills the draft exactly once via ui/notifications/tool-result
475
+ // on ready. We apply only the FIRST prefill and ignore any later ones, so a
476
+ // stray or hostile re-post can't silently rewrite a draft the user has
477
+ // already reviewed before clicking Send.
478
+ var draftApplied = false;
376
479
  var pendingRequestId = null;
377
480
  var pendingPayload = null;
378
481
  var sending = false;
379
482
  var collapsed = false;
380
483
  var outcomeUnknown = false;
484
+ var sent = false;
485
+ var sendBlocked = false;
486
+ var gmailUrl = null;
381
487
  var sendTimeoutId = null;
382
488
  // Just beyond the host-side tool-call timeout (60s) so a legitimately slow
383
489
  // send resolves to its real result first; this only fires when the reply
384
- // is genuinely lost (REBEL-677), so the button can never stay stuck-silent.
490
+ // is genuinely lost, so the button can never stay stuck-silent.
385
491
  var SEND_TIMEOUT_MS = 75000;
386
492
 
387
493
  var composeForm = document.getElementById('composeForm');
@@ -389,6 +495,19 @@ export const COMPOSE_EMAIL_HTML = `
389
495
  var collapsedMessage = document.getElementById('collapsedMessage');
390
496
  var reopenButton = document.getElementById('reopenButton');
391
497
 
498
+ var sentView = document.getElementById('sentView');
499
+ var sentTimestamp = document.getElementById('sentTimestamp');
500
+ var sentFrom = document.getElementById('sentFrom');
501
+ var sentTo = document.getElementById('sentTo');
502
+ var sentCcField = document.getElementById('sentCcField');
503
+ var sentCc = document.getElementById('sentCc');
504
+ var sentBccField = document.getElementById('sentBccField');
505
+ var sentBcc = document.getElementById('sentBcc');
506
+ var sentSubject = document.getElementById('sentSubject');
507
+ var sentBody = document.getElementById('sentBody');
508
+ var openGmailButton = document.getElementById('openGmailButton');
509
+ var sentCollapseButton = document.getElementById('sentCollapseButton');
510
+
392
511
  var toInput = document.getElementById('toInput');
393
512
  var ccInput = document.getElementById('ccInput');
394
513
  var bccInput = document.getElementById('bccInput');
@@ -413,6 +532,9 @@ export const COMPOSE_EMAIL_HTML = `
413
532
  var unknownBox = document.getElementById('unknownBox');
414
533
  var unknownTitle = document.getElementById('unknownTitle');
415
534
  var unknownText = document.getElementById('unknownText');
535
+ var blockedBox = document.getElementById('blockedBox');
536
+ var blockedText = document.getElementById('blockedText');
537
+ var openComposeButton = document.getElementById('openComposeButton');
416
538
 
417
539
  function applyThemeFromHostContext() {
418
540
  try {
@@ -501,21 +623,31 @@ export const COMPOSE_EMAIL_HTML = `
501
623
  );
502
624
  }
503
625
 
626
+ // Exactly one of the three panels is visible at a time: the editable form,
627
+ // the read-only sent view, or the collapsed summary bar.
628
+ function showView(view) {
629
+ composeForm.classList.toggle('hidden', view !== 'form');
630
+ sentView.classList.toggle('hidden', view !== 'sent');
631
+ collapsedState.classList.toggle('hidden', view !== 'collapsed');
632
+ postResize();
633
+ }
634
+
504
635
  function setCollapsed(nextCollapsed, message) {
505
636
  collapsed = nextCollapsed;
506
- composeForm.classList.toggle('hidden', collapsed);
507
- collapsedState.classList.toggle('hidden', !collapsed);
508
- if (message) {
509
- collapsedMessage.textContent = message;
637
+ if (nextCollapsed) {
638
+ collapsedMessage.textContent = message || 'Draft collapsed.';
639
+ showView('collapsed');
510
640
  } else {
511
- collapsedMessage.textContent = collapsed ? 'Draft collapsed.' : '';
641
+ // Expanding after a send restores the read-only sent view (never the
642
+ // editable form) so the user can re-read what went out without any risk
643
+ // of a duplicate send; before sending, it restores the editable form.
644
+ showView(sent ? 'sent' : 'form');
512
645
  }
513
- postResize();
514
646
  }
515
647
 
516
648
  function setSending(nextSending) {
517
649
  sending = nextSending;
518
- sendButton.disabled = nextSending;
650
+ sendButton.disabled = nextSending || sendBlocked;
519
651
  cancelButton.disabled = nextSending;
520
652
  toInput.disabled = nextSending;
521
653
  ccInput.disabled = nextSending;
@@ -524,6 +656,7 @@ export const COMPOSE_EMAIL_HTML = `
524
656
  bodyInput.disabled = nextSending;
525
657
  sendSpinner.classList.toggle('hidden', !nextSending);
526
658
  sendLabel.textContent = nextSending ? 'Sending…' : 'Send email';
659
+ sendButton.setAttribute('aria-busy', nextSending ? 'true' : 'false');
527
660
  postResize();
528
661
  }
529
662
 
@@ -567,7 +700,7 @@ export const COMPOSE_EMAIL_HTML = `
567
700
  // before reaching this iframe). We genuinely don't know whether the email
568
701
  // went out, so we must NOT claim success or failure: re-enable the form and
569
702
  // tell the user to verify before resending (the send is not idempotent, so
570
- // a blind retry could send a duplicate). REBEL-677 / FOX-3484.
703
+ // a blind retry could send a duplicate).
571
704
  function showSendUnknown() {
572
705
  outcomeUnknown = true;
573
706
  clearError();
@@ -591,11 +724,13 @@ export const COMPOSE_EMAIL_HTML = `
591
724
  function setCcVisible(visible) {
592
725
  ccRow.classList.toggle('hidden', !visible);
593
726
  toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';
727
+ toggleCcButton.setAttribute('aria-expanded', visible ? 'true' : 'false');
594
728
  }
595
729
 
596
730
  function setBccVisible(visible) {
597
731
  bccRow.classList.toggle('hidden', !visible);
598
732
  toggleBccButton.textContent = visible ? 'Hide BCC' : 'Add BCC';
733
+ toggleBccButton.setAttribute('aria-expanded', visible ? 'true' : 'false');
599
734
  }
600
735
 
601
736
  function readFormPayload() {
@@ -711,8 +846,190 @@ export const COMPOSE_EMAIL_HTML = `
711
846
  return null;
712
847
  }
713
848
 
849
+ function findTextBlock(blocks) {
850
+ if (!Array.isArray(blocks)) return null;
851
+ var block = blocks.find(function (c) {
852
+ return c && c.type === 'text' && typeof c.text === 'string';
853
+ });
854
+ return block ? block.text : null;
855
+ }
856
+
857
+ // Extract the send result identifiers ({ messageId, threadId, labelIds })
858
+ // from the tool-call reply. The connector attaches structuredContent, which
859
+ // super-mcp hoists onto the outer block, so the fast path is a single read.
860
+ // The envelope-unwrapping fallback keeps this robust for hosts (or replayed
861
+ // sessions) that forward only the serialized super-mcp text envelope.
862
+ function getSendMetaFromResult(result) {
863
+ if (!result || typeof result !== 'object') return null;
864
+ if (result.structuredContent && typeof result.structuredContent === 'object') {
865
+ return result.structuredContent;
866
+ }
867
+ try {
868
+ var outerText = findTextBlock(result.content);
869
+ if (typeof outerText !== 'string' && typeof result.text === 'string') {
870
+ outerText = result.text;
871
+ }
872
+ if (typeof outerText !== 'string') return null;
873
+ var envelope = JSON.parse(outerText);
874
+ if (!envelope || typeof envelope !== 'object') return null;
875
+ // outerText was the connector payload directly (no super-mcp envelope).
876
+ if (envelope.messageId || envelope.threadId) return envelope;
877
+ var inner = envelope.result;
878
+ if (!inner || typeof inner !== 'object') return null;
879
+ if (inner.structuredContent && typeof inner.structuredContent === 'object') {
880
+ return inner.structuredContent;
881
+ }
882
+ var innerText = findTextBlock(inner.content);
883
+ if (typeof innerText !== 'string') return null;
884
+ var payload = JSON.parse(innerText);
885
+ return (payload && typeof payload === 'object') ? payload : null;
886
+ } catch (_) {
887
+ return null;
888
+ }
889
+ }
890
+
891
+ // ---- Blocked-send Gmail escape hatch ----
892
+ // Shown ONLY when the user's own send preference blocks the tool
893
+ // (super-mcp TOOL_BLOCKED / -33008 + "disabled by user preference"). We
894
+ // never call the disabled tool; instead we open a prefilled Gmail compose
895
+ // window so the user finishes the send in Gmail (no copy-paste). This is
896
+ // deliberately narrow: admin-disabled ("disabled by your organization…")
897
+ // and generic security-policy blocks fall through to the normal retryable
898
+ // error, because offering a Gmail bypass there would route around a control
899
+ // the user did not set.
900
+ //
901
+ // Gmail compose URLs that get too long can silently fail to open, so we cap
902
+ // the length and degrade visibly (recipients + subject only, paste the body)
903
+ // rather than truncating without telling the user.
904
+ var GMAIL_COMPOSE_MAX_URL = 8000;
905
+ var BLOCKED_SEND_MESSAGE =
906
+ 'Sending from here is turned off in your settings. You can finish and send this email in Gmail, or turn sending back on in Settings.';
907
+
908
+ function isUserDisabledSendError(message) {
909
+ var m = String(message || '').toLowerCase();
910
+ // Anchor the code so it can't match inside a longer number (-330080),
911
+ // and require the user-preference phrase so admin-disabled / generic
912
+ // security blocks fall through to the ordinary retryable error.
913
+ return /-33008\\b/.test(m) && m.indexOf('disabled by user preference') !== -1;
914
+ }
915
+
916
+ // Base URL + path are constant (code-reviewed here, never config-provided);
917
+ // only the field VALUES vary and go through URLSearchParams, so query
918
+ // delimiters, newlines, and reserved characters become encoded data — no
919
+ // query injection or header splitting. The host ui/open-external-link
920
+ // bridge re-validates the mail.google.com host before opening.
921
+ function buildGmailComposeUrl(payload, includeBody) {
922
+ var url = new URL('https://mail.google.com/mail/');
923
+ var params = new URLSearchParams();
924
+ params.set('view', 'cm');
925
+ params.set('fs', '1');
926
+ var to = normalizeAddressList(payload.to).join(',');
927
+ if (to) params.set('to', to);
928
+ var cc = normalizeAddressList(payload.cc).join(',');
929
+ if (cc) params.set('cc', cc);
930
+ var bcc = normalizeAddressList(payload.bcc).join(',');
931
+ if (bcc) params.set('bcc', bcc);
932
+ var subject = trimString(payload.subject);
933
+ if (subject) params.set('su', subject);
934
+ if (includeBody) {
935
+ var body = String(payload.body || '');
936
+ if (body) params.set('body', body);
937
+ }
938
+ url.search = params.toString();
939
+ return url.toString();
940
+ }
941
+
942
+ function showBlockedSend() {
943
+ sendBlocked = true;
944
+ clearError();
945
+ clearSuccess();
946
+ clearUnknown();
947
+ sendButton.disabled = true;
948
+ sendButton.title =
949
+ 'Sending from here is turned off in your settings. Turn it back on in Settings, or open this draft in Gmail to send.';
950
+ blockedText.textContent = BLOCKED_SEND_MESSAGE;
951
+ blockedBox.classList.remove('hidden');
952
+ postResize();
953
+ }
954
+
955
+ openComposeButton.addEventListener('click', function () {
956
+ // Reset any prior "too long" note, then rebuild from the live form so
957
+ // edits made after the block are reflected.
958
+ blockedText.textContent = BLOCKED_SEND_MESSAGE;
959
+ var payload = readFormPayload();
960
+ var composeUrl = buildGmailComposeUrl(payload, true);
961
+ if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {
962
+ composeUrl = buildGmailComposeUrl(payload, false);
963
+ if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {
964
+ // Even without the body the link is too long (many recipients, or a
965
+ // very long subject). Gmail would silently refuse to open it, so
966
+ // don't pretend — tell the user and post nothing.
967
+ blockedText.textContent =
968
+ 'This draft is too large to open in Gmail. Shorten the recipients or subject, or turn sending back on in Settings.';
969
+ postResize();
970
+ return;
971
+ }
972
+ blockedText.textContent =
973
+ 'This email is long, so Gmail will open with just the recipients and subject. Copy the message text above into Gmail before sending.';
974
+ postResize();
975
+ }
976
+ window.parent.postMessage(
977
+ { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: composeUrl } },
978
+ '*'
979
+ );
980
+ });
981
+
982
+ function looksLikeEmail(value) {
983
+ var at = value.indexOf('@');
984
+ return at > 0 && at === value.lastIndexOf('@') && value.indexOf(' ') === -1;
985
+ }
986
+
987
+ // Build a Gmail deep link to the just-sent message. The /u/<account> segment
988
+ // targets the right inbox when the user is signed into several Google
989
+ // accounts; #all/<id> opens the thread (falling back to the message id).
990
+ function buildGmailUrl(meta, email) {
991
+ if (!meta || typeof meta !== 'object') return null;
992
+ var id = trimString(meta.threadId) || trimString(meta.messageId);
993
+ if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;
994
+ var account = trimString(email);
995
+ var userPart = looksLikeEmail(account) ? encodeURIComponent(account) : '0';
996
+ return 'https://mail.google.com/mail/u/' + userPart + '/#all/' + encodeURIComponent(id);
997
+ }
998
+
999
+ function formatSentTime() {
1000
+ try {
1001
+ return new Date().toLocaleString(undefined, {
1002
+ month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'
1003
+ });
1004
+ } catch (_) {
1005
+ return '';
1006
+ }
1007
+ }
1008
+
1009
+ function renderSentView(payload, meta, stamp) {
1010
+ payload = payload && typeof payload === 'object' ? payload : {};
1011
+ sentTimestamp.textContent = stamp ? 'Sent ' + stamp : 'Sent';
1012
+ sentFrom.textContent = trimString(payload.email) || 'Account not shown';
1013
+ sentTo.textContent = normalizeAddressList(payload.to).join(', ');
1014
+ var ccList = normalizeAddressList(payload.cc);
1015
+ sentCc.textContent = ccList.join(', ');
1016
+ sentCcField.classList.toggle('hidden', ccList.length === 0);
1017
+ var bccList = normalizeAddressList(payload.bcc);
1018
+ sentBcc.textContent = bccList.join(', ');
1019
+ sentBccField.classList.toggle('hidden', bccList.length === 0);
1020
+ sentSubject.textContent = String(payload.subject || '');
1021
+ sentBody.textContent = String(payload.body || '');
1022
+ gmailUrl = buildGmailUrl(meta, payload.email);
1023
+ openGmailButton.classList.toggle('hidden', !gmailUrl);
1024
+ }
1025
+
714
1026
  function handleSendRequest() {
715
1027
  if (sending) return;
1028
+ // Once the user's own send preference has blocked this tool, never
1029
+ // re-invoke it — the escape hatch is the only path out. The Send button
1030
+ // is already disabled, but this also fends off a future host that grants
1031
+ // allow-forms (a submit could otherwise re-fire the disabled tool).
1032
+ if (sendBlocked) return;
716
1033
 
717
1034
  var payload = readFormPayload();
718
1035
  var validationError = validatePayload(payload);
@@ -773,6 +1090,22 @@ export const COMPOSE_EMAIL_HTML = `
773
1090
  setCollapsed(false);
774
1091
  });
775
1092
 
1093
+ sentCollapseButton.addEventListener('click', function () {
1094
+ setCollapsed(true, collapsedMessage.textContent || 'Email sent.');
1095
+ });
1096
+
1097
+ // The iframe sandbox is "allow-scripts" only (no allow-popups / allow-forms),
1098
+ // so it cannot open a URL itself. Ask the host to open the Gmail link in the
1099
+ // user's browser via the ui/open-external-link bridge, which re-validates the
1100
+ // URL against its own allowlist before handing it to the OS.
1101
+ openGmailButton.addEventListener('click', function () {
1102
+ if (!gmailUrl) return;
1103
+ window.parent.postMessage(
1104
+ { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: gmailUrl } },
1105
+ '*'
1106
+ );
1107
+ });
1108
+
776
1109
  toggleCcButton.addEventListener('click', function () {
777
1110
  setCcVisible(ccRow.classList.contains('hidden'));
778
1111
  postResize();
@@ -793,14 +1126,32 @@ export const COMPOSE_EMAIL_HTML = `
793
1126
  });
794
1127
 
795
1128
  window.addEventListener('message', function (event) {
1129
+ // Honest scope (origin-independent): the iframe sandbox origin is 'null',
1130
+ // so validating event.origin is unreliable across dev/prod/custom-scheme
1131
+ // hosts. Instead reject any *identified* sender that isn't our host frame
1132
+ // (window.parent). A real cross-frame postMessage always stamps
1133
+ // event.source with the sending window, so a hostile sibling frame is
1134
+ // rejected here; a null source only occurs for same-context synthetic
1135
+ // dispatch (our own code) and cannot be forged from outside, so we
1136
+ // tolerate it. This does not authenticate the host's identity — the host
1137
+ // separately authenticates this iframe by origin+source.
1138
+ if (event.source && event.source !== window.parent) {
1139
+ return;
1140
+ }
1141
+
796
1142
  var data = event.data;
797
1143
  if (!data || typeof data !== 'object') {
798
1144
  return;
799
1145
  }
800
1146
 
801
1147
  if (data.method === 'ui/notifications/tool-result') {
1148
+ // Always parse (so the migration-shim's malformed-envelope warning
1149
+ // still fires), but apply only the first successful prefill: a stray
1150
+ // or hostile re-post can't silently rewrite a draft the user has
1151
+ // already reviewed.
802
1152
  var draft = getDraftFromToolResult(data.params);
803
- if (draft) {
1153
+ if (draft && !draftApplied) {
1154
+ draftApplied = true;
804
1155
  applyDraftData(draft);
805
1156
  }
806
1157
  return;
@@ -819,14 +1170,32 @@ export const COMPOSE_EMAIL_HTML = `
819
1170
  var errorMessage = data.error && typeof data.error.message === 'string'
820
1171
  ? data.error.message
821
1172
  : 'Failed to send email.';
1173
+ // Prefer the host-vetted structured reason (a closed enum the host
1174
+ // derives from the tool-block error data) and fall back to
1175
+ // text-matching the flattened message for hosts that don't forward it
1176
+ // yet. Only 'user-disabled' opens the Gmail escape hatch —
1177
+ // admin-disabled and security-policy blocks stay ordinary errors (see
1178
+ // the detector comment above for why).
1179
+ var blockedReason = data.error.data && data.error.data.reason;
1180
+ if (blockedReason === 'user-disabled' || isUserDisabledSendError(errorMessage)) {
1181
+ showBlockedSend();
1182
+ return;
1183
+ }
822
1184
  showError(errorMessage);
823
1185
  return;
824
1186
  }
825
1187
 
826
1188
  clearError();
827
- showSuccess('Email sent successfully.');
828
- setCollapsed(true, 'Email sent.');
829
- reopenButton.classList.add('hidden');
1189
+ clearSuccess();
1190
+ // Preserve what was sent (and how to reach it) instead of discarding the
1191
+ // draft. pendingPayload is the exact payload we posted; the reply carries
1192
+ // the Gmail message/thread ids. We default to the collapsed summary, but
1193
+ // Reopen now restores a read-only view of the sent message.
1194
+ var sentPayload = pendingPayload || readFormPayload();
1195
+ var stamp = formatSentTime();
1196
+ renderSentView(sentPayload, getSendMetaFromResult(data.result), stamp);
1197
+ sent = true;
1198
+ setCollapsed(true, stamp ? 'Email sent · ' + stamp : 'Email sent.');
830
1199
  });
831
1200
 
832
1201
  if (typeof ResizeObserver === 'function' && document.body) {
@@ -37,8 +37,16 @@ export declare abstract class BaseGoogleService<TClient> {
37
37
  /**
38
38
  * Common error handler for Google service operations
39
39
  * Maps Google API error codes to appropriate MCP error codes
40
+ *
41
+ * Auth-handoff errors (AccountError with code AUTH_REQUIRED /
42
+ * HOST_ORCHESTRATED_AUTH_REQUIRED) pass through unchanged: rewrapping them
43
+ * here would replace the string `code` that server.ts formatErrorResponse
44
+ * keys the structured `auth_required` reconnect handoff on with a mangled
45
+ * `HTTP_AUTH_REQUIRED`, silently degrading an expired grant to a generic
46
+ * failure — the gap the Tasks/Forms/Docs/Slides/Comments service catches
47
+ * used to hit on a first-request auth failure.
40
48
  */
41
- protected handleError(error: unknown, context: string): GoogleServiceError;
49
+ protected handleError(error: unknown, context: string): Error;
42
50
  /**
43
51
  * Validates required scopes are present for an operation.
44
52
  *
@@ -2,6 +2,7 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
2
  import { getAccountManager } from '../../modules/accounts/index.js';
3
3
  import { AccountError } from '../../modules/accounts/types.js';
4
4
  import { findMissingScopes, getServiceNamesForScopes } from '../../utils/scope-hierarchy.js';
5
+ import { isAuthHandoffError } from '../../utils/apiError.js';
5
6
  /**
6
7
  * Base error class for Google services
7
8
  */
@@ -54,8 +55,18 @@ export class BaseGoogleService {
54
55
  if (tokenStatus.status === 'AUTH_REQUIRED') {
55
56
  throw new AccountError(`${this.serviceName} authentication required`, 'AUTH_REQUIRED', 'Connect Google Workspace to continue');
56
57
  }
58
+ // Transient refresh blip (a temporary network error, not a dead grant): surface a
59
+ // retryable error rather than an AUTH_REQUIRED that would push the user to reconnect a
60
+ // grant that's actually fine. formatErrorResponse maps this to a generic retry, not the
61
+ // reconnect CTA. Mirrors the canRetry handling in withTokenRenewal / listAccounts.
62
+ if (!tokenStatus.valid && tokenStatus.canRetry) {
63
+ throw new AccountError(`${this.serviceName} token refresh failed temporarily`, 'TEMPORARY_AUTH_ERROR', 'Please try again in a moment');
64
+ }
57
65
  if (!tokenStatus.valid || !tokenStatus.token) {
58
- throw new GoogleServiceError(`${this.serviceName} authentication required`, 'AUTH_REQUIRED', 'Please authenticate the account');
66
+ // AccountError (string `code`), not GoogleServiceError: the latter's numeric
67
+ // McpError code is invisible to formatErrorResponse's auth handoff, which is
68
+ // how first-request-of-the-session auth failures degraded to plain errors.
69
+ throw new AccountError(`${this.serviceName} authentication required`, 'AUTH_REQUIRED', 'Please authenticate the account');
59
70
  }
60
71
  this.oauth2Client.setCredentials(tokenStatus.token);
61
72
  const client = clientFactory(this.oauth2Client);
@@ -69,8 +80,19 @@ export class BaseGoogleService {
69
80
  /**
70
81
  * Common error handler for Google service operations
71
82
  * Maps Google API error codes to appropriate MCP error codes
83
+ *
84
+ * Auth-handoff errors (AccountError with code AUTH_REQUIRED /
85
+ * HOST_ORCHESTRATED_AUTH_REQUIRED) pass through unchanged: rewrapping them
86
+ * here would replace the string `code` that server.ts formatErrorResponse
87
+ * keys the structured `auth_required` reconnect handoff on with a mangled
88
+ * `HTTP_AUTH_REQUIRED`, silently degrading an expired grant to a generic
89
+ * failure — the gap the Tasks/Forms/Docs/Slides/Comments service catches
90
+ * used to hit on a first-request auth failure.
72
91
  */
73
92
  handleError(error, context) {
93
+ if (isAuthHandoffError(error) && error instanceof Error) {
94
+ return error;
95
+ }
74
96
  if (error instanceof GoogleServiceError) {
75
97
  return error;
76
98
  }
@@ -130,6 +152,16 @@ export class BaseGoogleService {
130
152
  // Note: tokenInfo.requiredScopes is misleadingly named - it's actually the GRANTED scopes
131
153
  const grantedScopes = tokenInfo.requiredScopes;
132
154
  if (!grantedScopes || grantedScopes.length === 0) {
155
+ if (!tokenInfo.valid) {
156
+ // Invalid/expired grant — this is an auth failure, not a scope gap. Keep the
157
+ // reconnect signal (or transient-retry signal) intact: reporting it as a
158
+ // generic SCOPE_ERROR let the swallowing service catches (Tasks/Forms/Docs/
159
+ // Slides/Comments/Sheets) flatten an expired sign-in to a plain string.
160
+ if (tokenInfo.canRetry) {
161
+ throw new AccountError(`${this.serviceName} token refresh failed temporarily`, 'TEMPORARY_AUTH_ERROR', 'Please try again in a moment');
162
+ }
163
+ throw new AccountError(`${this.serviceName} authentication required`, 'AUTH_REQUIRED', tokenInfo.reason || 'Connect Google Workspace to continue');
164
+ }
133
165
  throw new GoogleServiceError('No permissions found', 'SCOPE_ERROR', 'The Google account connection may be incomplete. ' +
134
166
  'Use remove_workspace_account to disconnect, then authenticate_workspace_account to reconnect.');
135
167
  }