@mindstone/mcp-server-google-workspace 0.5.2 → 0.5.4

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 (45) hide show
  1. package/README.md +27 -1
  2. package/dist/file-read-context.d.ts +57 -0
  3. package/dist/file-read-context.js +36 -0
  4. package/dist/modules/calendar/service.js +97 -90
  5. package/dist/modules/comments/service.js +6 -6
  6. package/dist/modules/docs/service.js +15 -11
  7. package/dist/modules/docs/types.d.ts +4 -0
  8. package/dist/modules/drive/service.js +1 -17
  9. package/dist/modules/forms/service.js +4 -4
  10. package/dist/modules/gmail/services/attachment.js +3 -1
  11. package/dist/modules/gmail/services/base.js +3 -1
  12. package/dist/modules/gmail/services/draft.js +13 -1
  13. package/dist/modules/gmail/services/email.js +13 -4
  14. package/dist/modules/gmail/services/label.js +19 -1
  15. package/dist/modules/gmail/services/settings.js +7 -1
  16. package/dist/modules/sheets/service.js +18 -18
  17. package/dist/modules/slides/service.js +7 -7
  18. package/dist/modules/tasks/service.js +7 -7
  19. package/dist/resources/compose-email-template.d.ts +1 -1
  20. package/dist/resources/compose-email-template.js +107 -53
  21. package/dist/services/base/BaseGoogleService.js +2 -2
  22. package/dist/services/chat/index.js +3 -0
  23. package/dist/services/contacts/index.js +8 -5
  24. package/dist/services/meet/index.js +3 -0
  25. package/dist/tools/calendar-handlers.js +7 -7
  26. package/dist/tools/chat-handlers.js +4 -4
  27. package/dist/tools/contacts-handlers.js +5 -5
  28. package/dist/tools/definitions/gmail.js +4 -0
  29. package/dist/tools/docs-handlers.js +14 -6
  30. package/dist/tools/drive-handlers.d.ts +2 -1
  31. package/dist/tools/drive-handlers.js +21 -16
  32. package/dist/tools/gmail-handlers.d.ts +6 -5
  33. package/dist/tools/gmail-handlers.js +39 -27
  34. package/dist/tools/meet-handlers.js +4 -4
  35. package/dist/tools/server.js +24 -10
  36. package/dist/tools/sheets-handlers.js +4 -4
  37. package/dist/tools/slides-handlers.js +4 -4
  38. package/dist/utils/apiError.d.ts +7 -3
  39. package/dist/utils/apiError.js +37 -16
  40. package/dist/utils/google-retry.d.ts +15 -0
  41. package/dist/utils/google-retry.js +108 -0
  42. package/dist/utils/request-timeout.js +2 -0
  43. package/dist/utils/untrusted-content.d.ts +9 -0
  44. package/dist/utils/untrusted-content.js +37 -0
  45. package/package.json +3 -2
package/README.md CHANGED
@@ -8,7 +8,7 @@ Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Co
8
8
 
9
9
  ## Status
10
10
 
11
- - **Version:** [0.5.2](./CHANGELOG.md) · npm: not yet published
11
+ - **Version:** [0.5.4](./CHANGELOG.md) · npm: not yet published
12
12
  - **Auth:** OAuth (host-orchestrated) ([`GOOGLE_CLIENT_SECRET`](./server.json))
13
13
  - **Tools:** [124](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Tasks, Forms, Comments, Account)
14
14
  - **Surface:** cloud-api
@@ -74,6 +74,10 @@ node dist/index.js
74
74
 
75
75
  ## Configuration
76
76
 
77
+ **When Google says "slow down".** There is nothing to configure here. For reads (`GET`, `HEAD` and `OPTIONS`), short-window rate limits wait and retry the request; the total can be longer than a minute and a half when Google sends `Retry-After`, and each wait is capped at 64 seconds. Requests that already succeeded are not sent again. `POST` and `PATCH` are never replayed by the retry policy; `PUT` and `DELETE` keep the ordinary 429 retries but do not retry rate-limit 403s. Non-rate-limit permission errors and longer-window 403 quota responses keep their ordinary behavior; 429 responses give back-off advice, and some tools also include Google's error text. When the read retry loop ends, the error says so (`recoveryExhausted: true`); a host that retries failed calls itself can read that field and skip its own retry.
78
+
79
+ **Values you pass back stay exact.** Results mark text that comes from outside (email bodies, file names, event titles) as untrusted content, by wrapping it in an `<untrusted-content>` tag. Values meant to be passed back into another call are returned exactly as Google sent them: page tokens (which fetch the next page of results) and the IDs of messages, threads, files, events, calendars, Chat spaces and Meet records. You can pass them straight into the next call.
80
+
77
81
  This server is designed to run alongside a host application that performs the Google OAuth flow on its own. The host writes credentials to disk; this server reads them.
78
82
 
79
83
  ### Required environment variables
@@ -173,6 +177,14 @@ The full list lives under [`src/tools/definitions/`](./src/tools/definitions/) a
173
177
  | Tasks | 6 | List task lists, and list/create/update/complete/delete tasks. |
174
178
  | Forms | 4 | Read-only access to forms and their responses. |
175
179
 
180
+ ### Compose send status
181
+
182
+ In hosts that remember send status, sending an email closes its other compose copies. Reloaded cards show "Email sent" with the send time and hide Reopen because they do not have the sent contents. The copy used to send keeps its posted contents in a read-only sent view, including when confirmation follows a lost reply. After an error or block reply, a later sent status from another copy shows only the sent bar, without this copy's contents. While a send is in progress, other copies show “Sending…” with Send, Retry, Cancel and Save draft (where available) disabled. Replies to this copy’s own requests keep those controls locked until the other send ends. If the send ends without a confirmed outcome, those copies return to editing and keep any earlier uncertainty. A copy waiting for its own Send reply keeps its sending view. Sent views stay read-only, and uncertainty remains until a send is confirmed. After an error or missing confirmation, check whether the email was sent before using Retry; the notice stays visible while editing and returns on Reopen. Collapsing the card does not resolve that uncertainty. Policy-block explanations stay visible while editing with Send disabled. Cancel says "Nothing sent" only when no send may have gone through, including a `not-dispatched` failure before the request left the device.
183
+
184
+ When sending is blocked by your settings, your organization or security policy, the card hides Retry and keeps Cancel. If the server is stopped, Retry remains available.
185
+
186
+ Send requests declare `_meta: { 'mcp-app/cardOutcome': 'sent' }` to supporting hosts. When your own setting blocks sending, Retry stays unavailable; the Gmail fallback depends on the structured `user-disabled` reason. Draft saves do not declare a send outcome; Cancel after a draft-save timeout says "Nothing sent" unless an earlier send remains uncertain.
187
+
176
188
  ### Sheets read limits
177
189
 
178
190
  `read_workspace_spreadsheet_values` accepts `max_rows` and `max_cols` to keep the first rows and columns of a values read, including `value_view: "shaped"` and `return_json: true`. They refer to sheet rows and columns even with `major_dimension: "COLUMNS"`. Omitted limits leave that dimension unchanged. A truncated result reports `truncated: true` in JSON or a truncation notice in text.
@@ -246,3 +258,17 @@ A Google Doc can hold many tabs, nested up to a few levels deep. Every tab has a
246
258
  ## Licence
247
259
 
248
260
  [FSL-1.1-MIT](./LICENSE) — Functional Source License, Version 1.1, with MIT future licence. The software converts to MIT licence on 2030-04-08.
261
+
262
+ ### Host-authorized local inputs
263
+
264
+ `files/readModes` version 1 is an experimental extension used by these connectors,
265
+ not part of the MCP standard. A compatible host (the app running the connector)
266
+ decides which input files a tool call may read. The connector opens only the
267
+ host-approved physical path, after resolving symlinks. The host supplies this
268
+ permission information with each call; it is not a tool argument you need to set.
269
+ Missing or invalid permission information, or a file absent from the approved
270
+ list, stops the read.
271
+
272
+ Clients that do not negotiate this extension keep the connector's existing
273
+ standalone file restrictions. This extension changes input-read permissions;
274
+ existing output destinations, upload formats, size limits and file checks apply.
@@ -0,0 +1,57 @@
1
+ import { z } from 'zod';
2
+ /** Negotiation is connection-scoped; the selected mode belongs to one SDK request. */
3
+ export declare const FILE_READ_CAPABILITIES: {
4
+ experimental: {
5
+ 'files/readModes': {
6
+ version: number;
7
+ };
8
+ };
9
+ };
10
+ export declare const readModeSchema: z.ZodDiscriminatedUnion<"mode", [z.ZodObject<{
11
+ version: z.ZodLiteral<1>;
12
+ mode: z.ZodLiteral<"central">;
13
+ reads: z.ZodArray<z.ZodObject<{
14
+ location: z.ZodArray<z.ZodUnion<[z.ZodString, z.ZodNumber]>, "many">;
15
+ rawPath: z.ZodString;
16
+ canonicalPath: z.ZodEffects<z.ZodString, string, string>;
17
+ }, "strict", z.ZodTypeAny, {
18
+ location: (string | number)[];
19
+ rawPath: string;
20
+ canonicalPath: string;
21
+ }, {
22
+ location: (string | number)[];
23
+ rawPath: string;
24
+ canonicalPath: string;
25
+ }>, "many">;
26
+ }, "strict", z.ZodTypeAny, {
27
+ mode: "central";
28
+ version: 1;
29
+ reads: {
30
+ location: (string | number)[];
31
+ rawPath: string;
32
+ canonicalPath: string;
33
+ }[];
34
+ }, {
35
+ mode: "central";
36
+ version: 1;
37
+ reads: {
38
+ location: (string | number)[];
39
+ rawPath: string;
40
+ canonicalPath: string;
41
+ }[];
42
+ }>, z.ZodObject<{
43
+ version: z.ZodLiteral<1>;
44
+ mode: z.ZodLiteral<"standalone">;
45
+ }, "strict", z.ZodTypeAny, {
46
+ mode: "standalone";
47
+ version: 1;
48
+ }, {
49
+ mode: "standalone";
50
+ version: 1;
51
+ }>]>;
52
+ export type FileReadContext = z.infer<typeof readModeSchema>;
53
+ /** Pass SDK extra here, never model arguments or arguments._meta. */
54
+ export declare function fileReadContext(capabilities: unknown, extra: unknown): FileReadContext;
55
+ /** Exact concrete operand lookup only; canonicalization and permission belong to the host. */
56
+ export declare function centralReadPath(context: FileReadContext | undefined, rawPath: string, location: (string | number)[]): string | undefined;
57
+ //# sourceMappingURL=file-read-context.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { isAbsolute } from 'node:path';
3
+ /** Negotiation is connection-scoped; the selected mode belongs to one SDK request. */
4
+ export const FILE_READ_CAPABILITIES = { experimental: { 'files/readModes': { version: 1 } } };
5
+ const locationSchema = z.array(z.union([z.string(), z.number().int().nonnegative()]));
6
+ const allowedReadSchema = z.object({
7
+ location: locationSchema, rawPath: z.string(), canonicalPath: z.string().refine(isAbsolute),
8
+ }).strict();
9
+ export const readModeSchema = z.discriminatedUnion('mode', [
10
+ z.object({ version: z.literal(1), mode: z.literal('central'), reads: z.array(allowedReadSchema) }).strict(),
11
+ z.object({ version: z.literal(1), mode: z.literal('standalone') }).strict(),
12
+ ]);
13
+ const capabilitiesSchema = z.object({ experimental: z.object({
14
+ 'files/readModes': z.object({ version: z.literal(1) }).passthrough(),
15
+ }).passthrough() }).passthrough();
16
+ const extraSchema = z.object({ _meta: z.object({ 'files/readMode': readModeSchema }).passthrough() }).passthrough();
17
+ /** Pass SDK extra here, never model arguments or arguments._meta. */
18
+ export function fileReadContext(capabilities, extra) {
19
+ if (!capabilitiesSchema.safeParse(capabilities).success)
20
+ return { version: 1, mode: 'standalone' };
21
+ const parsed = extraSchema.safeParse(extra);
22
+ if (!parsed.success)
23
+ throw new Error('Negotiated file reads require valid request files/readMode metadata.');
24
+ return parsed.data._meta['files/readMode'];
25
+ }
26
+ /** Exact concrete operand lookup only; canonicalization and permission belong to the host. */
27
+ export function centralReadPath(context, rawPath, location) {
28
+ if (!context || context.mode === 'standalone')
29
+ return undefined;
30
+ const matches = context.reads.filter(read => read.rawPath === rawPath &&
31
+ read.location.length === location.length && read.location.every((part, index) => part === location[index]));
32
+ if (matches.length !== 1)
33
+ throw new Error('Central file read requires exactly one allowed concrete operand.');
34
+ return matches[0].canonicalPath;
35
+ }
36
+ //# sourceMappingURL=file-read-context.js.map
@@ -1,3 +1,4 @@
1
+ import { isGoogleRecoveryExhausted, isShortWindowRateLimit } from '../../utils/google-retry.js';
1
2
  import { google } from 'googleapis';
2
3
  import path from 'path';
3
4
  import { getAccountManager } from '../accounts/index.js';
@@ -7,6 +8,7 @@ import { DriveService } from '../drive/service.js';
7
8
  import { ATTACHMENT_FOLDERS } from '../attachments/types.js';
8
9
  import { AccountError } from '../accounts/types.js';
9
10
  import { isUnauthorizedError } from '../accounts/unauthorized.js';
11
+ import { isPassthroughGoogleError } from '../../utils/apiError.js';
10
12
  // Convert Google Calendar attachment to our format
11
13
  function convertToCalendarAttachment(attachment) {
12
14
  return {
@@ -52,6 +54,8 @@ export class CalendarService {
52
54
  this.initialized = true;
53
55
  }
54
56
  catch (error) {
57
+ if (isPassthroughGoogleError(error))
58
+ throw error;
55
59
  throw new CalendarError('Failed to initialize Calendar service', 'INIT_ERROR', error instanceof Error ? error.message : 'Unknown error');
56
60
  }
57
61
  }
@@ -127,6 +131,8 @@ export class CalendarService {
127
131
  return google.calendar({ version: 'v3', auth: this.oauth2Client });
128
132
  }
129
133
  catch (error) {
134
+ if (isPassthroughGoogleError(error))
135
+ throw error;
130
136
  if (error instanceof CalendarError) {
131
137
  throw error;
132
138
  }
@@ -141,6 +147,10 @@ export class CalendarService {
141
147
  return await operation();
142
148
  }
143
149
  catch (error) {
150
+ if (isGoogleRecoveryExhausted(error))
151
+ throw error;
152
+ if (isShortWindowRateLimit(error))
153
+ throw error;
144
154
  if (isUnauthorizedError(error)) {
145
155
  if (process.env.GOOGLE_WORKSPACE_DISABLE_REFRESH === '1') {
146
156
  throw new AccountError('Calendar authentication required', 'AUTH_REQUIRED', 'Connect Google Workspace to continue');
@@ -314,6 +324,10 @@ export class CalendarService {
314
324
  return Promise.all(trimmedEvents.map(event => this.mapEventResponse(email, event)));
315
325
  }
316
326
  catch (error) {
327
+ if (isGoogleRecoveryExhausted(error))
328
+ throw error;
329
+ if (isShortWindowRateLimit(error))
330
+ throw error;
317
331
  // Handle permission errors for shared calendars
318
332
  if (calendarId && calendarId !== 'primary' && (error.code === 403 || error.status === 403)) {
319
333
  throw new CalendarError("You don't have permission to view events on this calendar. " +
@@ -344,6 +358,8 @@ export class CalendarService {
344
358
  return this.mapEventResponse(email, event);
345
359
  }
346
360
  catch (error) {
361
+ if (isPassthroughGoogleError(error))
362
+ throw error;
347
363
  // Handle not found errors with helpful hint for primary calendar
348
364
  if (error.code === 404 || error.status === 404) {
349
365
  const hint = targetCalendarId === 'primary'
@@ -474,6 +490,10 @@ export class CalendarService {
474
490
  };
475
491
  }
476
492
  catch (error) {
493
+ if (isGoogleRecoveryExhausted(error))
494
+ throw error;
495
+ if (isShortWindowRateLimit(error))
496
+ throw error;
477
497
  // Handle permission errors for shared calendars
478
498
  if (targetCalendarId !== 'primary' && (error.code === 403 || error.status === 403)) {
479
499
  throw new CalendarError("You don't have permission to create events on this calendar. " +
@@ -607,107 +627,94 @@ export class CalendarService {
607
627
  return;
608
628
  }
609
629
  // For 'this_and_following', we need to check if this is a recurring event
610
- try {
611
- const { data: event } = await calendar.events.get({
630
+ const { data: event } = await calendar.events.get({
631
+ calendarId: 'primary',
632
+ eventId
633
+ });
634
+ const isRecurring = !!event.recurringEventId || !!event.recurrence;
635
+ if (!isRecurring) {
636
+ throw new CalendarError('Deletion scope can only be applied to recurring events', 'INVALID_REQUEST', 'The specified event is not recurring');
637
+ }
638
+ // For 'this_and_following', we need to use a different approach
639
+ // Google Calendar API handles recurring events differently
640
+ if (event.recurringEventId) {
641
+ // This is an instance of a recurring event
642
+ // We need to get the master event to update its recurrence rules
643
+ const { data: masterEvent } = await calendar.events.get({
612
644
  calendarId: 'primary',
613
- eventId
645
+ eventId: event.recurringEventId
614
646
  });
615
- const isRecurring = !!event.recurringEventId || !!event.recurrence;
616
- if (!isRecurring) {
617
- throw new CalendarError('Deletion scope can only be applied to recurring events', 'INVALID_REQUEST', 'The specified event is not recurring');
647
+ if (!masterEvent || !masterEvent.recurrence) {
648
+ throw new CalendarError('Failed to retrieve master event', 'NOT_FOUND', 'Could not find the master event for this recurring instance');
618
649
  }
619
- // For 'this_and_following', we need to use a different approach
620
- // Google Calendar API handles recurring events differently
621
- if (event.recurringEventId) {
622
- // This is an instance of a recurring event
623
- // We need to get the master event to update its recurrence rules
624
- const { data: masterEvent } = await calendar.events.get({
625
- calendarId: 'primary',
626
- eventId: event.recurringEventId
627
- });
628
- if (!masterEvent || !masterEvent.recurrence) {
629
- throw new CalendarError('Failed to retrieve master event', 'NOT_FOUND', 'Could not find the master event for this recurring instance');
630
- }
631
- // Get the instance date to use as the cutoff
632
- const instanceDate = new Date(event.start?.dateTime || event.start?.date || '');
633
- // Format the date as YYYYMMDD for UNTIL parameter in RRULE
634
- // Subtract one day to make it exclusive (end before this instance)
635
- instanceDate.setDate(instanceDate.getDate() - 1);
636
- const formattedDate = instanceDate.toISOString().slice(0, 10).replace(/-/g, '');
637
- // Update the recurrence rules to end before this instance
638
- const updatedRules = masterEvent.recurrence.map(rule => {
639
- if (rule.startsWith('RRULE:')) {
640
- // If the rule already has an UNTIL parameter, we need to replace it
641
- if (rule.includes('UNTIL=')) {
642
- return rule.replace(/UNTIL=\d+T\d+Z?/, `UNTIL=${formattedDate}`);
643
- }
644
- else {
645
- // Otherwise, add the UNTIL parameter
646
- return `${rule};UNTIL=${formattedDate}`;
647
- }
650
+ // Get the instance date to use as the cutoff
651
+ const instanceDate = new Date(event.start?.dateTime || event.start?.date || '');
652
+ // Format the date as YYYYMMDD for UNTIL parameter in RRULE
653
+ // Subtract one day to make it exclusive (end before this instance)
654
+ instanceDate.setDate(instanceDate.getDate() - 1);
655
+ const formattedDate = instanceDate.toISOString().slice(0, 10).replace(/-/g, '');
656
+ // Update the recurrence rules to end before this instance
657
+ const updatedRules = masterEvent.recurrence.map(rule => {
658
+ if (rule.startsWith('RRULE:')) {
659
+ // If the rule already has an UNTIL parameter, we need to replace it
660
+ if (rule.includes('UNTIL=')) {
661
+ return rule.replace(/UNTIL=\d+T\d+Z?/, `UNTIL=${formattedDate}`);
648
662
  }
649
- return rule;
650
- });
651
- // Update the master event with the new recurrence rules
652
- await calendar.events.patch({
653
- calendarId: 'primary',
654
- eventId: event.recurringEventId,
655
- sendUpdates,
656
- requestBody: {
657
- recurrence: updatedRules
663
+ else {
664
+ // Otherwise, add the UNTIL parameter
665
+ return `${rule};UNTIL=${formattedDate}`;
658
666
  }
659
- });
660
- // Now delete this specific instance
661
- await calendar.events.delete({
662
- calendarId: 'primary',
663
- eventId,
664
- sendUpdates
665
- });
666
- }
667
- else if (event.recurrence) {
668
- // This is a master event with recurrence rules
669
- // We need to update the recurrence rule to end before this instance
670
- const eventDate = new Date(event.start?.dateTime || event.start?.date || '');
671
- // Format the date as YYYYMMDD for UNTIL parameter in RRULE
672
- const formattedDate = eventDate.toISOString().slice(0, 10).replace(/-/g, '');
673
- // Get the existing recurrence rules
674
- const recurrenceRules = event.recurrence || [];
675
- // Update the RRULE to include UNTIL parameter
676
- const updatedRules = recurrenceRules.map(rule => {
677
- if (rule.startsWith('RRULE:')) {
678
- // If the rule already has an UNTIL parameter, we need to replace it
679
- if (rule.includes('UNTIL=')) {
680
- return rule.replace(/UNTIL=\d+T\d+Z?/, `UNTIL=${formattedDate}`);
681
- }
682
- else {
683
- // Otherwise, add the UNTIL parameter
684
- return `${rule};UNTIL=${formattedDate}`;
685
- }
686
- }
687
- return rule;
688
- });
689
- // Update the master event with the new recurrence rules
690
- await calendar.events.patch({
691
- calendarId: 'primary',
692
- eventId,
693
- sendUpdates,
694
- requestBody: {
695
- recurrence: updatedRules
696
- }
697
- });
698
- }
699
- }
700
- catch (error) {
701
- if (error instanceof CalendarError) {
702
- throw error;
703
- }
704
- // If we can't get the event or another error occurs, fall back to simple delete
667
+ }
668
+ return rule;
669
+ });
670
+ // Update the master event with the new recurrence rules
671
+ await calendar.events.patch({
672
+ calendarId: 'primary',
673
+ eventId: event.recurringEventId,
674
+ sendUpdates,
675
+ requestBody: {
676
+ recurrence: updatedRules
677
+ }
678
+ });
679
+ // Now delete this specific instance
705
680
  await calendar.events.delete({
706
681
  calendarId: 'primary',
707
682
  eventId,
708
683
  sendUpdates
709
684
  });
710
685
  }
686
+ else if (event.recurrence) {
687
+ // This is a master event with recurrence rules
688
+ // We need to update the recurrence rule to end before this instance
689
+ const eventDate = new Date(event.start?.dateTime || event.start?.date || '');
690
+ // Format the date as YYYYMMDD for UNTIL parameter in RRULE
691
+ const formattedDate = eventDate.toISOString().slice(0, 10).replace(/-/g, '');
692
+ // Get the existing recurrence rules
693
+ const recurrenceRules = event.recurrence || [];
694
+ // Update the RRULE to include UNTIL parameter
695
+ const updatedRules = recurrenceRules.map(rule => {
696
+ if (rule.startsWith('RRULE:')) {
697
+ // If the rule already has an UNTIL parameter, we need to replace it
698
+ if (rule.includes('UNTIL=')) {
699
+ return rule.replace(/UNTIL=\d+T\d+Z?/, `UNTIL=${formattedDate}`);
700
+ }
701
+ else {
702
+ // Otherwise, add the UNTIL parameter
703
+ return `${rule};UNTIL=${formattedDate}`;
704
+ }
705
+ }
706
+ return rule;
707
+ });
708
+ // Update the master event with the new recurrence rules
709
+ await calendar.events.patch({
710
+ calendarId: 'primary',
711
+ eventId,
712
+ sendUpdates,
713
+ requestBody: {
714
+ recurrence: updatedRules
715
+ }
716
+ });
717
+ }
711
718
  });
712
719
  }
713
720
  }
@@ -1,6 +1,6 @@
1
1
  import { google } from 'googleapis';
2
2
  import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
3
- import { describeApiError, isAuthHandoffError } from '../../utils/apiError.js';
3
+ import { describeApiError, isPassthroughGoogleError } from '../../utils/apiError.js';
4
4
  import { DRIVE_SCOPES } from '../drive/scopes.js';
5
5
  const DEFAULT_PAGE_SIZE = 20;
6
6
  // Fields parameter for comments.list — Google API requires explicit field selection
@@ -99,7 +99,7 @@ export class CommentsService extends BaseGoogleService {
99
99
  catch (error) {
100
100
  // An expired/revoked grant must keep its reconnect signal — folding it
101
101
  // into a plain error string would skip the host's auth_required handoff.
102
- if (isAuthHandoffError(error))
102
+ if (isPassthroughGoogleError(error))
103
103
  throw error;
104
104
  return {
105
105
  success: false,
@@ -141,7 +141,7 @@ export class CommentsService extends BaseGoogleService {
141
141
  catch (error) {
142
142
  // An expired/revoked grant must keep its reconnect signal — folding it
143
143
  // into a plain error string would skip the host's auth_required handoff.
144
- if (isAuthHandoffError(error))
144
+ if (isPassthroughGoogleError(error))
145
145
  throw error;
146
146
  return {
147
147
  success: false,
@@ -175,7 +175,7 @@ export class CommentsService extends BaseGoogleService {
175
175
  catch (error) {
176
176
  // An expired/revoked grant must keep its reconnect signal — folding it
177
177
  // into a plain error string would skip the host's auth_required handoff.
178
- if (isAuthHandoffError(error))
178
+ if (isPassthroughGoogleError(error))
179
179
  throw error;
180
180
  return {
181
181
  success: false,
@@ -208,7 +208,7 @@ export class CommentsService extends BaseGoogleService {
208
208
  catch (error) {
209
209
  // An expired/revoked grant must keep its reconnect signal — folding it
210
210
  // into a plain error string would skip the host's auth_required handoff.
211
- if (isAuthHandoffError(error))
211
+ if (isPassthroughGoogleError(error))
212
212
  throw error;
213
213
  return {
214
214
  success: false,
@@ -236,7 +236,7 @@ export class CommentsService extends BaseGoogleService {
236
236
  catch (error) {
237
237
  // An expired/revoked grant must keep its reconnect signal — folding it
238
238
  // into a plain error string would skip the host's auth_required handoff.
239
- if (isAuthHandoffError(error))
239
+ if (isPassthroughGoogleError(error))
240
240
  throw error;
241
241
  return {
242
242
  success: false,
@@ -3,7 +3,8 @@ import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
3
3
  import { TabCopyError, copyTabContent } from './tabCopy.js';
4
4
  import { computeMoveApiIndex } from '../../utils/tabPosition.js';
5
5
  import { DOCS_SCOPES } from './scopes.js';
6
- import { describeApiError, describeApiErrorUntrusted, isAuthHandoffError } from '../../utils/apiError.js';
6
+ import { describeApiError, describeApiErrorUntrusted, extractHttpStatus, isAuthHandoffError, isPassthroughGoogleError } from '../../utils/apiError.js';
7
+ import { preserveGoogleRetryDecision } from '../../utils/google-retry.js';
7
8
  import { wrapUntrustedJsonStrings } from '../../utils/untrusted-content.js';
8
9
  import { ALL_TEXT_KEYS, DocsInputError, TAB_READ_TEXT_OPTIONS, TAB_TREE_FIELDS, TRUNCATION_MARKER, assertUniqueTitle, buildAllTabsText, bodyEndIndex, countWords, descendantsOf, extractBodyText, findAnchor, flatParagraphs, flattenTabs, nextParagraphInContainer, normalizeInsertText, paragraphSearchText, requireTabs, resolveTab, siblingsOf, } from './tabs.js';
9
10
  const DEFAULT_MAX_CHARS = 50000;
@@ -144,7 +145,7 @@ export class DocsService extends BaseGoogleService {
144
145
  catch (error) {
145
146
  // An expired/revoked grant must keep its reconnect signal — folding it
146
147
  // into a plain error string would skip the host's auth_required handoff.
147
- if (isAuthHandoffError(error))
148
+ if (isPassthroughGoogleError(error))
148
149
  throw error;
149
150
  if (error instanceof DocsInputError)
150
151
  throw error;
@@ -272,7 +273,7 @@ export class DocsService extends BaseGoogleService {
272
273
  catch (error) {
273
274
  // An expired/revoked grant must keep its reconnect signal — folding it
274
275
  // into a plain error string would skip the host's auth_required handoff.
275
- if (isAuthHandoffError(error))
276
+ if (isPassthroughGoogleError(error))
276
277
  throw error;
277
278
  return {
278
279
  success: false,
@@ -346,7 +347,7 @@ export class DocsService extends BaseGoogleService {
346
347
  catch (error) {
347
348
  // An expired/revoked grant must keep its reconnect signal — folding it
348
349
  // into a plain error string would skip the host's auth_required handoff.
349
- if (isAuthHandoffError(error))
350
+ if (isPassthroughGoogleError(error))
350
351
  throw error;
351
352
  if (error instanceof DocsInputError)
352
353
  throw error;
@@ -431,7 +432,7 @@ export class DocsService extends BaseGoogleService {
431
432
  catch (error) {
432
433
  // An expired/revoked grant must keep its reconnect signal — folding it
433
434
  // into a plain error string would skip the host's auth_required handoff.
434
- if (isAuthHandoffError(error))
435
+ if (isPassthroughGoogleError(error))
435
436
  throw error;
436
437
  if (error instanceof DocsInputError)
437
438
  throw error;
@@ -501,7 +502,7 @@ export class DocsService extends BaseGoogleService {
501
502
  catch (error) {
502
503
  // An expired/revoked grant must keep its reconnect signal — folding it
503
504
  // into a plain error string would skip the host's auth_required handoff.
504
- if (isAuthHandoffError(error))
505
+ if (isPassthroughGoogleError(error))
505
506
  throw error;
506
507
  if (error instanceof DocsInputError)
507
508
  throw error;
@@ -541,7 +542,7 @@ export class DocsService extends BaseGoogleService {
541
542
  catch (error) {
542
543
  // An expired/revoked grant must keep its reconnect signal — folding it
543
544
  // into a plain error string would skip the host's auth_required handoff.
544
- if (isAuthHandoffError(error))
545
+ if (isPassthroughGoogleError(error))
545
546
  throw error;
546
547
  return {
547
548
  success: false,
@@ -580,7 +581,7 @@ export class DocsService extends BaseGoogleService {
580
581
  catch (error) {
581
582
  // An expired/revoked grant must keep its reconnect signal — folding it
582
583
  // into a plain error string would skip the host's auth_required handoff.
583
- if (isAuthHandoffError(error))
584
+ if (isPassthroughGoogleError(error))
584
585
  throw error;
585
586
  if (error instanceof DocsInputError)
586
587
  throw error;
@@ -606,7 +607,7 @@ export class DocsService extends BaseGoogleService {
606
607
  toFailure(error) {
607
608
  // An expired/revoked grant must keep its reconnect signal — folding it
608
609
  // into a plain error string would skip the host's auth_required handoff.
609
- if (isAuthHandoffError(error))
610
+ if (isPassthroughGoogleError(error))
610
611
  throw error;
611
612
  if (error instanceof DocsInputError)
612
613
  throw error;
@@ -1080,10 +1081,13 @@ export class DocsService extends BaseGoogleService {
1080
1081
  throw cause;
1081
1082
  if (cause instanceof DocsInputError)
1082
1083
  throw cause;
1083
- return {
1084
+ const status = extractHttpStatus(cause);
1085
+ return preserveGoogleRetryDecision({
1084
1086
  success: false,
1085
1087
  error: `Copy failed during "${error.phase}": ${describeApiErrorUntrusted(cause, DOCS_API_ERROR_SOURCE)}.${outcome}`,
1086
- };
1088
+ cause,
1089
+ ...(status === 429 ? { status } : {}),
1090
+ }, cause);
1087
1091
  }
1088
1092
  }
1089
1093
  /** Best-effort removal of a tab a failed copy created. True when it is gone. */
@@ -180,6 +180,10 @@ export interface DocsOperationResult {
180
180
  success: boolean;
181
181
  data?: DocumentResponse | DocsDocument | TabListResponse | TabJsonResponse | DocsBatchUpdateResponse | TabWriteResponse | TabDeleteResponse | InsertTextResponse | TabCopyResponse;
182
182
  error?: string;
183
+ /** Original API failure for the tool boundary's cause chain. */
184
+ cause?: unknown;
185
+ /** HTTP status preserved for the tool boundary when a write wrapper fails. */
186
+ status?: number;
183
187
  occurrencesChanged?: number;
184
188
  }
185
189
  export interface ListTabsOptions {
@@ -3,29 +3,13 @@ import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
3
3
  import { Readable } from 'stream';
4
4
  import { DRIVE_SCOPES } from './scopes.js';
5
5
  import { extractHttpStatus } from '../../utils/apiError.js';
6
+ import { errorText, rateLimitReason } from '../../utils/google-retry.js';
6
7
  const MAX_INLINE_BINARY_BYTES = 500 * 1024; // 500KB
7
8
  /** A 403 caused by a missing OAuth scope (not by the file's sharing settings). */
8
9
  const INSUFFICIENT_SCOPE = /insufficient.*scope|insufficientPermissions|ACCESS_TOKEN_SCOPE_INSUFFICIENT/i;
9
- /** The error's message plus its response body, where Google puts the structured reason. */
10
- function errorText(error) {
11
- const message = error instanceof Error ? error.message : '';
12
- const data = error?.response?.data;
13
- return `${message}\n${typeof data === 'string' ? data : JSON.stringify(data ?? '')}`;
14
- }
15
10
  function isInsufficientScopeError(error) {
16
11
  return INSUFFICIENT_SCOPE.test(errorText(error));
17
12
  }
18
- /** Drive's quota reasons; Google sends these with a 403, so they look like a permission denial. */
19
- const RATE_LIMIT_REASON = /\b(?:userRateLimitExceeded|rateLimitExceeded|dailyLimitExceeded)\b/;
20
- /** The rate-limit reason of a 429, or of a 403 whose structured reason is a quota limit; undefined otherwise. */
21
- function rateLimitReason(error, status) {
22
- if (status !== 403 && status !== 429)
23
- return undefined;
24
- const reason = RATE_LIMIT_REASON.exec(errorText(error))?.[0];
25
- if (reason)
26
- return reason;
27
- return status === 429 ? 'too many requests' : undefined;
28
- }
29
13
  /** A Drive rate limit hit while checking file access. Carries the HTTP status so error descriptions keep it. */
30
14
  class DriveRateLimitError extends Error {
31
15
  status;
@@ -1,6 +1,6 @@
1
1
  import { google } from 'googleapis';
2
2
  import { BaseGoogleService } from '../../services/base/BaseGoogleService.js';
3
- import { describeApiError, isAuthHandoffError } from '../../utils/apiError.js';
3
+ import { describeApiError, isPassthroughGoogleError } from '../../utils/apiError.js';
4
4
  import { FORMS_SCOPES } from './scopes.js';
5
5
  /**
6
6
  * Service for interacting with Google Forms API.
@@ -150,7 +150,7 @@ export class FormsService extends BaseGoogleService {
150
150
  catch (error) {
151
151
  // An expired/revoked grant must keep its reconnect signal — folding it
152
152
  // into a plain error string would skip the host's auth_required handoff.
153
- if (isAuthHandoffError(error))
153
+ if (isPassthroughGoogleError(error))
154
154
  throw error;
155
155
  return {
156
156
  success: false,
@@ -220,7 +220,7 @@ export class FormsService extends BaseGoogleService {
220
220
  catch (error) {
221
221
  // An expired/revoked grant must keep its reconnect signal — folding it
222
222
  // into a plain error string would skip the host's auth_required handoff.
223
- if (isAuthHandoffError(error))
223
+ if (isPassthroughGoogleError(error))
224
224
  throw error;
225
225
  return {
226
226
  success: false,
@@ -285,7 +285,7 @@ export class FormsService extends BaseGoogleService {
285
285
  catch (error) {
286
286
  // An expired/revoked grant must keep its reconnect signal — folding it
287
287
  // into a plain error string would skip the host's auth_required handoff.
288
- if (isAuthHandoffError(error))
288
+ if (isPassthroughGoogleError(error))
289
289
  throw error;
290
290
  return {
291
291
  success: false,
@@ -1,4 +1,4 @@
1
- import { describeApiError } from '../../../utils/apiError.js';
1
+ import { describeApiError, isPassthroughGoogleError } from '../../../utils/apiError.js';
2
2
  import { GmailError } from '../types.js';
3
3
  import { AttachmentIndexService } from '../../attachments/index-service.js';
4
4
  /**
@@ -111,6 +111,8 @@ export class GmailAttachmentService {
111
111
  };
112
112
  }
113
113
  catch (error) {
114
+ if (isPassthroughGoogleError(error))
115
+ throw error;
114
116
  if (error instanceof GmailError)
115
117
  throw error;
116
118
  throw new GmailError('Failed to get attachment', 'ATTACHMENT_ERROR', `Error: ${describeApiError(error)}`);