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

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 (126) hide show
  1. package/README.md +20 -6
  2. package/dist/accounts.d.ts +3 -3
  3. package/dist/accounts.js +18 -31
  4. package/dist/arg-normalize.js +15 -35
  5. package/dist/arg-strict.js +8 -28
  6. package/dist/auth.d.ts +1 -1
  7. package/dist/auth.js +5 -10
  8. package/dist/boot-gates.d.ts +1 -1
  9. package/dist/boot-gates.js +3 -5
  10. package/dist/cimd-cache.js +5 -11
  11. package/dist/client-config.d.ts +2 -2
  12. package/dist/client-config.js +8 -14
  13. package/dist/client.js +0 -0
  14. package/dist/compose.d.ts +8 -1
  15. package/dist/compose.js +11 -11
  16. package/dist/config-file.js +7 -12
  17. package/dist/discover.js +6 -12
  18. package/dist/discovery-client.js +14 -33
  19. package/dist/doctor.d.ts +3 -3
  20. package/dist/doctor.js +12 -18
  21. package/dist/env-load.js +2 -5
  22. package/dist/executor.js +2 -4
  23. package/dist/fanout.js +8 -17
  24. package/dist/fs-atomic.d.ts +0 -3
  25. package/dist/fs-atomic.js +104 -22
  26. package/dist/hint-provider.d.ts +4 -1
  27. package/dist/hint-provider.js +4 -10
  28. package/dist/http-config.d.ts +2 -2
  29. package/dist/http-config.js +3 -7
  30. package/dist/http-transport.d.ts +5 -5
  31. package/dist/http-transport.js +39 -92
  32. package/dist/identity.d.ts +2 -2
  33. package/dist/identity.js +6 -9
  34. package/dist/index.js +19 -31
  35. package/dist/master-key.d.ts +3 -3
  36. package/dist/master-key.js +11 -22
  37. package/dist/mcp-token.d.ts +40 -16
  38. package/dist/mcp-token.js +121 -44
  39. package/dist/metrics-cli.d.ts +1 -1
  40. package/dist/metrics-cli.js +1 -1
  41. package/dist/metrics-tap.js +2 -5
  42. package/dist/migrate-config.d.ts +1 -2
  43. package/dist/migrate-config.js +3 -5
  44. package/dist/net-tuning.js +2 -4
  45. package/dist/oauth-as.d.ts +7 -2
  46. package/dist/oauth-as.js +45 -78
  47. package/dist/oauth-consent.js +4 -10
  48. package/dist/outbound-allowlist.js +4 -9
  49. package/dist/reauth-hint.js +2 -5
  50. package/dist/registry-transfer.d.ts +1 -1
  51. package/dist/registry-transfer.js +5 -13
  52. package/dist/registry.d.ts +3 -9
  53. package/dist/registry.js +97 -76
  54. package/dist/scope-catalog.d.ts +5 -0
  55. package/dist/scope-catalog.js +17 -7
  56. package/dist/scope-observability.d.ts +2 -3
  57. package/dist/scope-observability.js +8 -14
  58. package/dist/services.d.ts +3 -0
  59. package/dist/services.js +5 -10
  60. package/dist/ssrf-guard.js +11 -22
  61. package/dist/tenant-purge.js +2 -4
  62. package/dist/token-store.js +0 -0
  63. package/dist/tools/_coerce.d.ts +4 -4
  64. package/dist/tools/_errors.js +22 -39
  65. package/dist/tools/_local-files.js +4 -8
  66. package/dist/tools/account-wizard.d.ts +4 -3
  67. package/dist/tools/account-wizard.js +48 -54
  68. package/dist/tools/accounts-tool.d.ts +8 -1
  69. package/dist/tools/accounts-tool.js +18 -7
  70. package/dist/tools/admin.js +8 -4
  71. package/dist/tools/analytics.js +32 -16
  72. package/dist/tools/calendar.d.ts +5 -0
  73. package/dist/tools/calendar.js +63 -7
  74. package/dist/tools/chat.js +2 -3
  75. package/dist/tools/contacts.js +19 -14
  76. package/dist/tools/docs.js +45 -21
  77. package/dist/tools/drive.js +72 -39
  78. package/dist/tools/forms.js +2 -3
  79. package/dist/tools/generated/gmail.js +0 -14
  80. package/dist/tools/generated/method-map.js +1 -1
  81. package/dist/tools/gmail-mime.d.ts +1 -1
  82. package/dist/tools/gmail-mime.js +7 -12
  83. package/dist/tools/gmail.d.ts +3 -3
  84. package/dist/tools/gmail.js +135 -52
  85. package/dist/tools/google-api.js +5 -7
  86. package/dist/tools/meet.js +2 -3
  87. package/dist/tools/searchconsole.js +2 -3
  88. package/dist/tools/sheets.d.ts +10 -0
  89. package/dist/tools/sheets.js +111 -5
  90. package/dist/tools/slides.js +2 -3
  91. package/dist/tools/tasks.js +2 -3
  92. package/dist/trim.js +2 -3
  93. package/dist/usage-metrics.js +5 -12
  94. package/dist/write-control.d.ts +4 -8
  95. package/dist/write-control.js +18 -6
  96. package/package.json +24 -22
  97. package/skills/google-workspace/SKILL.md +162 -0
  98. package/skills/google-workspace/reference/admin.md +105 -0
  99. package/skills/google-workspace/reference/analytics.md +70 -0
  100. package/skills/google-workspace/reference/appsmarket.md +5 -0
  101. package/skills/google-workspace/reference/calendar.md +175 -0
  102. package/skills/google-workspace/reference/chat.md +59 -0
  103. package/skills/google-workspace/reference/classroom.md +5 -0
  104. package/skills/google-workspace/reference/cloudidentity.md +5 -0
  105. package/skills/google-workspace/reference/cloudsearch.md +5 -0
  106. package/skills/google-workspace/reference/contacts.md +138 -0
  107. package/skills/google-workspace/reference/docs.md +395 -0
  108. package/skills/google-workspace/reference/drive.md +485 -0
  109. package/skills/google-workspace/reference/driveactivity.md +5 -0
  110. package/skills/google-workspace/reference/drivelabels.md +5 -0
  111. package/skills/google-workspace/reference/forms.md +92 -0
  112. package/skills/google-workspace/reference/gmail.md +305 -0
  113. package/skills/google-workspace/reference/groupsmigration.md +5 -0
  114. package/skills/google-workspace/reference/groupssettings.md +5 -0
  115. package/skills/google-workspace/reference/keep.md +5 -0
  116. package/skills/google-workspace/reference/licensing.md +5 -0
  117. package/skills/google-workspace/reference/meet.md +68 -0
  118. package/skills/google-workspace/reference/postmaster.md +5 -0
  119. package/skills/google-workspace/reference/reseller.md +5 -0
  120. package/skills/google-workspace/reference/script.md +5 -0
  121. package/skills/google-workspace/reference/searchconsole.md +128 -0
  122. package/skills/google-workspace/reference/sheets.md +430 -0
  123. package/skills/google-workspace/reference/slides.md +67 -0
  124. package/skills/google-workspace/reference/tasks.md +167 -0
  125. package/skills/google-workspace/reference/vault.md +5 -0
  126. package/skills/google-workspace/reference/workspaceevents.md +5 -0
@@ -4,7 +4,7 @@ import { analyticsdata as analyticsdataClient } from '@googleapis/analyticsdata'
4
4
  import { analyticsadmin as analyticsadminClient } from '@googleapis/analyticsadmin';
5
5
  import { accountArgLive } from '../accounts.js';
6
6
  import { getClient } from '../client.js';
7
- import { handleGoogleApiError } from './_errors.js';
7
+ import { handleGoogleApiError, invalidParams } from './_errors.js';
8
8
  /** Accepts "213025502" or "properties/213025502"; rejects the identifiers
9
9
  * people paste by mistake (G-… measurement IDs, UA-… properties) with a
10
10
  * pointer to the right one. */
@@ -104,10 +104,14 @@ export function shapeMetadata(data) {
104
104
  const propertySchema = z
105
105
  .string()
106
106
  .describe('GA4 property: numeric ID like "213025502" or "properties/213025502" — NOT a "G-..." measurement ID and not "UA-...". Find yours with analytics_account_summaries.');
107
+ // Accepts this server's plain string form and the native GA4 API shape ({name}),
108
+ // so a request built against GA4's own docs works unmodified.
109
+ const metricOrDimensionRef = z.union([z.string(), z.object({ name: z.string() })]);
110
+ const nameOf = (ref) => (typeof ref === 'string' ? ref : ref.name);
111
+ const dateRangeRef = z.object({ startDate: z.string(), endDate: z.string() });
107
112
  export function registerAnalyticsTools(server, deps = {}) {
108
- // Per-registry, LIVE account enum + injectable client (S1.10): the
109
- // schema follows the registry's account view at parse time, and the
110
- // custody path is the context's, not the process global.
113
+ // Per-registry, live account enum + injectable client: the schema follows
114
+ // the registry's account view at parse time, not a process-global default.
111
115
  const accountEnum = accountArgLive(() => server.accountAliases()).optional();
112
116
  const getClientFn = deps.getClientFn ?? getClient;
113
117
  server.registerTool('analytics_account_summaries', {
@@ -131,16 +135,19 @@ export function registerAnalyticsTools(server, deps = {}) {
131
135
  }
132
136
  });
133
137
  server.registerTool('analytics_run_report', {
134
- description: 'Run a Google Analytics (GA4) report: metrics over a date range, optionally grouped by dimensions — the workhorse for questions like "how many users last week, by country". Dates accept YYYY-MM-DD or relative forms ("today", "yesterday", "28daysAgo"). Unsure which dimension/metric names are valid? Call analytics_get_metadata first.',
138
+ description: 'Run a Google Analytics (GA4) report: metrics over a date range, optionally grouped by dimensions — the workhorse for questions like "how many users last week, by country". Dates accept YYYY-MM-DD or relative forms ("today", "yesterday", "28daysAgo"). Also accepts the native GA4 request shapes directly: a single dateRanges entry in place of startDate/endDate, and metrics/dimensions as {name} objects. Unsure which dimension/metric names are valid? Call analytics_get_metadata first.',
135
139
  inputSchema: {
136
140
  account: accountEnum.describe('Google account alias'),
137
141
  property: propertySchema,
138
- startDate: z.string().describe('Start date: YYYY-MM-DD or relative ("today", "yesterday", "NdaysAgo" e.g. "28daysAgo")'),
139
- endDate: z.string().describe('End date: YYYY-MM-DD or relative ("today", "yesterday", "NdaysAgo")'),
140
- metrics: coerceArray(z.string()).describe('Metric API names, e.g. ["activeUsers","sessions","screenPageViews"]. Max 10. Valid names (including custom ones) come from analytics_get_metadata.'),
141
- dimensions: coerceArray(z.string())
142
+ startDate: z.string().optional().describe('Start date: YYYY-MM-DD or relative ("today", "yesterday", "NdaysAgo" e.g. "28daysAgo"). Required unless dateRanges is given.'),
143
+ endDate: z.string().optional().describe('End date: YYYY-MM-DD or relative ("today", "yesterday", "NdaysAgo"). Required unless dateRanges is given.'),
144
+ dateRanges: coerceJson(z.array(dateRangeRef))
142
145
  .optional()
143
- .describe('Dimension API names to group by, e.g. ["date"] or ["country","deviceCategory"]. Max 9. Omit for a single total row.'),
146
+ .describe('Native GA4 shape, as an alternative to startDate/endDate: exactly one {startDate, endDate} entry (this tool runs one range per call).'),
147
+ metrics: coerceArray(metricOrDimensionRef).describe('Metric API names, e.g. ["activeUsers","sessions","screenPageViews"], or the native GA4 [{"name":"activeUsers"}] form. Max 10. Valid names (including custom ones) come from analytics_get_metadata.'),
148
+ dimensions: coerceArray(metricOrDimensionRef)
149
+ .optional()
150
+ .describe('Dimension API names to group by, e.g. ["date"] or ["country","deviceCategory"], or the native GA4 {"name":...} form. Max 9. Omit for a single total row.'),
144
151
  dimensionFilter: coerceJson(z.record(z.string(), z.unknown()))
145
152
  .optional()
146
153
  .describe('FilterExpression on dimensions (applies independently of metricFilter). Simple: {"filter":{"fieldName":"country","stringFilter":{"matchType":"EXACT","value":"France"}}}. AND of two: {"andGroup":{"expressions":[{"filter":{"fieldName":"country","stringFilter":{"matchType":"EXACT","value":"France"}}},{"filter":{"fieldName":"deviceCategory","stringFilter":{"matchType":"EXACT","value":"mobile"}}}]}}. matchType: EXACT | BEGINS_WITH | ENDS_WITH | CONTAINS | FULL_REGEXP (add "caseSensitive":true for case-sensitive). Also available: inListFilter, notExpression, orGroup.'),
@@ -158,19 +165,28 @@ export function registerAnalyticsTools(server, deps = {}) {
158
165
  keepEmptyRows: coerceBoolean.optional().describe('Include rows whose metrics are all zero (default false)'),
159
166
  returnPropertyQuota: coerceBoolean.optional().describe("Include this property's remaining quota tokens in the response"),
160
167
  },
161
- }, async ({ account, property, startDate, endDate, metrics, dimensions, dimensionFilter, metricFilter, orderBys, limit, offset, metricAggregations, keepEmptyRows, returnPropertyQuota }) => {
168
+ }, async ({ account, property, startDate, endDate, dateRanges, metrics, dimensions, dimensionFilter, metricFilter, orderBys, limit, offset, metricAggregations, keepEmptyRows, returnPropertyQuota }) => {
162
169
  const prop = normalizeProperty(property);
163
170
  if ('hint' in prop)
164
171
  return invalidProperty(prop.hint, account);
172
+ if (dateRanges !== undefined && dateRanges.length > 1) {
173
+ return invalidParams(account, `dateRanges has ${dateRanges.length} entries, but analytics_run_report runs a single range per call.`, 'Pass exactly one {startDate, endDate} entry, or call the tool once per range.');
174
+ }
175
+ const range = dateRanges?.[0];
176
+ const resolvedStart = range?.startDate ?? startDate;
177
+ const resolvedEnd = range?.endDate ?? endDate;
178
+ if (resolvedStart === undefined || resolvedEnd === undefined) {
179
+ return invalidParams(account, 'Missing a date range: pass startDate and endDate, or a single-entry dateRanges.', 'e.g. startDate: "28daysAgo", endDate: "today", or dateRanges: [{"startDate":"28daysAgo","endDate":"today"}].');
180
+ }
165
181
  try {
166
182
  const auth = await getClientFn(account);
167
183
  const dataApi = analyticsdataClient({ version: 'v1beta', auth });
168
184
  const requestBody = {
169
- dateRanges: [{ startDate, endDate }],
170
- metrics: metrics.map((name) => ({ name })),
185
+ dateRanges: [{ startDate: resolvedStart, endDate: resolvedEnd }],
186
+ metrics: metrics.map((ref) => ({ name: nameOf(ref) })),
171
187
  };
172
188
  if (dimensions?.length)
173
- requestBody.dimensions = dimensions.map((name) => ({ name }));
189
+ requestBody.dimensions = dimensions.map((ref) => ({ name: nameOf(ref) }));
174
190
  if (dimensionFilter)
175
191
  requestBody.dimensionFilter = dimensionFilter;
176
192
  if (metricFilter)
@@ -281,8 +297,8 @@ function invalidProperty(hint, account) {
281
297
  export function handleAnalyticsError(error, account) {
282
298
  return handleGoogleApiError(error, account, {
283
299
  scope: 'Needs the "analytics" bundle on this account: add it to the scope profile, then re-auth.',
284
- // GA4 answers PERMISSION_DENIED for a property ACL too, and the old
285
- // combined hint sent those callers to re-auth a scope they already had.
300
+ // GA4 returns PERMISSION_DENIED for a property-access issue too, not just
301
+ // a missing scope; keep the hints distinct, or callers get sent to re-auth a scope they already have.
286
302
  resource: 'The scope is not the problem: this Google account has no access to that GA4 property. Grant it in GA4 Admin > Property Access Management, or call analytics_account_summaries to see the properties it can read.',
287
303
  bundle: 'analytics',
288
304
  });
@@ -8,6 +8,11 @@ export declare function registerCalendarTools(server: ToolRegistry, deps?: Curat
8
8
  * Date.parse is lenient, so it is used only to SKIP the check, never to accept. */
9
9
  export declare function timeRangeError(timeMin: string | undefined, timeMax: string | undefined): string | null;
10
10
  export declare const TIME_RANGE_HINT: string;
11
+ /** The Calendar API requires timeMin/timeMax as RFC3339 with a mandatory
12
+ * offset; a bare local datetime is silently ambiguous rather than rejected,
13
+ * so catch it here with a message that names the field. */
14
+ export declare function missingTimeZoneError(field: 'timeMin' | 'timeMax', value: string | undefined): string | null;
15
+ export declare const MISSING_TIME_ZONE_HINT = "Add \"Z\" for UTC or an explicit offset, e.g. \"2026-04-04T00:00:00Z\" or \"2026-04-04T00:00:00+01:00\".";
11
16
  export declare function formatEvent(event: any, opts?: {
12
17
  full?: boolean;
13
18
  }): {
@@ -7,9 +7,8 @@ import { checkOutbound } from '../outbound-allowlist.js';
7
7
  import { handleGoogleApiError, invalidParams } from './_errors.js';
8
8
  import { listResult, sliceClean } from '../trim.js';
9
9
  export function registerCalendarTools(server, deps = {}) {
10
- // Per-registry, LIVE account enum + injectable client (S1.10): the
11
- // schema follows the registry's account view at parse time, and the
12
- // custody path is the context's, not the process global.
10
+ // Per-registry, live account enum + injectable client: the schema follows
11
+ // the registry's account view at parse time, not a process-global default.
13
12
  const accountEnum = accountArgLive(() => server.accountAliases()).optional();
14
13
  const getClientFn = deps.getClientFn ?? getClient;
15
14
  server.registerTool('calendar_list_calendars', {
@@ -55,6 +54,9 @@ export function registerCalendarTools(server, deps = {}) {
55
54
  .describe('Continuation token from a previous call\'s nextPageToken'),
56
55
  },
57
56
  }, async ({ account, calendarId, query, timeMin, timeMax, maxResults, pageToken }) => {
57
+ const tzError = missingTimeZoneError('timeMin', timeMin) ?? missingTimeZoneError('timeMax', timeMax);
58
+ if (tzError)
59
+ return invalidParams(account, tzError, MISSING_TIME_ZONE_HINT);
58
60
  const rangeError = timeRangeError(timeMin, timeMax);
59
61
  if (rangeError)
60
62
  return invalidParams(account, rangeError, TIME_RANGE_HINT);
@@ -237,6 +239,46 @@ export function registerCalendarTools(server, deps = {}) {
237
239
  return handleCalendarError(error, account);
238
240
  }
239
241
  });
242
+ // attendeesOmitted plus a single-entry attendees array patches only the caller's own RSVP.
243
+ server.registerTool('calendar_respond_event', {
244
+ description: 'RSVP to a calendar event as this account (accepted/declined/tentative) without touching any other attendee',
245
+ inputSchema: {
246
+ account: accountEnum.describe('Google account alias'),
247
+ eventId: z.string().min(1).describe('Calendar event ID'),
248
+ calendarId: z.string().default('primary').optional()
249
+ .describe('Calendar ID (default: primary)'),
250
+ response: z.enum(['accepted', 'declined', 'tentative']).describe('RSVP response'),
251
+ comment: z.string().optional().describe('Optional comment attached to the response'),
252
+ },
253
+ }, async ({ account, eventId, calendarId, response, comment }) => {
254
+ try {
255
+ const auth = await getClientFn(account);
256
+ const cal = calendarClient({ version: 'v3', auth });
257
+ const cid = calendarId ?? 'primary';
258
+ const current = await cal.events.get({ calendarId: cid, eventId });
259
+ const attendees = current.data.attendees ?? [];
260
+ const accountEmail = server.accountSet().configs[account]?.email;
261
+ const self = attendees.find((a) => a.self)
262
+ ?? attendees.find((a) => a.email?.toLowerCase() === accountEmail?.toLowerCase());
263
+ if (!self?.email) {
264
+ return invalidParams(account, `Event "${eventId}" has no attendee entry for this account, so there is nothing to RSVP to.`, 'RSVP only applies to events where this account is invited as a guest; check calendar_get_event to see the attendee list.');
265
+ }
266
+ const res = await cal.events.patch({
267
+ calendarId: cid,
268
+ eventId,
269
+ requestBody: {
270
+ attendeesOmitted: true,
271
+ attendees: [{ email: self.email, responseStatus: response, ...(comment !== undefined ? { comment } : {}) }],
272
+ },
273
+ });
274
+ return {
275
+ content: [{ type: 'text', text: JSON.stringify(formatEvent(res.data), null, 2) }],
276
+ };
277
+ }
278
+ catch (error) {
279
+ return handleCalendarError(error, account);
280
+ }
281
+ });
240
282
  server.registerTool('calendar_delete_event', {
241
283
  description: 'Delete a Google Calendar event',
242
284
  inputSchema: {
@@ -329,6 +371,9 @@ export function registerCalendarTools(server, deps = {}) {
329
371
  .describe('Continuation token from a previous call\'s nextPageToken'),
330
372
  },
331
373
  }, async ({ account, calendarId, eventId, timeMin, timeMax, maxResults, pageToken }) => {
374
+ const tzError = missingTimeZoneError('timeMin', timeMin) ?? missingTimeZoneError('timeMax', timeMax);
375
+ if (tzError)
376
+ return invalidParams(account, tzError, MISSING_TIME_ZONE_HINT);
332
377
  const rangeError = timeRangeError(timeMin, timeMax);
333
378
  if (rangeError)
334
379
  return invalidParams(account, rangeError, TIME_RANGE_HINT);
@@ -368,6 +413,9 @@ export function registerCalendarTools(server, deps = {}) {
368
413
  if (calendarIds.length === 0) {
369
414
  return invalidParams(account, '`calendarIds` is empty, so there is nothing to check.', 'Pass at least one calendar ID, e.g. ["primary"]. Use calendar_list_calendars to see the IDs this account can read.');
370
415
  }
416
+ const tzError = missingTimeZoneError('timeMin', timeMin) ?? missingTimeZoneError('timeMax', timeMax);
417
+ if (tzError)
418
+ return invalidParams(account, tzError, MISSING_TIME_ZONE_HINT);
371
419
  const rangeError = timeRangeError(timeMin, timeMax);
372
420
  if (rangeError)
373
421
  return invalidParams(account, rangeError, TIME_RANGE_HINT);
@@ -382,10 +430,8 @@ export function registerCalendarTools(server, deps = {}) {
382
430
  },
383
431
  });
384
432
  return {
385
- // freebusy answers 200 with NO `calendars` key on an empty items
386
- // list, and JSON.stringify(undefined) returns undefined, not a
387
- // string: the SDK then rejected our own result with -32602. The
388
- // value is a map keyed by calendar id, so the fallback is {}.
433
+ // Empty items returns 200 with no `calendars` key; JSON.stringify(undefined)
434
+ // would make the SDK reject our own result, so fall back to {}.
389
435
  content: [{ type: 'text', text: JSON.stringify(res.data.calendars ?? {}, null, 2) }],
390
436
  };
391
437
  }
@@ -443,6 +489,16 @@ export function timeRangeError(timeMin, timeMax) {
443
489
  }
444
490
  export const TIME_RANGE_HINT = 'Swap the two values or widen the window: timeMin must be strictly earlier than timeMax. ' +
445
491
  'An empty result from this tool then always means "nothing scheduled", never "bad range".';
492
+ const TZ_SUFFIX_RE = /(Z|[+-]\d{2}:?\d{2})$/;
493
+ /** The Calendar API requires timeMin/timeMax as RFC3339 with a mandatory
494
+ * offset; a bare local datetime is silently ambiguous rather than rejected,
495
+ * so catch it here with a message that names the field. */
496
+ export function missingTimeZoneError(field, value) {
497
+ if (value === undefined || TZ_SUFFIX_RE.test(value))
498
+ return null;
499
+ return `${field} ("${value}") has no "Z" or UTC offset, so its timezone is ambiguous.`;
500
+ }
501
+ export const MISSING_TIME_ZONE_HINT = 'Add "Z" for UTC or an explicit offset, e.g. "2026-04-04T00:00:00Z" or "2026-04-04T00:00:00+01:00".';
446
502
  export function formatEvent(event, opts = {}) {
447
503
  const full = opts.full ?? true;
448
504
  const description = event.description ?? '';
@@ -5,9 +5,8 @@ import { accountArgLive } from '../accounts.js';
5
5
  import { getClient } from '../client.js';
6
6
  import { handleGoogleApiError, invalidParams } from './_errors.js';
7
7
  export function registerChatTools(server, deps = {}) {
8
- // Per-registry, LIVE account enum + injectable client (S1.10): the
9
- // schema follows the registry's account view at parse time, and the
10
- // custody path is the context's, not the process global.
8
+ // Per-registry, live account enum + injectable client: the schema follows
9
+ // the registry's account view at parse time, not a process-global default.
11
10
  const accountEnum = accountArgLive(() => server.accountAliases()).optional();
12
11
  const getClientFn = deps.getClientFn ?? getClient;
13
12
  server.registerTool('chat_spaces_list', {
@@ -34,7 +34,7 @@ function formatContact(person) {
34
34
  photo: person.photos?.[0]?.url ?? '',
35
35
  };
36
36
  }
37
- /** Accent-fold + lowercase for name comparison ("Rym" == "Rÿm"). */
37
+ /** Accent-fold + lowercase for name comparison ("Zoe" == "Zoë"). */
38
38
  const foldName = (s) => s.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase().trim();
39
39
  /** Canonical-address preference within one contact: explicit primary, then
40
40
  * People type order work > home > other. */
@@ -52,7 +52,7 @@ function pickEmail(c) {
52
52
  return [...c.emails].sort((a, b) => emailRank(b) - emailRank(a))[0];
53
53
  }
54
54
  /** Deterministic rank tuple; higher wins, compared lexicographically so the
55
- * first discriminating rule decides (A10 tie-break table). */
55
+ * first discriminating rule decides. */
56
56
  function scoreTuple(c, foldedQuery) {
57
57
  const exact = foldName(c.displayName) === foldedQuery ? 1 : 0; // 1. exact over prefix
58
58
  const saved = c.source === 'contacts' ? 1 : 0; // 2. saved over other-contact
@@ -123,9 +123,8 @@ function dedupeCandidates(list) {
123
123
  return [...byResource.values()];
124
124
  }
125
125
  export function registerContactsTools(server, deps = {}) {
126
- // Per-registry, LIVE account enum + injectable client (S1.10): the
127
- // schema follows the registry's account view at parse time, and the
128
- // custody path is the context's, not the process global.
126
+ // Per-registry, live account enum + injectable client: the schema follows
127
+ // the registry's account view at parse time, not a process-global default.
129
128
  const accountEnum = accountArgLive(() => server.accountAliases()).optional();
130
129
  const getClientFn = deps.getClientFn ?? getClient;
131
130
  server.registerTool('contacts_search', {
@@ -170,7 +169,7 @@ export function registerContactsTools(server, deps = {}) {
170
169
  description: 'Resolve a free-text name/alias to ONE canonical email address (ranked + tie-broken), so you need not hand-expand transliteration OR-queries. Returns a single confident match, an explicit ambiguous candidate list, or null when nothing matches. For picking a recipient before gmail_send.',
171
170
  inputSchema: {
172
171
  account: accountEnum.describe('Google account alias'),
173
- name: z.string().min(1).describe('Free-text name or alias to resolve (e.g. "Rym")'),
172
+ name: z.string().min(1).describe('Free-text name or alias to resolve (e.g. "Zoe")'),
174
173
  maxCandidates: z.number().min(1).max(10).default(5).optional()
175
174
  .describe('Max candidates to return when ambiguous (1-10, default: 5)'),
176
175
  includeOtherContacts: coerceBoolean.optional()
@@ -197,7 +196,7 @@ export function registerContactsTools(server, deps = {}) {
197
196
  candidates.push(...(other.data.results ?? []).map((r) => toCandidate(r.person, 'otherContacts')));
198
197
  }
199
198
  catch {
200
- // otherContacts unavailable (scope/5xx): degrade to saved-contacts only.
199
+ // otherContacts unavailable: degrade silently
201
200
  }
202
201
  }
203
202
  const result = resolveContacts(dedupeCandidates(candidates), name, maxCandidates ?? 5);
@@ -235,8 +234,8 @@ export function registerContactsTools(server, deps = {}) {
235
234
  description: 'List all contacts (paginated)',
236
235
  inputSchema: {
237
236
  account: accountEnum.describe('Google account alias'),
238
- pageSize: z.number().min(1).max(1000).default(100).optional()
239
- .describe('Number of contacts per page (default: 100)'),
237
+ pageSize: z.number().min(1).max(1000).default(50).optional()
238
+ .describe('Number of contacts per page (default: 50)'),
240
239
  pageToken: z.string().optional().describe('Page token for pagination'),
241
240
  sortOrder: z.enum([
242
241
  'LAST_MODIFIED_ASCENDING',
@@ -245,19 +244,25 @@ export function registerContactsTools(server, deps = {}) {
245
244
  'LAST_NAME_ASCENDING',
246
245
  ]).default('FIRST_NAME_ASCENDING').optional()
247
246
  .describe('Sort order (default: FIRST_NAME_ASCENDING)'),
247
+ requireEmail: coerceBoolean.optional().describe('Only return contacts with at least one email address. Filtering happens after the page is fetched, so the returned page can hold fewer than pageSize contacts; nextPageToken still continues the underlying, unfiltered listing'),
248
+ requireName: coerceBoolean.optional().describe('Only return contacts with a name. Filtering happens after the page is fetched, so the returned page can hold fewer than pageSize contacts; nextPageToken still continues the underlying, unfiltered listing'),
248
249
  },
249
- }, async ({ account, pageSize, pageToken, sortOrder }) => {
250
+ }, async ({ account, pageSize, pageToken, sortOrder, requireEmail, requireName }) => {
250
251
  try {
251
252
  const auth = await getClientFn(account);
252
253
  const people = peopleClient({ version: 'v1', auth });
253
254
  const res = await people.people.connections.list({
254
255
  resourceName: 'people/me',
255
256
  personFields: PERSON_FIELDS,
256
- pageSize: pageSize ?? 100,
257
+ pageSize: pageSize ?? 50,
257
258
  pageToken: pageToken ?? undefined,
258
259
  sortOrder: sortOrder ?? 'FIRST_NAME_ASCENDING',
259
260
  });
260
- const contacts = (res.data.connections ?? []).map(formatContact);
261
+ let contacts = (res.data.connections ?? []).map(formatContact);
262
+ if (requireEmail)
263
+ contacts = contacts.filter((c) => c.emails.length > 0);
264
+ if (requireName)
265
+ contacts = contacts.filter((c) => c.name !== '');
261
266
  return {
262
267
  content: [{ type: 'text', text: JSON.stringify({
263
268
  contacts,
@@ -453,8 +458,8 @@ export function registerContactsTools(server, deps = {}) {
453
458
  const members = [];
454
459
  let fetchFailures = 0;
455
460
  let firstError;
456
- // getBatchGet caps at 200 names while maxMembers goes to 1000, so a
457
- // large group used to fail outright rather than come back in pages.
461
+ // getBatchGet caps at 200 names while maxMembers goes to 1000, so fetch
462
+ // in chunks rather than fail outright on a large group.
458
463
  for (let i = 0; i < memberResourceNames.length; i += BATCH_GET_LIMIT) {
459
464
  const chunk = memberResourceNames.slice(i, i + BATCH_GET_LIMIT);
460
465
  try {
@@ -5,12 +5,8 @@ import { accountArgLive } from '../accounts.js';
5
5
  import { getClient } from '../client.js';
6
6
  import { handleGoogleApiError, invalidParams } from './_errors.js';
7
7
  import { capText } from '../trim.js';
8
- // A single very large insertText has been observed to apply only partially while
9
- // the request still returns success, silently dropping the tail. Split a large
10
- // insert into bounded pieces sent as sequential insertText requests in one atomic
11
- // batchUpdate: small inserts keep the exact single-request path, and a large one
12
- // can no longer be silently truncated. Docs indices are UTF-16 code units (= JS
13
- // string length), so index math advances by `.length`; never split a surrogate pair.
8
+ // A single large insertText can silently apply only partially despite returning
9
+ // success; split into <=DOCS_INSERT_CHUNK sequential inserts in one atomic batchUpdate (UTF-16-safe, no split surrogate pairs).
14
10
  export const DOCS_INSERT_CHUNK = 5000;
15
11
  export function splitInsertText(text, maxLen = DOCS_INSERT_CHUNK) {
16
12
  if (text.length === 0)
@@ -170,9 +166,8 @@ export function listTabs(tabs) {
170
166
  return out;
171
167
  }
172
168
  export function registerDocsTools(server, deps = {}) {
173
- // Per-registry, LIVE account enum + injectable client (S1.10): the
174
- // schema follows the registry's account view at parse time, and the
175
- // custody path is the context's, not the process global.
169
+ // Per-registry, live account enum + injectable client: the schema follows
170
+ // the registry's account view at parse time, not a process-global default.
176
171
  const accountEnum = accountArgLive(() => server.accountAliases()).optional();
177
172
  const getClientFn = deps.getClientFn ?? getClient;
178
173
  server.registerTool('docs_create', {
@@ -385,35 +380,64 @@ export function registerDocsTools(server, deps = {}) {
385
380
  server.registerTool('docs_replace_text', {
386
381
  // Insert/append-capable or non-convergent: a retry duplicates content.
387
382
  annotations: { idempotentHint: false },
388
- description: 'Find and replace all occurrences of text in a document',
383
+ description: 'Find and replace text in a document. Pass findText/replaceText for a single pair, or replacements for several pairs applied in one batchUpdate.',
389
384
  inputSchema: {
390
385
  account: accountEnum.describe('Google account alias'),
391
386
  documentId: z.string().min(1).describe('Google Docs document ID'),
392
- findText: z.string().describe('Text to search for'),
393
- replaceText: z.string().describe('Replacement text'),
387
+ findText: z.string().optional().describe('Text to search for. Use with replaceText; exactly one of this pair or `replacements` is required.'),
388
+ replaceText: z.string().optional().describe('Replacement text for findText'),
394
389
  matchCase: coerceBoolean.default(true).optional()
395
390
  .describe('Case-sensitive match (default: true)'),
391
+ replacements: coerceJson(z.array(z.object({
392
+ findText: z.string(),
393
+ replaceText: z.string(),
394
+ matchCase: coerceBoolean.optional(),
395
+ })).min(1)).optional().describe('Several find/replace pairs applied in one batchUpdate, each returning its own count. Exactly one of this or findText/replaceText is required.'),
396
396
  },
397
- }, async ({ account, documentId, findText, replaceText, matchCase }) => {
397
+ }, async ({ account, documentId, findText, replaceText, matchCase, replacements }) => {
398
+ const singlePair = findText !== undefined || replaceText !== undefined;
399
+ if (singlePair && replacements) {
400
+ return invalidParams(account, 'Pass either findText/replaceText or replacements, not both.', 'Use findText and replaceText for one pair, or replacements for several pairs in one call.');
401
+ }
402
+ if (!singlePair && !replacements) {
403
+ return invalidParams(account, 'Pass findText and replaceText, or a replacements array.', 'Use findText and replaceText for one pair, or replacements for several pairs in one call.');
404
+ }
405
+ if (singlePair && (findText === undefined || replaceText === undefined)) {
406
+ return invalidParams(account, 'Both findText and replaceText are required together.', 'Pass both, or use replacements for several pairs.');
407
+ }
408
+ const pairs = replacements ?? [{ findText: findText, replaceText: replaceText, matchCase }];
398
409
  try {
399
410
  const auth = await getClientFn(account);
400
411
  const docs = docsClient({ version: 'v1', auth });
401
412
  const res = await docs.documents.batchUpdate({
402
413
  documentId,
403
414
  requestBody: {
404
- requests: [{
405
- replaceAllText: {
406
- containsText: { text: findText, matchCase: matchCase ?? true },
407
- replaceText,
408
- },
409
- }],
415
+ requests: pairs.map((p) => ({
416
+ replaceAllText: {
417
+ containsText: { text: p.findText, matchCase: p.matchCase ?? true },
418
+ replaceText: p.replaceText,
419
+ },
420
+ })),
410
421
  },
411
422
  });
412
- const occurrences = res.data.replies?.[0]?.replaceAllText?.occurrencesChanged ?? 0;
423
+ const counts = (res.data.replies ?? []).map((r) => r?.replaceAllText?.occurrencesChanged ?? 0);
424
+ const warning = counts.every((c) => c === 0)
425
+ ? 'No occurrences were replaced; check spelling and matchCase.'
426
+ : undefined;
427
+ if (replacements) {
428
+ return {
429
+ content: [{ type: 'text', text: JSON.stringify({
430
+ documentId: res.data.documentId,
431
+ replacements: pairs.map((p, i) => ({ findText: p.findText, replaceText: p.replaceText, occurrencesReplaced: counts[i] })),
432
+ ...(warning ? { warning } : {}),
433
+ }, null, 2) }],
434
+ };
435
+ }
413
436
  return {
414
437
  content: [{ type: 'text', text: JSON.stringify({
415
438
  documentId: res.data.documentId,
416
- occurrencesReplaced: occurrences,
439
+ occurrencesReplaced: counts[0],
440
+ ...(warning ? { warning } : {}),
417
441
  }, null, 2) }],
418
442
  };
419
443
  }