mcp-google-multi 6.0.0-beta.1 → 6.0.0-beta.3

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 (182) hide show
  1. package/README.md +5 -3
  2. package/dist/accounts.d.ts +22 -1
  3. package/dist/accounts.js +64 -16
  4. package/dist/api-probe.d.ts +5 -0
  5. package/dist/api-probe.js +23 -15
  6. package/dist/arg-normalize.d.ts +61 -4
  7. package/dist/arg-normalize.js +229 -4
  8. package/dist/arg-strict.d.ts +61 -0
  9. package/dist/arg-strict.js +193 -0
  10. package/dist/auth.d.ts +4 -3
  11. package/dist/auth.js +26 -85
  12. package/dist/boot-gates.d.ts +26 -0
  13. package/dist/boot-gates.js +38 -0
  14. package/dist/cimd-cache.d.ts +38 -0
  15. package/dist/cimd-cache.js +117 -0
  16. package/dist/client.d.ts +32 -2
  17. package/dist/client.js +0 -0
  18. package/dist/compose.d.ts +11 -0
  19. package/dist/compose.js +109 -0
  20. package/dist/config-file.d.ts +14 -0
  21. package/dist/config-file.js +41 -1
  22. package/dist/discover.js +38 -15
  23. package/dist/discovery-client.d.ts +11 -1
  24. package/dist/discovery-client.js +120 -18
  25. package/dist/doctor.d.ts +15 -3
  26. package/dist/doctor.js +151 -27
  27. package/dist/env-load.d.ts +11 -0
  28. package/dist/env-load.js +23 -1
  29. package/dist/executor.d.ts +3 -0
  30. package/dist/executor.js +16 -3
  31. package/dist/fanout.d.ts +9 -1
  32. package/dist/fanout.js +83 -14
  33. package/dist/fs-atomic.d.ts +11 -0
  34. package/dist/fs-atomic.js +219 -28
  35. package/dist/hint-provider.d.ts +129 -0
  36. package/dist/hint-provider.js +64 -0
  37. package/dist/http-transport.d.ts +73 -6
  38. package/dist/http-transport.js +350 -26
  39. package/dist/identity.d.ts +4 -1
  40. package/dist/identity.js +25 -6
  41. package/dist/index.js +142 -114
  42. package/dist/master-key.js +13 -5
  43. package/dist/mcp-token.d.ts +136 -19
  44. package/dist/mcp-token.js +569 -72
  45. package/dist/metrics-cli.d.ts +21 -0
  46. package/dist/metrics-cli.js +206 -0
  47. package/dist/metrics-tap.d.ts +12 -0
  48. package/dist/metrics-tap.js +95 -0
  49. package/dist/migrate-config.js +2 -2
  50. package/dist/oauth-as.d.ts +103 -3
  51. package/dist/oauth-as.js +374 -79
  52. package/dist/oauth-consent.d.ts +35 -10
  53. package/dist/oauth-consent.js +101 -39
  54. package/dist/outbound-allowlist.d.ts +34 -0
  55. package/dist/outbound-allowlist.js +111 -0
  56. package/dist/reauth-hint.d.ts +1 -1
  57. package/dist/reauth-hint.js +12 -8
  58. package/dist/registry-transfer.d.ts +5 -0
  59. package/dist/registry-transfer.js +65 -5
  60. package/dist/registry.d.ts +66 -2
  61. package/dist/registry.js +214 -18
  62. package/dist/scope-catalog.d.ts +11 -0
  63. package/dist/scope-catalog.js +39 -6
  64. package/dist/scope-observability.d.ts +8 -6
  65. package/dist/scope-observability.js +29 -13
  66. package/dist/services.d.ts +17 -4
  67. package/dist/services.js +77 -6
  68. package/dist/setup-prompt.d.ts +1 -1
  69. package/dist/setup-prompt.js +1 -1
  70. package/dist/ssrf-guard.d.ts +23 -9
  71. package/dist/ssrf-guard.js +101 -62
  72. package/dist/tenant-purge.d.ts +26 -0
  73. package/dist/tenant-purge.js +67 -0
  74. package/dist/token-store.d.ts +20 -2
  75. package/dist/token-store.js +0 -0
  76. package/dist/tools/_coerce.d.ts +5 -0
  77. package/dist/tools/_coerce.js +11 -0
  78. package/dist/tools/_errors.d.ts +34 -3
  79. package/dist/tools/_errors.js +346 -53
  80. package/dist/tools/_local-files.d.ts +9 -0
  81. package/dist/tools/_local-files.js +25 -2
  82. package/dist/tools/account-wizard.d.ts +34 -2
  83. package/dist/tools/account-wizard.js +223 -65
  84. package/dist/tools/accounts-tool.d.ts +7 -0
  85. package/dist/tools/accounts-tool.js +34 -18
  86. package/dist/tools/admin.d.ts +10 -1
  87. package/dist/tools/admin.js +21 -16
  88. package/dist/tools/analytics.d.ts +27 -0
  89. package/dist/tools/analytics.js +289 -0
  90. package/dist/tools/calendar.d.ts +9 -1
  91. package/dist/tools/calendar.js +93 -29
  92. package/dist/tools/chat.d.ts +10 -1
  93. package/dist/tools/chat.js +20 -12
  94. package/dist/tools/contacts.d.ts +2 -1
  95. package/dist/tools/contacts.js +74 -43
  96. package/dist/tools/docs.d.ts +2 -1
  97. package/dist/tools/docs.js +90 -84
  98. package/dist/tools/drive.d.ts +2 -1
  99. package/dist/tools/drive.js +197 -120
  100. package/dist/tools/forms.d.ts +10 -1
  101. package/dist/tools/forms.js +26 -19
  102. package/dist/tools/generated/_shared.d.ts +8 -1
  103. package/dist/tools/generated/_shared.js +18 -4
  104. package/dist/tools/generated/admin.d.ts +2 -1
  105. package/dist/tools/generated/admin.js +610 -479
  106. package/dist/tools/generated/analytics.d.ts +3 -0
  107. package/dist/tools/generated/analytics.js +981 -0
  108. package/dist/tools/generated/appsmarket.d.ts +2 -1
  109. package/dist/tools/generated/appsmarket.js +9 -9
  110. package/dist/tools/generated/calendar.d.ts +2 -1
  111. package/dist/tools/generated/calendar.js +83 -83
  112. package/dist/tools/generated/chat.d.ts +2 -1
  113. package/dist/tools/generated/chat.js +178 -151
  114. package/dist/tools/generated/classroom.d.ts +2 -1
  115. package/dist/tools/generated/classroom.js +467 -425
  116. package/dist/tools/generated/cloudidentity.d.ts +2 -1
  117. package/dist/tools/generated/cloudidentity.js +209 -201
  118. package/dist/tools/generated/cloudsearch.d.ts +2 -1
  119. package/dist/tools/generated/cloudsearch.js +139 -138
  120. package/dist/tools/generated/contacts.d.ts +2 -1
  121. package/dist/tools/generated/contacts.js +49 -40
  122. package/dist/tools/generated/drive.d.ts +2 -1
  123. package/dist/tools/generated/drive.js +133 -124
  124. package/dist/tools/generated/driveactivity.d.ts +2 -1
  125. package/dist/tools/generated/driveactivity.js +3 -3
  126. package/dist/tools/generated/drivelabels.d.ts +2 -1
  127. package/dist/tools/generated/drivelabels.js +113 -85
  128. package/dist/tools/generated/forms.d.ts +2 -1
  129. package/dist/tools/generated/forms.js +14 -14
  130. package/dist/tools/generated/gmail.d.ts +2 -1
  131. package/dist/tools/generated/gmail.js +253 -226
  132. package/dist/tools/generated/groupsmigration.d.ts +2 -1
  133. package/dist/tools/generated/groupsmigration.js +4 -4
  134. package/dist/tools/generated/groupssettings.d.ts +2 -1
  135. package/dist/tools/generated/groupssettings.js +10 -10
  136. package/dist/tools/generated/index.d.ts +2 -1
  137. package/dist/tools/generated/index.js +2 -0
  138. package/dist/tools/generated/keep.d.ts +2 -1
  139. package/dist/tools/generated/keep.js +23 -22
  140. package/dist/tools/generated/licensing.d.ts +2 -1
  141. package/dist/tools/generated/licensing.js +54 -38
  142. package/dist/tools/generated/meet.d.ts +2 -1
  143. package/dist/tools/generated/meet.js +41 -41
  144. package/dist/tools/generated/method-map.d.ts +2 -0
  145. package/dist/tools/generated/method-map.js +894 -0
  146. package/dist/tools/generated/postmaster.d.ts +2 -1
  147. package/dist/tools/generated/postmaster.js +12 -12
  148. package/dist/tools/generated/reseller.d.ts +2 -1
  149. package/dist/tools/generated/reseller.js +69 -63
  150. package/dist/tools/generated/script.d.ts +2 -1
  151. package/dist/tools/generated/script.js +62 -52
  152. package/dist/tools/generated/searchconsole.d.ts +2 -1
  153. package/dist/tools/generated/searchconsole.js +8 -6
  154. package/dist/tools/generated/sheets.d.ts +2 -1
  155. package/dist/tools/generated/sheets.js +25 -24
  156. package/dist/tools/generated/tasks.d.ts +2 -1
  157. package/dist/tools/generated/tasks.js +15 -9
  158. package/dist/tools/generated/vault.d.ts +2 -1
  159. package/dist/tools/generated/vault.js +132 -123
  160. package/dist/tools/generated/workspaceevents.d.ts +2 -1
  161. package/dist/tools/generated/workspaceevents.js +48 -47
  162. package/dist/tools/gmail.d.ts +12 -2
  163. package/dist/tools/gmail.js +95 -51
  164. package/dist/tools/google-api.d.ts +2 -3
  165. package/dist/tools/google-api.js +76 -33
  166. package/dist/tools/meet.d.ts +10 -1
  167. package/dist/tools/meet.js +18 -11
  168. package/dist/tools/searchconsole.d.ts +2 -1
  169. package/dist/tools/searchconsole.js +27 -23
  170. package/dist/tools/sheets.d.ts +2 -1
  171. package/dist/tools/sheets.js +72 -80
  172. package/dist/tools/slides.d.ts +10 -1
  173. package/dist/tools/slides.js +23 -16
  174. package/dist/tools/tasks.d.ts +2 -1
  175. package/dist/tools/tasks.js +35 -31
  176. package/dist/trim.d.ts +26 -0
  177. package/dist/trim.js +67 -0
  178. package/dist/usage-metrics.d.ts +178 -0
  179. package/dist/usage-metrics.js +621 -0
  180. package/dist/write-control.d.ts +27 -1
  181. package/dist/write-control.js +99 -12
  182. package/package.json +34 -3
@@ -1,11 +1,12 @@
1
1
  import { z } from 'zod';
2
- import { coerceArray, coerceBoolean, coerceJson } from './_coerce.js';
2
+ import { coerceArray, coerceBoolean, coerceJson, coerceNumber } from './_coerce.js';
3
3
  import { gmail as gmailClient } from '@googleapis/gmail';
4
- import { accountAliasSchema } from '../accounts.js';
4
+ import { accountArgLive } from '../accounts.js';
5
5
  import { getClient } from '../client.js';
6
- import { handleGoogleApiError, mapGoogleError } from './_errors.js';
6
+ import { handleGoogleApiError, invalidParams, mapGoogleError } from './_errors.js';
7
7
  import { buildReplyHeaders, composeRaw, renderMarkdown, htmlToMarkdown, HeaderInjectionError } from './gmail-mime.js';
8
- import { prepareLocalDest } from './_local-files.js';
8
+ import { hostFilesRefused, prepareLocalDest } from './_local-files.js';
9
+ import { checkOutbound } from '../outbound-allowlist.js';
9
10
  import addressparser from 'nodemailer/lib/addressparser/index.js';
10
11
  import { lookup as lookupMime } from 'mime-types';
11
12
  import { configDir } from '../config-file.js';
@@ -13,7 +14,6 @@ import { getTokenDir } from '../accounts.js';
13
14
  import { sliceClean } from '../trim.js';
14
15
  import * as path from 'path';
15
16
  import * as fs from 'fs';
16
- const accountEnum = accountAliasSchema.optional();
17
17
  function getHeader(headers, name) {
18
18
  return headers?.find((h) => h.name?.toLowerCase() === name.toLowerCase())?.value ?? '';
19
19
  }
@@ -106,9 +106,11 @@ export function deriveReplySubject(sourceSubject) {
106
106
  // The account's own-address set (primary + Gmail send-as aliases) used to
107
107
  // exclude the caller from reply-all. Send-as rarely changes, so memoize per
108
108
  // process; a stale miss only costs one extra self-copy, never a wrong send.
109
+ // Keyed by alias AND mailbox: two contexts can share an alias name.
109
110
  const ownAddressCache = new Map();
110
111
  function getOwnAddresses(gmail, account, primaryEmail) {
111
- let cached = ownAddressCache.get(account);
112
+ const key = `${account} ${normAddr(primaryEmail)}`;
113
+ let cached = ownAddressCache.get(key);
112
114
  if (!cached) {
113
115
  cached = (async () => {
114
116
  const set = new Set([normAddr(primaryEmail)]);
@@ -124,7 +126,7 @@ function getOwnAddresses(gmail, account, primaryEmail) {
124
126
  }
125
127
  return set;
126
128
  })();
127
- ownAddressCache.set(account, cached);
129
+ ownAddressCache.set(key, cached);
128
130
  }
129
131
  return cached;
130
132
  }
@@ -423,18 +425,44 @@ export async function readBatch(gmail, account, ids, full, rawHtml) {
423
425
  const summary = { counts: { ok, failed }, ...(truncatedAny ? { truncated: true } : {}) };
424
426
  return [...entries, summary];
425
427
  }
426
- export function registerGmailTools(server) {
428
+ /** Compact gmail_search row: just the pick-one-message selection signal, with
429
+ * the snippet flattened to one bounded line. Pure. */
430
+ export function compactMessageRow(m) {
431
+ const snippet = m.snippet.replace(/\s+/g, ' ').trim();
432
+ return {
433
+ id: m.id,
434
+ from: m.from,
435
+ subject: m.subject,
436
+ date: m.date,
437
+ snippet: snippet.length > 120 ? `${snippet.slice(0, 119)}…` : snippet,
438
+ };
439
+ }
440
+ export function registerGmailTools(server, deps = {}) {
441
+ // Per-registry, LIVE account enum + injectable client (S1.10): the
442
+ // schema follows the registry's account view at parse time, and the
443
+ // custody path is the context's, not the process global.
444
+ const accountEnum = accountArgLive(() => server.accountAliases()).optional();
445
+ const getClientFn = deps.getClientFn ?? getClient;
446
+ const localFiles = deps.localFiles ?? true;
447
+ const registerHostFileTool = localFiles ? server.registerTool : (() => undefined);
427
448
  server.registerTool('gmail_search', {
428
- description: 'Search messages in a Gmail account',
449
+ description: 'Search messages in a Gmail account. Returns compact rows (id, from, subject, date, snippet); ' +
450
+ 'pass full=true for threadId, to, labelIds and the untruncated snippet.',
429
451
  inputSchema: {
430
452
  account: accountEnum.describe('Google account alias'),
431
453
  query: z.string().describe('Gmail search syntax, e.g. "from:monaam is:unread"'),
432
- maxResults: z.number().min(1).max(100).default(20).optional()
454
+ maxResults: coerceNumber(z.number().min(1).max(100)).optional()
433
455
  .describe('Max results to return (default: 20, max: 100)'),
456
+ full: coerceBoolean.optional().describe('Return the full row shape instead of the compact default'),
434
457
  },
435
- }, async ({ account, query, maxResults }) => {
458
+ }, async ({ account, query, maxResults, full }) => {
436
459
  try {
437
- const auth = await getClient(account);
460
+ // Gmail treats a blank `q` as no filter, so a caller passing an unset
461
+ // variable got the whole mailbox back as if it had matched.
462
+ if (query.trim() === '') {
463
+ return invalidParams(account, '`query` is empty, and Gmail reads an empty query as "match everything".', 'Pass a real Gmail search term such as "is:unread" or "from:someone@example.com". Returning the whole mailbox for a blank query would look like a successful search.');
464
+ }
465
+ const auth = await getClientFn(account);
438
466
  const gmail = gmailClient({ version: 'v1', auth });
439
467
  const listRes = await gmail.users.messages.list({
440
468
  userId: 'me',
@@ -466,8 +494,12 @@ export function registerGmailTools(server) {
466
494
  });
467
495
  }
468
496
  }
497
+ // Search is a pick-one-message step ~always followed by gmail_read;
498
+ // the compact row is the selection signal, the rest was measured burn
499
+ // (p90 14.4k chars per call). full=true restores the pre-6.0 shape.
500
+ const rows = full === true ? results : results.map(compactMessageRow);
469
501
  return {
470
- content: [{ type: 'text', text: JSON.stringify(results, null, 2) }],
502
+ content: [{ type: 'text', text: JSON.stringify(rows, null, 2) }],
471
503
  };
472
504
  }
473
505
  catch (error) {
@@ -480,14 +512,14 @@ export function registerGmailTools(server) {
480
512
  description: 'Read a full Gmail message by ID (body capped at 50k chars unless full=true)',
481
513
  inputSchema: {
482
514
  account: accountEnum.describe('Google account alias'),
483
- messageId: z.string().describe('Gmail message ID'),
515
+ messageId: z.string().min(1).describe('Gmail message ID'),
484
516
  full: coerceBoolean.optional().describe('Return the entire body without the character cap'),
485
517
  rawHtml: coerceBoolean.optional()
486
518
  .describe('Return the HTML body unconverted instead of the plain-text rendering (HTML-only messages)'),
487
519
  },
488
520
  }, async ({ account, messageId, full, rawHtml }) => {
489
521
  try {
490
- const auth = await getClient(account);
522
+ const auth = await getClientFn(account);
491
523
  const gmail = gmailClient({ version: 'v1', auth });
492
524
  const res = await gmail.users.messages.get({
493
525
  userId: 'me',
@@ -509,7 +541,7 @@ export function registerGmailTools(server) {
509
541
  description: 'Read all messages in a Gmail thread (bodies capped at 50k chars each unless full=true). mode=summary returns headers + snippets only.',
510
542
  inputSchema: {
511
543
  account: accountEnum.describe('Google account alias'),
512
- threadId: z.string().describe('Gmail thread ID'),
544
+ threadId: z.string().min(1).describe('Gmail thread ID'),
513
545
  full: coerceBoolean.optional().describe('Return entire bodies without the character cap'),
514
546
  rawHtml: coerceBoolean.optional()
515
547
  .describe('Return HTML bodies unconverted instead of the plain-text rendering (HTML-only messages)'),
@@ -518,7 +550,7 @@ export function registerGmailTools(server) {
518
550
  },
519
551
  }, async ({ account, threadId, full, rawHtml, mode }) => {
520
552
  try {
521
- const auth = await getClient(account);
553
+ const auth = await getClientFn(account);
522
554
  const gmail = gmailClient({ version: 'v1', auth });
523
555
  if (mode === 'summary') {
524
556
  const res = await gmail.users.threads.get({
@@ -568,7 +600,7 @@ export function registerGmailTools(server) {
568
600
  },
569
601
  }, async ({ account, ids, full, rawHtml }) => {
570
602
  try {
571
- const auth = await getClient(account);
603
+ const auth = await getClientFn(account);
572
604
  const gmail = gmailClient({ version: 'v1', auth });
573
605
  const result = await readBatch(gmail, account, ids ?? [], full === true, rawHtml === true);
574
606
  return {
@@ -598,13 +630,15 @@ export function registerGmailTools(server) {
598
630
  .describe('With replyToMessageId: include the source To+Cc (minus your own addresses) in cc. Default false (reply to sender only).'),
599
631
  replyToThreadId: z.string().optional()
600
632
  .describe('Thread ID to send the message in'),
601
- attachments: coerceJson(attachmentSchema),
633
+ ...(localFiles ? { attachments: coerceJson(attachmentSchema) } : {}),
602
634
  },
603
635
  }, async ({ account, to, subject, body, htmlBody, allowRawHtml, cc, replyToMessageId, replyAll, replyToThreadId, attachments }) => {
636
+ if (!localFiles && attachments?.length)
637
+ return hostFilesRefused(account, 'attachments');
604
638
  try {
605
- const auth = await getClient(account);
639
+ const auth = await getClientFn(account);
606
640
  const gmail = gmailClient({ version: 'v1', auth });
607
- const config = (await import('../accounts.js')).getAccountSet().configs[account];
641
+ const config = server.accountSet().configs[account];
608
642
  if (htmlBody !== undefined) {
609
643
  throw new GmailComposeError('E_HTMLBODY_REMOVED', 'htmlBody was removed in v6: author Markdown in `body`; for literal HTML pass `allowRawHtml: true`.');
610
644
  }
@@ -625,6 +659,10 @@ export function registerGmailTools(server) {
625
659
  if (finalSubject === undefined) {
626
660
  throw new GmailComposeError('E_MISSING_SUBJECT', '`subject` is required (or set replyToMessageId to derive it from the source).');
627
661
  }
662
+ // After derivation so reply-autofilled recipients are gated too.
663
+ const outbound = checkOutbound('gmail recipient', [...parseAddresses(finalTo), ...parseAddresses(finalCc ?? '')].map((a) => a.address), account);
664
+ if (outbound)
665
+ return outbound;
628
666
  const html = renderMarkdown(body, allowRawHtml === true);
629
667
  const files = await readAttachments(attachments, Buffer.byteLength(body ?? '') + Buffer.byteLength(html));
630
668
  const encoded = await composeRaw({
@@ -658,18 +696,18 @@ export function registerGmailTools(server) {
658
696
  return mapped ?? handleGmailError(error, account);
659
697
  }
660
698
  });
661
- server.registerTool('gmail_download_attachment', {
699
+ registerHostFileTool('gmail_download_attachment', {
662
700
  description: 'Download an email attachment to local disk. Use gmail_read first to get the attachmentId.',
663
701
  inputSchema: {
664
702
  account: accountEnum.describe('Google account alias'),
665
- messageId: z.string().describe('The Gmail message ID'),
666
- attachmentId: z.string().describe('The attachment ID from gmail_read response'),
703
+ messageId: z.string().min(1).describe('The Gmail message ID'),
704
+ attachmentId: z.string().min(1).describe('The attachment ID from gmail_read response'),
667
705
  filename: z.string().describe('Filename to save as (e.g. report.xlsx)'),
668
- savePath: z.string().describe('Absolute DIRECTORY path to save into (created if missing, on the machine running the server), e.g. /home/user/Downloads; the file name comes from `filename`'),
706
+ savePath: z.string().min(1).describe('Absolute DIRECTORY path to save into (created if missing, on the machine running the server), e.g. /home/user/Downloads; the file name comes from `filename`'),
669
707
  },
670
708
  }, async ({ account, messageId, attachmentId, filename, savePath }) => {
671
709
  try {
672
- const auth = await getClient(account);
710
+ const auth = await getClientFn(account);
673
711
  const gmail = gmailClient({ version: 'v1', auth });
674
712
  const res = await gmail.users.messages.attachments.get({
675
713
  userId: 'me',
@@ -709,13 +747,15 @@ export function registerGmailTools(server) {
709
747
  .describe('With replyToMessageId: include the source To+Cc (minus your own addresses) in cc. Default false (reply to sender only).'),
710
748
  replyToThreadId: z.string().optional()
711
749
  .describe('Thread ID to associate the draft with'),
712
- attachments: coerceJson(attachmentSchema),
750
+ ...(localFiles ? { attachments: coerceJson(attachmentSchema) } : {}),
713
751
  },
714
752
  }, async ({ account, to, subject, body, htmlBody, allowRawHtml, cc, replyToMessageId, replyAll, replyToThreadId, attachments }) => {
753
+ if (!localFiles && attachments?.length)
754
+ return hostFilesRefused(account, 'attachments');
715
755
  try {
716
- const auth = await getClient(account);
756
+ const auth = await getClientFn(account);
717
757
  const gmail = gmailClient({ version: 'v1', auth });
718
- const config = (await import('../accounts.js')).getAccountSet().configs[account];
758
+ const config = server.accountSet().configs[account];
719
759
  if (htmlBody !== undefined) {
720
760
  throw new GmailComposeError('E_HTMLBODY_REMOVED', 'htmlBody was removed in v6: author Markdown in `body`; for literal HTML pass `allowRawHtml: true`.');
721
761
  }
@@ -734,6 +774,10 @@ export function registerGmailTools(server) {
734
774
  if (finalSubject === undefined) {
735
775
  throw new GmailComposeError('E_MISSING_SUBJECT', '`subject` is required (or set replyToMessageId to derive it from the source).');
736
776
  }
777
+ // After derivation so reply-autofilled recipients are gated too.
778
+ const outbound = checkOutbound('gmail recipient', [...parseAddresses(finalTo), ...parseAddresses(finalCc ?? '')].map((a) => a.address), account);
779
+ if (outbound)
780
+ return outbound;
737
781
  const html = renderMarkdown(body, allowRawHtml === true);
738
782
  const files = await readAttachments(attachments, Buffer.byteLength(body ?? '') + Buffer.byteLength(html));
739
783
  const encoded = await composeRaw({
@@ -773,13 +817,13 @@ export function registerGmailTools(server) {
773
817
  description: 'Add or remove labels on a Gmail message. Use system label IDs like STARRED, UNREAD, INBOX, TRASH, or custom label IDs from gmail_list_labels.',
774
818
  inputSchema: {
775
819
  account: accountEnum.describe('Google account alias'),
776
- messageId: z.string().describe('Gmail message ID'),
820
+ messageId: z.string().min(1).describe('Gmail message ID'),
777
821
  addLabelIds: coerceArray(z.string()).optional().describe('Label IDs to add'),
778
822
  removeLabelIds: coerceArray(z.string()).optional().describe('Label IDs to remove'),
779
823
  },
780
824
  }, async ({ account, messageId, addLabelIds, removeLabelIds }) => {
781
825
  try {
782
- const auth = await getClient(account);
826
+ const auth = await getClientFn(account);
783
827
  const gmail = gmailClient({ version: 'v1', auth });
784
828
  const res = await gmail.users.messages.modify({
785
829
  userId: 'me',
@@ -802,11 +846,11 @@ export function registerGmailTools(server) {
802
846
  description: 'Move a Gmail message to Trash (recoverable)',
803
847
  inputSchema: {
804
848
  account: accountEnum.describe('Google account alias'),
805
- messageId: z.string().describe('Gmail message ID'),
849
+ messageId: z.string().min(1).describe('Gmail message ID'),
806
850
  },
807
851
  }, async ({ account, messageId }) => {
808
852
  try {
809
- const auth = await getClient(account);
853
+ const auth = await getClientFn(account);
810
854
  const gmail = gmailClient({ version: 'v1', auth });
811
855
  const res = await gmail.users.messages.trash({ userId: 'me', id: messageId });
812
856
  return {
@@ -822,11 +866,11 @@ export function registerGmailTools(server) {
822
866
  description: 'Permanently and irreversibly delete a Gmail message. No recovery possible.',
823
867
  inputSchema: {
824
868
  account: accountEnum.describe('Google account alias'),
825
- messageId: z.string().describe('Gmail message ID'),
869
+ messageId: z.string().min(1).describe('Gmail message ID'),
826
870
  },
827
871
  }, async ({ account, messageId }) => {
828
872
  try {
829
- const auth = await getClient(account);
873
+ const auth = await getClientFn(account);
830
874
  const gmail = gmailClient({ version: 'v1', auth });
831
875
  await gmail.users.messages.delete({ userId: 'me', id: messageId });
832
876
  return {
@@ -848,7 +892,7 @@ export function registerGmailTools(server) {
848
892
  },
849
893
  }, async ({ account, messageIds, addLabelIds, removeLabelIds }) => {
850
894
  try {
851
- const auth = await getClient(account);
895
+ const auth = await getClientFn(account);
852
896
  const gmail = gmailClient({ version: 'v1', auth });
853
897
  await gmail.users.messages.batchModify({
854
898
  userId: 'me',
@@ -875,7 +919,7 @@ export function registerGmailTools(server) {
875
919
  },
876
920
  }, async ({ account, messageIds }) => {
877
921
  try {
878
- const auth = await getClient(account);
922
+ const auth = await getClientFn(account);
879
923
  const gmail = gmailClient({ version: 'v1', auth });
880
924
  await gmail.users.messages.batchDelete({
881
925
  userId: 'me',
@@ -900,7 +944,7 @@ export function registerGmailTools(server) {
900
944
  },
901
945
  }, async ({ account, maxResults, query }) => {
902
946
  try {
903
- const auth = await getClient(account);
947
+ const auth = await getClientFn(account);
904
948
  const gmail = gmailClient({ version: 'v1', auth });
905
949
  const res = await gmail.users.drafts.list({
906
950
  userId: 'me',
@@ -920,11 +964,11 @@ export function registerGmailTools(server) {
920
964
  description: 'Read the full content of a specific Gmail draft',
921
965
  inputSchema: {
922
966
  account: accountEnum.describe('Google account alias'),
923
- draftId: z.string().describe('Draft ID'),
967
+ draftId: z.string().min(1).describe('Draft ID'),
924
968
  },
925
969
  }, async ({ account, draftId }) => {
926
970
  try {
927
- const auth = await getClient(account);
971
+ const auth = await getClientFn(account);
928
972
  const gmail = gmailClient({ version: 'v1', auth });
929
973
  const res = await gmail.users.drafts.get({
930
974
  userId: 'me',
@@ -944,11 +988,11 @@ export function registerGmailTools(server) {
944
988
  description: 'Send an existing Gmail draft by its draft ID',
945
989
  inputSchema: {
946
990
  account: accountEnum.describe('Google account alias'),
947
- draftId: z.string().describe('Draft ID to send'),
991
+ draftId: z.string().min(1).describe('Draft ID to send'),
948
992
  },
949
993
  }, async ({ account, draftId }) => {
950
994
  try {
951
- const auth = await getClient(account);
995
+ const auth = await getClientFn(account);
952
996
  const gmail = gmailClient({ version: 'v1', auth });
953
997
  const res = await gmail.users.drafts.send({
954
998
  userId: 'me',
@@ -970,7 +1014,7 @@ export function registerGmailTools(server) {
970
1014
  },
971
1015
  }, async ({ account }) => {
972
1016
  try {
973
- const auth = await getClient(account);
1017
+ const auth = await getClientFn(account);
974
1018
  const gmail = gmailClient({ version: 'v1', auth });
975
1019
  const res = await gmail.users.labels.list({ userId: 'me' });
976
1020
  return {
@@ -994,7 +1038,7 @@ export function registerGmailTools(server) {
994
1038
  },
995
1039
  }, async ({ account, name, messageListVisibility, labelListVisibility }) => {
996
1040
  try {
997
- const auth = await getClient(account);
1041
+ const auth = await getClientFn(account);
998
1042
  const gmail = gmailClient({ version: 'v1', auth });
999
1043
  const res = await gmail.users.labels.create({
1000
1044
  userId: 'me',
@@ -1017,11 +1061,11 @@ export function registerGmailTools(server) {
1017
1061
  description: 'Permanently delete a Gmail label and remove it from all messages',
1018
1062
  inputSchema: {
1019
1063
  account: accountEnum.describe('Google account alias'),
1020
- labelId: z.string().describe('Label ID to delete'),
1064
+ labelId: z.string().min(1).describe('Label ID to delete'),
1021
1065
  },
1022
1066
  }, async ({ account, labelId }) => {
1023
1067
  try {
1024
- const auth = await getClient(account);
1068
+ const auth = await getClientFn(account);
1025
1069
  const gmail = gmailClient({ version: 'v1', auth });
1026
1070
  await gmail.users.labels.delete({ userId: 'me', id: labelId });
1027
1071
  return {
@@ -1040,7 +1084,7 @@ export function registerGmailTools(server) {
1040
1084
  },
1041
1085
  }, async ({ account }) => {
1042
1086
  try {
1043
- const auth = await getClient(account);
1087
+ const auth = await getClientFn(account);
1044
1088
  const gmail = gmailClient({ version: 'v1', auth });
1045
1089
  const res = await gmail.users.getProfile({ userId: 'me' });
1046
1090
  return {
@@ -1056,7 +1100,7 @@ export function registerGmailTools(server) {
1056
1100
  description: 'Get all mailbox changes since a given historyId. Useful for detecting new emails since last check.',
1057
1101
  inputSchema: {
1058
1102
  account: accountEnum.describe('Google account alias'),
1059
- startHistoryId: z.string().describe('History ID from a previous gmail_get_profile or gmail_read response'),
1103
+ startHistoryId: z.string().min(1).describe('History ID from a previous gmail_get_profile or gmail_read response'),
1060
1104
  maxResults: z.number().min(1).max(500).default(100).optional()
1061
1105
  .describe('Max results to return (default: 100)'),
1062
1106
  historyTypes: coerceArray(z.enum(['messageAdded', 'messageDeleted', 'labelAdded', 'labelRemoved'])).optional()
@@ -1064,7 +1108,7 @@ export function registerGmailTools(server) {
1064
1108
  },
1065
1109
  }, async ({ account, startHistoryId, maxResults, historyTypes }) => {
1066
1110
  try {
1067
- const auth = await getClient(account);
1111
+ const auth = await getClientFn(account);
1068
1112
  const gmail = gmailClient({ version: 'v1', auth });
1069
1113
  const res = await gmail.users.history.list({
1070
1114
  userId: 'me',
@@ -1088,7 +1132,7 @@ export function registerGmailTools(server) {
1088
1132
  },
1089
1133
  }, async ({ account }) => {
1090
1134
  try {
1091
- const auth = await getClient(account);
1135
+ const auth = await getClientFn(account);
1092
1136
  const gmail = gmailClient({ version: 'v1', auth });
1093
1137
  const res = await gmail.users.settings.getVacation({ userId: 'me' });
1094
1138
  return {
@@ -1114,7 +1158,7 @@ export function registerGmailTools(server) {
1114
1158
  },
1115
1159
  }, async ({ account, enableAutoReply, responseSubject, responseBodyPlainText, startTime, endTime, restrictToContacts, restrictToDomain }) => {
1116
1160
  try {
1117
- const auth = await getClient(account);
1161
+ const auth = await getClientFn(account);
1118
1162
  const gmail = gmailClient({ version: 'v1', auth });
1119
1163
  const res = await gmail.users.settings.updateVacation({
1120
1164
  userId: 'me',
@@ -1,10 +1,9 @@
1
1
  import type { ToolRegistry } from '../registry.js';
2
2
  import { type Policy } from '../write-control.js';
3
- import { getClient } from '../client.js';
4
3
  import { type Toolsets } from '../toolsets.js';
4
+ import { type ExecuteDeps } from '../executor.js';
5
5
  import { type DiscoveryDeps, type DiscoveryMethod } from '../discovery-client.js';
6
- export interface EscapeDeps extends DiscoveryDeps {
7
- getClientFn?: typeof getClient;
6
+ export interface EscapeDeps extends DiscoveryDeps, ExecuteDeps {
8
7
  toolsets?: Toolsets;
9
8
  }
10
9
  /** Up to three closest known ids for the unknown_method did-you-mean hint;
@@ -1,13 +1,13 @@
1
1
  import { z } from 'zod';
2
2
  import { isAllowed, writeDisabledResult } from '../write-control.js';
3
- import { accountAliasSchema } from '../accounts.js';
3
+ import { accountArgLive } from '../accounts.js';
4
4
  import { getClient } from '../client.js';
5
5
  import { coerceJson } from './_coerce.js';
6
6
  import { getToolsets, toolsetEnabled } from '../toolsets.js';
7
- import { editDistance } from '../scope-catalog.js';
7
+ import { editDistance, SUGGEST_MAX_INPUT } from '../scope-catalog.js';
8
8
  import { executeApiMethod, jsonResult } from '../executor.js';
9
- import { WORKSPACE_APIS, cudFromMethod, loadMethodIndex, searchMethods, } from '../discovery-client.js';
10
- const accountEnum = accountAliasSchema.optional();
9
+ import { SUPPORTED_APIS, resolveApiAliases, cudFromMethod, loadMethodIndex, searchMethods, MAX_SEARCH_QUERY, } from '../discovery-client.js';
10
+ import { hints } from '../hint-provider.js';
11
11
  // Policy/toolset namespace for each API alias must match the NAMED tools' service
12
12
  // names, or user deny globs and GOOGLE_TOOLSETS silently miss escape-hatch calls.
13
13
  const SERVICE_FOR_ALIAS = {
@@ -29,13 +29,24 @@ const SERVICE_FOR_ALIAS = {
29
29
  admin_reports: 'admin',
30
30
  admin_datatransfer: 'admin',
31
31
  groupssettings: 'groupssettings',
32
+ analyticsadmin: 'analytics',
33
+ analyticsdata: 'analytics',
32
34
  };
35
+ /** Discovery ids are short dotted identifiers; the bound keeps a caller from
36
+ * sending megabytes through lookup, suggestion and the echoed message. */
37
+ const MAX_METHOD_ID = 256;
38
+ const MAX_API_ALIAS = 64;
33
39
  /** Up to three closest known ids for the unknown_method did-you-mean hint;
34
40
  * bounded distance so unrelated ids never masquerade as suggestions. */
35
41
  export function nearestMethodIds(methodId, index) {
42
+ if (methodId.length > SUGGEST_MAX_INPUT)
43
+ return [];
36
44
  const maxDist = Math.max(3, Math.floor(methodId.length / 3));
45
+ const wanted = methodId.toLowerCase();
37
46
  return index
38
- .map((m) => ({ id: m.id, d: editDistance(methodId.toLowerCase(), m.id.toLowerCase()) }))
47
+ // the distance is at least the length gap, so most ids skip the DP
48
+ .filter((m) => Math.abs(m.id.length - wanted.length) <= maxDist)
49
+ .map((m) => ({ id: m.id, d: editDistance(wanted, m.id.toLowerCase()) }))
39
50
  .filter((x) => x.d <= maxDist)
40
51
  .sort((a, b) => a.d - b.d)
41
52
  .slice(0, 3)
@@ -53,37 +64,53 @@ function describeMethod(m) {
53
64
  };
54
65
  }
55
66
  export function registerEscapeTools(registry, policy, deps = {}) {
67
+ // Live per-registry account validation (S1.10), same as the curated files.
68
+ const accountEnum = accountArgLive(() => registry.accountAliases()).optional();
56
69
  const getClientFn = deps.getClientFn ?? getClient;
57
70
  const toolsets = deps.toolsets ?? getToolsets();
58
71
  const serviceForAlias = (alias) => SERVICE_FOR_ALIAS[alias] ?? alias;
59
72
  const apiEnabled = (alias) => {
60
73
  return toolsetEnabled(toolsets, serviceForAlias(alias));
61
74
  };
62
- const enabledApis = Object.keys(WORKSPACE_APIS).filter(apiEnabled);
75
+ const enabledApis = Object.keys(SUPPORTED_APIS).filter(apiEnabled);
63
76
  const apiList = enabledApis.join(', ');
64
- const toolsetDisabled = (alias) => jsonResult({
65
- error: 'toolset_disabled',
66
- message: `API "${alias}" maps to service "${serviceForAlias(alias)}", which is excluded by GOOGLE_TOOLSETS.`,
67
- hint: 'Add the service to GOOGLE_TOOLSETS (or unset it) to use this API.',
68
- retriable: false,
69
- }, true);
77
+ const toolsetDisabled = (alias) => {
78
+ const rendered = hints()?.render({ kind: 'toolset_disabled', api: alias, service: serviceForAlias(alias) });
79
+ return jsonResult({
80
+ error: 'toolset_disabled',
81
+ message: rendered?.message ?? `API "${alias}" maps to service "${serviceForAlias(alias)}", which is excluded by GOOGLE_TOOLSETS.`,
82
+ hint: rendered?.hint ?? 'Add the service to GOOGLE_TOOLSETS (or unset it) to use this API.',
83
+ retriable: false,
84
+ }, true);
85
+ };
70
86
  registry.registerMeta('google_api_search', {
71
87
  description: 'Search the Google API Discovery index for any Workspace REST method, including ones with no ' +
72
88
  'dedicated tool here. Returns method ids + parameters to invoke via google_api_call. ' +
73
89
  `APIs: ${apiList}.`,
74
90
  inputSchema: {
75
- query: z.string().describe('Keywords, e.g. "slides create presentation" or "drive revisions"'),
76
- api: z.string().optional().describe('Restrict the search to one API alias'),
91
+ query: z.string().max(MAX_SEARCH_QUERY).describe('Keywords, e.g. "slides create presentation" or "drive revisions"'),
92
+ api: z.string().max(MAX_API_ALIAS).optional().describe('Restrict the search to one API alias'),
77
93
  maxResults: z.number().min(1).max(25).default(10).optional(),
78
94
  },
79
95
  annotations: { openWorldHint: true },
80
96
  }, async ({ query, api, maxResults }) => {
81
- if (api && !WORKSPACE_APIS[api]) {
82
- return jsonResult({ error: 'unknown_api', message: `Unknown api "${api}".`, hint: `Known APIs: ${apiList}`, retriable: false }, true);
97
+ // Alias resolution: "analytics" fans out to both GA4 Discovery APIs
98
+ // instead of dead-ending on unknown_api.
99
+ let requested = null;
100
+ if (api) {
101
+ requested = resolveApiAliases(api);
102
+ if (!requested) {
103
+ registry.usageMetrics?.recordSearchApi(null);
104
+ return jsonResult({ error: 'unknown_api', message: `Unknown api "${api}".`, hint: `Known APIs: ${apiList}`, retriable: false }, true);
105
+ }
106
+ const enabled = requested.filter(apiEnabled);
107
+ if (enabled.length === 0)
108
+ return toolsetDisabled(requested[0]);
109
+ requested = enabled;
110
+ // Post-resolution SUPPORTED_APIS keys only (closed vocabulary).
111
+ registry.usageMetrics?.recordSearchApi(requested);
83
112
  }
84
- if (api && !apiEnabled(api))
85
- return toolsetDisabled(api);
86
- const apis = api ? [api] : enabledApis;
113
+ const apis = requested ?? enabledApis;
87
114
  const unavailable = [];
88
115
  const indexes = await Promise.all(apis.map(async (a) => {
89
116
  try {
@@ -96,6 +123,9 @@ export function registerEscapeTools(registry, policy, deps = {}) {
96
123
  }));
97
124
  const matches = searchMethods(indexes.flat(), query, maxResults ?? 10);
98
125
  return jsonResult({
126
+ // Teach the resolved keys whenever the input wasn't already one, so the
127
+ // follow-up google_api_call uses a real key.
128
+ ...(requested && (requested.length > 1 || requested[0] !== api) ? { resolvedApi: requested } : {}),
99
129
  methods: matches.map(describeMethod),
100
130
  ...(unavailable.length > 0 ? { unavailableApis: unavailable } : {}),
101
131
  next: 'Invoke with google_api_call({account, api, methodId, pathParams, queryParams, body}).',
@@ -104,12 +134,13 @@ export function registerEscapeTools(registry, policy, deps = {}) {
104
134
  registry.registerMeta('google_api_call', {
105
135
  description: 'Invoke any Google Workspace REST method by Discovery id (escape hatch for operations without a ' +
106
136
  'dedicated tool). Find methods with google_api_search first. Subject to the same write-control ' +
107
- 'policy as named tools. Returns JSON only — for binary/file content (media downloads, ' +
137
+ 'policy as named tools. On reads, pass a `fields` query param (Google partial response) to keep ' +
138
+ 'the payload small. Returns JSON only — for binary/file content (media downloads, ' +
108
139
  'drive.files.export) use drive_download / drive_export instead.',
109
140
  inputSchema: {
110
141
  account: accountEnum.describe('Google account alias (omit for the default account)'),
111
- api: z.string().describe(`API alias: ${apiList}`),
112
- methodId: z.string().describe('Discovery method id, e.g. "drive.revisions.list"'),
142
+ api: z.string().max(MAX_API_ALIAS).describe(`API alias: ${apiList}`),
143
+ methodId: z.string().min(1).max(MAX_METHOD_ID).describe('Discovery method id, e.g. "drive.revisions.list"'),
113
144
  pathParams: coerceJson(z.record(z.string(), z.union([z.string(), z.number()])).optional())
114
145
  .describe('Values for {placeholders} in the method path'),
115
146
  queryParams: coerceJson(z
@@ -127,14 +158,20 @@ export function registerEscapeTools(registry, policy, deps = {}) {
127
158
  annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
128
159
  _meta: { 'anthropic/maxResultSizeChars': 100_000 },
129
160
  }, async ({ account, api, methodId, pathParams, queryParams, body }) => {
130
- if (!WORKSPACE_APIS[api]) {
161
+ const resolved = resolveApiAliases(api);
162
+ if (!resolved) {
131
163
  return jsonResult({ error: 'unknown_api', message: `Unknown api "${api}".`, hint: `Known APIs: ${apiList}`, retriable: false, account }, true);
132
164
  }
133
- if (!apiEnabled(api))
134
- return toolsetDisabled(api);
165
+ if (resolved.length > 1) {
166
+ // A call targets exactly one Discovery doc; only search can fan out.
167
+ return jsonResult({ error: 'unknown_api', message: `"${api}" maps to ${resolved.length} APIs.`, hint: `Pass one of: ${resolved.join(', ')} (method ids differ per API; google_api_search({query, api: "${api}"}) finds the right one).`, retriable: false, account }, true);
168
+ }
169
+ const apiKey = resolved[0];
170
+ if (!apiEnabled(apiKey))
171
+ return toolsetDisabled(apiKey);
135
172
  let index;
136
173
  try {
137
- index = await loadMethodIndex(api, deps);
174
+ index = await loadMethodIndex(apiKey, deps);
138
175
  }
139
176
  catch (err) {
140
177
  return jsonResult({ error: 'discovery_unavailable', message: err.message, retriable: true, account }, true);
@@ -146,34 +183,40 @@ export function registerEscapeTools(registry, policy, deps = {}) {
146
183
  // alias, retry under the doc's own prefix before failing.
147
184
  const docPrefix = index[0]?.id.split('.')[0];
148
185
  const [head, ...rest] = String(methodId).split('.');
149
- if (docPrefix && head === api && head !== docPrefix && rest.length > 0) {
186
+ if (docPrefix && (head === apiKey || head === api) && head !== docPrefix && rest.length > 0) {
150
187
  const swapped = [docPrefix, ...rest].join('.');
151
188
  method = index.find((m) => m.id === swapped);
152
189
  }
153
190
  }
154
191
  if (!method) {
192
+ registry.usageMetrics?.recordEscapeMethod(null);
155
193
  const near = nearestMethodIds(String(methodId), index);
156
194
  return jsonResult({
157
195
  error: 'unknown_method',
158
- message: `No method "${methodId}" in ${api}.`,
196
+ message: `No method "${methodId}" in ${apiKey}.`,
159
197
  hint: `${near.length ? `Did you mean: ${near.join(', ')}? ` : ''}` +
160
- `Use google_api_search({query: "...", api: "${api}"}) to find the right method id.`,
198
+ `Use google_api_search({query: "...", api: "${apiKey}"}) to find the right method id.`,
161
199
  retriable: false,
162
200
  account,
163
201
  }, true);
164
202
  }
203
+ // The RESOLVED index id only, never the caller's methodId argument.
204
+ registry.usageMetrics?.recordEscapeMethod(method.id);
165
205
  const cud = cudFromMethod(method);
166
- const policyService = serviceForAlias(api);
206
+ const policyService = serviceForAlias(apiKey);
167
207
  const lastSegment = method.id.split('.').pop() ?? method.id;
168
- const toolRef = { name: `${policyService}_${lastSegment}`, service: policyService, cud };
208
+ // The escape hatch self-gates, so it needs the same scope signal the
209
+ // registry wrapper gets; without it a privileged method would slip past
210
+ // safe-writes here while its generated twin is refused.
211
+ const toolRef = { name: `${policyService}_${lastSegment}`, service: policyService, cud, scopes: method.scopes };
169
212
  if (cud !== 'read' && !isAllowed(toolRef, policy)) {
170
- return writeDisabledResult(toolRef, policy);
213
+ return writeDisabledResult(toolRef, policy, account);
171
214
  }
172
215
  return executeApiMethod(method, {
173
216
  account: account,
174
217
  pathParams: pathParams,
175
218
  queryParams: queryParams,
176
219
  body,
177
- }, { getClientFn });
220
+ }, { getClientFn, scopeDeps: deps.scopeDeps });
178
221
  });
179
222
  }
@@ -1,2 +1,11 @@
1
1
  import type { ToolRegistry } from '../registry.js';
2
- export declare function registerMeetTools(server: ToolRegistry): void;
2
+ import type { Account } from '../accounts.js';
3
+ import { type CuratedToolDeps } from '../client.js';
4
+ export declare function registerMeetTools(server: ToolRegistry, deps?: CuratedToolDeps): void;
5
+ export declare function handleMeetError(error: any, account: Account): {
6
+ content: {
7
+ type: "text";
8
+ text: string;
9
+ }[];
10
+ isError: true;
11
+ };