@mindstone/mcp-server-google-workspace 0.5.12 → 0.5.14

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 (37) hide show
  1. package/README.md +32 -3
  2. package/dist/connectorRenewalClient.d.ts +162 -0
  3. package/dist/connectorRenewalClient.js +212 -0
  4. package/dist/modules/accounts/manager.js +24 -4
  5. package/dist/modules/accounts/oauth.js +5 -2
  6. package/dist/modules/accounts/token.d.ts +1 -0
  7. package/dist/modules/accounts/token.js +18 -8
  8. package/dist/modules/accounts/unauthorized.d.ts +4 -0
  9. package/dist/modules/accounts/unauthorized.js +46 -0
  10. package/dist/modules/calendar/service.js +2 -2
  11. package/dist/modules/docs/markdown.d.ts +67 -0
  12. package/dist/modules/docs/markdown.js +651 -0
  13. package/dist/modules/docs/service.d.ts +1 -1
  14. package/dist/modules/docs/service.js +35 -53
  15. package/dist/modules/docs/types.d.ts +0 -1
  16. package/dist/oauth/coordinatedClient.d.ts +14 -0
  17. package/dist/oauth/coordinatedClient.js +103 -0
  18. package/dist/tools/definitions/chat.js +1 -2
  19. package/dist/tools/definitions/docs.js +4 -8
  20. package/dist/tools/definitions/drive.js +0 -1
  21. package/dist/tools/docs-handlers.d.ts +0 -2
  22. package/dist/tools/docs-handlers.js +0 -2
  23. package/dist/tools/param-normalizer.js +0 -1
  24. package/dist/tools/server.js +8 -23
  25. package/dist/tools/type-guards.d.ts +0 -1
  26. package/dist/tools/type-guards.js +1 -3
  27. package/dist/utils/apiError.d.ts +4 -4
  28. package/dist/utils/apiError.js +7 -6
  29. package/dist/utils/google-retry.d.ts +6 -0
  30. package/dist/utils/google-retry.js +18 -1
  31. package/node_modules/cross-spawn/README.md +19 -3
  32. package/node_modules/cross-spawn/lib/parse.js +38 -10
  33. package/node_modules/cross-spawn/lib/util/escape.js +84 -25
  34. package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
  35. package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
  36. package/node_modules/cross-spawn/package.json +21 -24
  37. package/package.json +1 -1
@@ -4,8 +4,9 @@ import { TabCopyError, copyTabContent } from './tabCopy.js';
4
4
  import { computeMoveApiIndex } from '../../utils/tabPosition.js';
5
5
  import { DOCS_SCOPES } from './scopes.js';
6
6
  import { describeApiError, describeApiErrorUntrusted, extractHttpStatus, failedResult, isAuthHandoffError, isPassthroughGoogleError, withCause } from '../../utils/apiError.js';
7
- import { preserveGoogleRetryDecision } from '../../utils/google-retry.js';
7
+ import { markMayHaveWritten, preserveGoogleRetryDecision } from '../../utils/google-retry.js';
8
8
  import { wrapUntrustedJsonValues } from '../../utils/untrusted-content.js';
9
+ import { markdownToDocsRequests } from './markdown.js';
9
10
  import { ALL_TEXT_KEYS, DocsInputError, quoteTabId, 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';
10
11
  const DEFAULT_MAX_CHARS = 50000;
11
12
  /** Cap on `read_workspace_document` with `tab_id` + `return_json` (enveloped size). */
@@ -223,6 +224,7 @@ export class DocsService extends BaseGoogleService {
223
224
  * Create a new document with optional initial content
224
225
  */
225
226
  async createDocument(email, options) {
227
+ let documentId;
226
228
  try {
227
229
  await this.ensureInitialized();
228
230
  this.checkInitialized();
@@ -234,27 +236,19 @@ export class DocsService extends BaseGoogleService {
234
236
  title: options.title,
235
237
  },
236
238
  });
237
- const documentId = createResponse.data.documentId;
239
+ documentId = createResponse.data.documentId;
238
240
  if (!documentId) {
239
241
  return {
240
242
  success: false,
241
243
  error: 'Failed to create document - no documentId returned',
242
244
  };
243
245
  }
244
- // Add initial content if provided
245
- if (options.content) {
246
+ // Add initial content if provided, its markdown written as formatting
247
+ const contentRequests = options.content ? markdownToDocsRequests(options.content, { index: 1 }) : [];
248
+ if (contentRequests.length > 0) {
246
249
  await client.documents.batchUpdate({
247
250
  documentId,
248
- requestBody: {
249
- requests: [
250
- {
251
- insertText: {
252
- location: { index: 1 },
253
- text: options.content,
254
- },
255
- },
256
- ],
257
- },
251
+ requestBody: { requests: contentRequests },
258
252
  });
259
253
  }
260
254
  const result = {
@@ -270,8 +264,13 @@ export class DocsService extends BaseGoogleService {
270
264
  catch (error) {
271
265
  // An expired/revoked grant must keep its reconnect signal — folding it
272
266
  // into a plain error string would skip the host's auth_required handoff.
273
- if (isPassthroughGoogleError(error))
267
+ if (isPassthroughGoogleError(error)) {
268
+ // The document already exists: a replay would create a second one.
269
+ if (documentId) {
270
+ throw markMayHaveWritten(withCause(new Error(`Created document ${documentId}, but adding its content failed.`), error));
271
+ }
274
272
  throw error;
273
+ }
275
274
  return failedResult(error, describeApiError(error));
276
275
  }
277
276
  }
@@ -288,19 +287,14 @@ export class DocsService extends BaseGoogleService {
288
287
  const { doc, flat } = await this.readAllTabs(client, options.documentId);
289
288
  const tab = resolveTab(flat, options.tabId, { allowDefault: true });
290
289
  const endIndex = bodyEndIndex(tab.tab.documentTab?.body);
291
- await client.documents.batchUpdate({
292
- documentId: options.documentId,
293
- requestBody: {
294
- requests: [
295
- {
296
- insertText: {
297
- location: { index: endIndex, tabId: tab.tabId },
298
- text: options.text,
299
- },
300
- },
301
- ],
302
- },
290
+ const requests = markdownToDocsRequests(options.text, {
291
+ index: endIndex,
292
+ tabId: tab.tabId,
293
+ continuesParagraph: true,
303
294
  });
295
+ if (requests.length > 0) {
296
+ await client.documents.batchUpdate({ documentId: options.documentId, requestBody: { requests } });
297
+ }
304
298
  const result = {
305
299
  title: doc.title || 'Untitled',
306
300
  documentId: options.documentId,
@@ -314,20 +308,11 @@ export class DocsService extends BaseGoogleService {
314
308
  documentId: options.documentId,
315
309
  });
316
310
  const endIndex = this.getDocumentEndIndex(docResponse.data);
317
- // Append text at the end
318
- await client.documents.batchUpdate({
319
- documentId: options.documentId,
320
- requestBody: {
321
- requests: [
322
- {
323
- insertText: {
324
- location: { index: endIndex },
325
- text: options.text,
326
- },
327
- },
328
- ],
329
- },
330
- });
311
+ // Append text at the end, its markdown written as formatting
312
+ const requests = markdownToDocsRequests(options.text, { index: endIndex, continuesParagraph: true });
313
+ if (requests.length > 0) {
314
+ await client.documents.batchUpdate({ documentId: options.documentId, requestBody: { requests } });
315
+ }
331
316
  const result = {
332
317
  title: docResponse.data.title || 'Untitled',
333
318
  documentId: options.documentId,
@@ -366,13 +351,8 @@ export class DocsService extends BaseGoogleService {
366
351
  },
367
352
  });
368
353
  }
369
- // Insert new content at start
370
- requests.push({
371
- insertText: {
372
- location: { index: 1, ...(tabId !== undefined ? { tabId } : {}) },
373
- text: content,
374
- },
375
- });
354
+ // Insert the new content at the start, its markdown written as formatting
355
+ requests.push(...markdownToDocsRequests(content, { index: 1, tabId }));
376
356
  return requests;
377
357
  }
378
358
  /**
@@ -889,7 +869,7 @@ export class DocsService extends BaseGoogleService {
889
869
  /**
890
870
  * Copy one tab's content into another tab of the same document: into a new
891
871
  * tab (`newTabTitle`) or into an existing tab, which is cleared first
892
- * (`targetTabId` + `overwriteExisting`). Every input check, the source read
872
+ * (`targetTabId`). Every input check, the source read
893
873
  * and the per-chip access checks happen before the first write. On a failure
894
874
  * after that, a tab this call created is deleted again (best effort); an
895
875
  * existing target is left as it is and the error says so. A copy that
@@ -911,9 +891,6 @@ export class DocsService extends BaseGoogleService {
911
891
  if (hasTarget && (options.newTabParentId !== undefined || options.newTabPosition !== undefined)) {
912
892
  throw new DocsInputError('new_tab_parent_id and new_tab_position only apply with new_tab_title.');
913
893
  }
914
- if (hasTarget && options.overwriteExisting !== true) {
915
- throw new DocsInputError('Copying into an existing tab clears it first. Pass overwrite_existing: true to confirm, or use new_tab_title to copy into a new tab.');
916
- }
917
894
  const newTitle = hasNewTitle ? requireTabTitle(options.newTabTitle) : undefined;
918
895
  client = await this.getWriteClient(email);
919
896
  const docsClient = client;
@@ -1033,8 +1010,10 @@ export class DocsService extends BaseGoogleService {
1033
1010
  }
1034
1011
  const cause = error.cause;
1035
1012
  let outcome = '';
1013
+ let mayHaveWritten = true;
1036
1014
  if (createdTabId && client) {
1037
1015
  const cleaned = await this.deleteHalfWrittenTab(client, options.documentId, createdTabId);
1016
+ mayHaveWritten = !cleaned;
1038
1017
  outcome = cleaned
1039
1018
  ? ` The new tab ${createdTabId} was deleted again, so nothing changed.`
1040
1019
  : ` The new tab ${createdTabId} could not be deleted and may be partly written; delete it with delete_workspace_document_tab before trying again.`;
@@ -1051,6 +1030,7 @@ export class DocsService extends BaseGoogleService {
1051
1030
  }
1052
1031
  else {
1053
1032
  outcome = ' Nothing was written to the document.';
1033
+ mayHaveWritten = false;
1054
1034
  }
1055
1035
  // Auth handoffs keep their reconnect signal (after the cleanup attempt).
1056
1036
  if (isAuthHandoffError(cause))
@@ -1058,11 +1038,13 @@ export class DocsService extends BaseGoogleService {
1058
1038
  if (cause instanceof DocsInputError)
1059
1039
  throw cause;
1060
1040
  const status = extractHttpStatus(cause);
1061
- return preserveGoogleRetryDecision(withCause({
1041
+ const failure = preserveGoogleRetryDecision(withCause({
1062
1042
  success: false,
1063
1043
  error: `Copy failed during "${error.phase}": ${describeApiErrorUntrusted(cause, DOCS_API_ERROR_SOURCE)}.${outcome}`,
1064
1044
  ...(status === 429 ? { status } : {}),
1065
1045
  }, cause), cause);
1046
+ // Re-running a copy that may have written would write it twice.
1047
+ return mayHaveWritten ? markMayHaveWritten(failure) : failure;
1066
1048
  }
1067
1049
  }
1068
1050
  /** Best-effort removal of a tab a failed copy created. True when it is gone. */
@@ -151,7 +151,6 @@ export interface CopyTabOptions {
151
151
  documentId: string;
152
152
  sourceTabId: string;
153
153
  targetTabId?: string;
154
- overwriteExisting?: boolean;
155
154
  newTabTitle?: string;
156
155
  newTabParentId?: string;
157
156
  newTabPosition?: number;
@@ -0,0 +1,14 @@
1
+ import { OAuth2Client, type Credentials } from 'google-auth-library';
2
+ type Credential = {
3
+ relativePath: string;
4
+ read: () => Promise<unknown>;
5
+ save: (tokens: Credentials) => Promise<void>;
6
+ };
7
+ /** Register only a token already read from its account's credential file; never search other accounts. */
8
+ export declare function registerGoogleCredential(file: string, token: unknown, read: Credential['read'], save: Credential['save']): void;
9
+ /** The SDK's explicit refresh and API-request automatic refresh both enter this protected seam (10.6.2). */
10
+ export declare class CoordinatedOAuth2Client extends OAuth2Client {
11
+ protected refreshTokenNoCache(refreshToken?: string | null): Promise<import("google-auth-library/build/src/auth/oauth2client.js").GetTokenResponse>;
12
+ }
13
+ export {};
14
+ //# sourceMappingURL=coordinatedClient.d.ts.map
@@ -0,0 +1,103 @@
1
+ import path from 'node:path';
2
+ import { OAuth2Client } from 'google-auth-library';
3
+ import { z } from 'zod';
4
+ import { ConnectorRenewal, RenewalAttemptError, RenewalWaitError } from '../connectorRenewalClient.js';
5
+ const SavedToken = z.object({
6
+ access_token: z.string().min(1), refresh_token: z.string().min(1),
7
+ expiry_date: z.number().finite().optional(), scope: z.string().optional(), token_type: z.string().optional(),
8
+ }).passthrough();
9
+ const credentials = new Map();
10
+ const credentialKeys = new Map();
11
+ let coordinator;
12
+ /** Register only a token already read from its account's credential file; never search other accounts. */
13
+ export function registerGoogleCredential(file, token, read, save) {
14
+ if (!process.env.GOOGLE_WORKSPACE_RENEWAL_COORDINATOR_STATE)
15
+ return;
16
+ const parsed = SavedToken.safeParse(token);
17
+ const oldKey = credentialKeys.get(file);
18
+ if (oldKey)
19
+ credentials.delete(oldKey);
20
+ credentialKeys.delete(file);
21
+ if (!parsed.success)
22
+ return;
23
+ // CREDENTIALS_PATH is <provider folder>/<instance>/credentials (or the standalone credentials folder).
24
+ const instance = path.dirname(path.dirname(file));
25
+ const relativePath = path.basename(instance) === 'google-workspace-mcp'
26
+ ? `credentials/${path.basename(file)}`
27
+ : `${path.basename(instance)}/credentials/${path.basename(file)}`;
28
+ credentials.set(parsed.data.refresh_token, { relativePath, read, save });
29
+ credentialKeys.set(file, parsed.data.refresh_token);
30
+ }
31
+ function normalized(token) {
32
+ return { accessToken: token.access_token, refreshToken: token.refresh_token, expiresAt: token.expiry_date ?? null };
33
+ }
34
+ const RefreshResponse = z.object({
35
+ access_token: z.string().min(1), refresh_token: z.string().min(1).optional(),
36
+ expires_in: z.number().positive().finite(), scope: z.string().optional(), token_type: z.string().optional(),
37
+ });
38
+ /** The SDK's explicit refresh and API-request automatic refresh both enter this protected seam (10.6.2). */
39
+ export class CoordinatedOAuth2Client extends OAuth2Client {
40
+ async refreshTokenNoCache(refreshToken) {
41
+ const statePath = process.env.GOOGLE_WORKSPACE_RENEWAL_COORDINATOR_STATE;
42
+ if (!statePath)
43
+ return super.refreshTokenNoCache(refreshToken);
44
+ const disabled = process.env.GOOGLE_WORKSPACE_DISABLE_REFRESH;
45
+ if (disabled && disabled !== '0' && disabled.toLowerCase() !== 'false')
46
+ throw new RenewalWaitError();
47
+ const credential = refreshToken ? credentials.get(refreshToken) : undefined;
48
+ if (!credential)
49
+ throw new RenewalWaitError();
50
+ const original = SavedToken.parse(await credential.read());
51
+ if (original.refresh_token !== refreshToken)
52
+ throw new RenewalWaitError();
53
+ if (coordinator?.path !== statePath)
54
+ coordinator = { path: statePath, client: new ConnectorRenewal(statePath) };
55
+ let saved = original;
56
+ const result = await coordinator.client.refresh({ provider: 'google-workspace', relativePath: credential.relativePath }, normalized(original), async (permitted, dispatched) => {
57
+ const latest = SavedToken.safeParse(await credential.read());
58
+ if (!latest.success || latest.data.refresh_token !== refreshToken)
59
+ throw new RenewalWaitError();
60
+ const body = new URLSearchParams({ client_id: this._clientId ?? '', client_secret: this._clientSecret ?? '',
61
+ grant_type: 'refresh_token', refresh_token: permitted.refreshToken });
62
+ if (!this._clientId || !this._clientSecret)
63
+ throw new RenewalWaitError();
64
+ const signal = AbortSignal.timeout(30000);
65
+ dispatched();
66
+ const response = await globalThis.fetch(this.endpoints.oauth2TokenUrl, {
67
+ method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, signal,
68
+ });
69
+ const data = await response.json();
70
+ if (!response.ok) {
71
+ const failure = z.object({ error: z.string() }).safeParse(data);
72
+ throw new RenewalAttemptError(response.status < 500 && failure.success &&
73
+ failure.data.error === 'invalid_grant'
74
+ ? 'rejected' : response.status >= 400 && response.status < 500 ? 'not_dispatched' : 'uncertain');
75
+ }
76
+ const fresh = RefreshResponse.parse(data);
77
+ saved = { ...original, ...fresh, refresh_token: fresh.refresh_token ?? permitted.refreshToken,
78
+ expiry_date: Date.now() + fresh.expires_in * 1000 };
79
+ return normalized(SavedToken.parse(saved));
80
+ }, async (tokens) => {
81
+ const latest = SavedToken.safeParse(await credential.read());
82
+ if (!latest.success || !(latest.data.access_token === original.access_token
83
+ && latest.data.refresh_token === original.refresh_token
84
+ || latest.data.access_token === tokens.accessToken && latest.data.refresh_token === tokens.refreshToken)) {
85
+ throw new RenewalAttemptError('uncertain');
86
+ }
87
+ saved = { ...original, ...saved, access_token: tokens.accessToken,
88
+ refresh_token: tokens.refreshToken ?? original.refresh_token, expiry_date: tokens.expiresAt ?? undefined };
89
+ await credential.save(saved);
90
+ }, async () => {
91
+ const legacy = await super.refreshTokenNoCache(refreshToken);
92
+ saved = { ...original, ...legacy.tokens, refresh_token: legacy.tokens.refresh_token ?? refreshToken };
93
+ return normalized(SavedToken.parse(saved));
94
+ });
95
+ const tokens = { ...saved, access_token: result.accessToken, refresh_token: result.refreshToken,
96
+ expiry_date: result.expiresAt ?? undefined };
97
+ // The SDK restores this field after refreshTokenNoCache; keep that restoration on the new rotation.
98
+ if (this.credentials.refresh_token === refreshToken)
99
+ this.credentials.refresh_token = tokens.refresh_token;
100
+ return { tokens, res: null };
101
+ }
102
+ }
103
+ //# sourceMappingURL=coordinatedClient.js.map
@@ -100,8 +100,7 @@ export const chatTools = [
100
100
  category: "Chat",
101
101
  description: `Post a plain-text message to a Google Chat space as the authenticated user.
102
102
 
103
- This sends a real message visible to everyone in the space. Confirm the space
104
- and the message content with the user before sending.
103
+ This sends a real message visible to everyone in the space.
105
104
 
106
105
  Use list_chat_spaces first to find the space resource name (e.g. "spaces/AAAA...").
107
106
 
@@ -730,8 +730,8 @@ export const docsTools = [
730
730
  apply with new_tab_title.
731
731
 
732
732
  Which target: to archive or duplicate a tab, use new_tab_title. To reset a tab in place from a
733
- template (keeping its id, position and sub-tabs), use target_tab_id with overwrite_existing:
734
- true, which clears the tab first. Never delete a tab in order to replace it: deleting also
733
+ template (keeping its id, position and sub-tabs), use target_tab_id, which clears the tab
734
+ first. Never delete a tab in order to replace it: deleting also
735
735
  deletes its sub-tabs. target_tab_id needs a real tab id ("default" is refused);
736
736
  source_tab_id and new_tab_parent_id accept "default" for the first tab.
737
737
 
@@ -756,7 +756,7 @@ export const docsTools = [
756
756
  { "email": "user@example.com", "document_id": "1ABC123xyz", "source_tab_id": "t.live01", "new_tab_title": "2031-10-13", "new_tab_parent_id": "t.live01", "new_tab_position": 0 }
757
757
 
758
758
  2. Reset the live tab from the Template tab (clears it first):
759
- { "email": "user@example.com", "document_id": "1ABC123xyz", "source_tab_id": "t.tmpl02", "target_tab_id": "t.live01", "overwrite_existing": true }`,
759
+ { "email": "user@example.com", "document_id": "1ABC123xyz", "source_tab_id": "t.tmpl02", "target_tab_id": "t.live01" }`,
760
760
  aliases: ['copy_doc_tab', 'duplicate_document_tab', 'clone_document_tab'],
761
761
  annotations: { readOnlyHint: false, destructiveHint: true },
762
762
  inputSchema: {
@@ -776,11 +776,7 @@ export const docsTools = [
776
776
  },
777
777
  target_tab_id: {
778
778
  type: 'string',
779
- description: 'Existing tab to copy into; it is cleared first and needs overwrite_existing: true ("default" is not accepted). Not with new_tab_title.'
780
- },
781
- overwrite_existing: {
782
- type: 'boolean',
783
- description: 'Confirms that target_tab_id will be cleared and overwritten (required with target_tab_id).'
779
+ description: 'Existing tab to copy into; it is cleared first ("default" is not accepted). Not with new_tab_title.'
784
780
  },
785
781
  new_tab_title: {
786
782
  type: 'string',
@@ -443,7 +443,6 @@ COMMON MISTAKES:
443
443
  1. Verify account access with list_workspace_accounts
444
444
  2. Confirm account if multiple exist
445
445
  3. Check Drive write permissions
446
- 4. Confirm deletion is intended
447
446
 
448
447
  Example Flow:
449
448
  1. Check account access
@@ -125,8 +125,6 @@ interface CopyDocumentTabArgs {
125
125
  sourceTabId?: string;
126
126
  target_tab_id?: string;
127
127
  targetTabId?: string;
128
- overwrite_existing?: boolean;
129
- overwriteExisting?: boolean;
130
128
  new_tab_title?: string;
131
129
  newTabTitle?: string;
132
130
  new_tab_parent_id?: string;
@@ -602,7 +602,6 @@ export async function handleCopyDocumentTab(args) {
602
602
  const documentId = readAliasedString(rawArgs, 'document_id', 'documentId');
603
603
  const sourceTabId = readAliasedString(rawArgs, 'source_tab_id', 'sourceTabId');
604
604
  const targetTabId = readAliasedString(rawArgs, 'target_tab_id', 'targetTabId');
605
- const overwriteExisting = readAliasedBoolean(rawArgs, 'overwrite_existing', 'overwriteExisting');
606
605
  const newTabTitle = readAliasedString(rawArgs, 'new_tab_title', 'newTabTitle');
607
606
  const newTabParentId = readAliasedString(rawArgs, 'new_tab_parent_id', 'newTabParentId');
608
607
  const newTabPosition = readAliasedNumber(rawArgs, 'new_tab_position', 'newTabPosition');
@@ -618,7 +617,6 @@ export async function handleCopyDocumentTab(args) {
618
617
  documentId: documentId,
619
618
  sourceTabId: sourceTabId,
620
619
  ...(targetTabId !== undefined ? { targetTabId } : {}),
621
- ...(overwriteExisting !== undefined ? { overwriteExisting } : {}),
622
620
  ...(newTabTitle !== undefined ? { newTabTitle } : {}),
623
621
  ...(newTabParentId !== undefined ? { newTabParentId } : {}),
624
622
  ...(newTabPosition !== undefined ? { newTabPosition } : {}),
@@ -43,7 +43,6 @@ const LEGACY_ALIASES = {
43
43
  deleteSubTabs: 'delete_sub_tabs',
44
44
  sourceTabId: 'source_tab_id',
45
45
  targetTabId: 'target_tab_id',
46
- overwriteExisting: 'overwrite_existing',
47
46
  newTabTitle: 'new_tab_title',
48
47
  newTabParentId: 'new_tab_parent_id',
49
48
  newTabPosition: 'new_tab_position',
@@ -3,8 +3,9 @@ import { createRequire } from 'node:module';
3
3
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
4
  import { createStdioTransport } from "./stdio-transport.js";
5
5
  import logger, { renderLogArg } from '../utils/logger.js';
6
- import { isGoogleRecoveryExhausted } from '../utils/google-retry.js';
6
+ import { isGoogleRecoveryExhausted, mayHaveWritten } from '../utils/google-retry.js';
7
7
  import { GENERIC_NEXT_STEP, classifyGoogleFailure, envelopeErrorDetail, googleFailureNextStep, hasErrorDetails, summariseGoogleError, } from '../utils/apiError.js';
8
+ import { isGoogleAuthFailure } from '../modules/accounts/unauthorized.js';
8
9
  import { CallToolRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js";
9
10
  const require = createRequire(import.meta.url);
10
11
  const pkg = require('../../package.json');
@@ -757,34 +758,18 @@ export class GSuiteServer {
757
758
  // the string auth codes checked below).
758
759
  const rawCode = error?.code;
759
760
  const code = typeof rawCode === 'string' ? rawCode : undefined;
760
- const status = typeof error === 'object' && error !== null
761
- ? error.response?.status
762
- ?? error.status
763
- ?? error.code
764
- : undefined;
765
- const numericStatus = typeof status === 'number'
766
- ? status
767
- : typeof status === 'string' && /^\d+$/.test(status)
768
- ? Number(status)
769
- : undefined;
770
- if (code === 'AUTH_REQUIRED' || code === 'HOST_ORCHESTRATED_AUTH_REQUIRED') {
761
+ if (code === 'AUTH_REQUIRED' || code === 'HOST_ORCHESTRATED_AUTH_REQUIRED' || isGoogleAuthFailure(error)) {
771
762
  return {
772
763
  status: 'auth_required',
773
764
  user_action: { id: 'google.connect_account' },
774
765
  agent_action: {
775
766
  instruction: "Connect Google Workspace to continue. The user will be redirected to Google's sign-in."
776
767
  },
777
- setupToolName: 'authenticate_workspace_account'
778
- };
779
- }
780
- if (numericStatus === 401) {
781
- return {
782
- status: 'auth_required',
783
- user_action: { id: 'google.connect_account' },
784
- agent_action: {
785
- instruction: "Connect Google Workspace to continue. The user will be redirected to Google's sign-in."
786
- },
787
- setupToolName: 'authenticate_workspace_account'
768
+ setupToolName: 'authenticate_workspace_account',
769
+ // The request may already have partly run: say what happened so it is checked, not repeated.
770
+ ...(mayHaveWritten(error)
771
+ ? errorDetailField(`${errorDetailText(error)} This request may already have partly run; check the result before trying it again.`)
772
+ : {})
788
773
  };
789
774
  }
790
775
  // Connector input checks: the connector's own guidance about the caller's input.
@@ -178,7 +178,6 @@ interface CopyDocumentTabArgs {
178
178
  documentId: string;
179
179
  sourceTabId: string;
180
180
  targetTabId?: string;
181
- overwriteExisting?: boolean;
182
181
  newTabTitle?: string;
183
182
  newTabParentId?: string;
184
183
  newTabPosition?: number;
@@ -654,7 +654,6 @@ export function isCopyDocumentTabArgs(args) {
654
654
  const documentId = readAliasedArg(rawParams, 'document_id', 'documentId');
655
655
  const sourceTabId = readAliasedArg(rawParams, 'source_tab_id', 'sourceTabId');
656
656
  const targetTabId = readAliasedArg(rawParams, 'target_tab_id', 'targetTabId');
657
- const overwriteExisting = readAliasedArg(rawParams, 'overwrite_existing', 'overwriteExisting');
658
657
  const newTabTitle = readAliasedArg(rawParams, 'new_tab_title', 'newTabTitle');
659
658
  const newTabParentId = readAliasedArg(rawParams, 'new_tab_parent_id', 'newTabParentId');
660
659
  const newTabPosition = readAliasedArg(rawParams, 'new_tab_position', 'newTabPosition');
@@ -663,14 +662,13 @@ export function isCopyDocumentTabArgs(args) {
663
662
  typeof documentId === 'string' &&
664
663
  typeof sourceTabId === 'string' &&
665
664
  isOptional(targetTabId, 'string') &&
666
- isOptional(overwriteExisting, 'boolean') &&
667
665
  isOptional(newTabTitle, 'string') &&
668
666
  isOptional(newTabParentId, 'string') &&
669
667
  isOptional(newTabPosition, 'number');
670
668
  }
671
669
  export function assertCopyDocumentTabArgs(args) {
672
670
  if (!isCopyDocumentTabArgs(args)) {
673
- throw new Error('Invalid copy document tab parameters. Required: document_id, source_tab_id, and either target_tab_id (with overwrite_existing: true) or new_tab_title. Optional with new_tab_title: new_tab_parent_id (string), new_tab_position (number)');
671
+ throw new Error('Invalid copy document tab parameters. Required: document_id, source_tab_id, and either target_tab_id or new_tab_title. Optional with new_tab_title: new_tab_parent_id (string), new_tab_position (number)');
674
672
  }
675
673
  }
676
674
  export function isBatchUpdateDocumentArgs(args) {
@@ -90,10 +90,10 @@ export declare function hasErrorDetails(error: unknown): error is {
90
90
  */
91
91
  export declare function isAuthHandoffError(error: unknown): boolean;
92
92
  /**
93
- * True when the server's `formatErrorResponse` owns this error's tool result: an
94
- * auth hand-off code (the `auth_required` reconnect, or a pass-through such as
95
- * `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose `resolution` is connector
96
- * text. A handler's own result builder rethrows these instead of summarising them,
93
+ * True when the server's `formatErrorResponse` owns this error's tool result: a
94
+ * wrapped Google auth failure, an auth hand-off code (the `auth_required` reconnect,
95
+ * or a pass-through such as `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose
96
+ * `resolution` is connector text. A handler's result builder rethrows these instead of summarising them,
97
97
  * so the resolution and the hand-off are written in one place.
98
98
  */
99
99
  export declare function isServerFormattedError(error: unknown): boolean;
@@ -3,6 +3,7 @@ import { wrapUntrustedContent } from './untrusted-controls.js';
3
3
  import { unwrapUntrusted } from './untrusted-content.js';
4
4
  import { GOOGLE_RATE_LIMIT_NEXT_STEP, LONG_WINDOW_QUOTA, errorText, isGoogleRecoveryExhausted, isShortWindowRateLimit, preserveGoogleRetryDecision, } from './google-retry.js';
5
5
  import { AccountError } from '../modules/accounts/types.js';
6
+ import { isGoogleAuthFailure } from '../modules/accounts/unauthorized.js';
6
7
  /**
7
8
  * Links `target` to the original thrown value as a non-enumerable `cause`, so
8
9
  * status and reason stay reachable (cause-walking readers) without the original
@@ -267,18 +268,18 @@ export function isAuthHandoffError(error) {
267
268
  return typeof code === 'string' && AUTH_HANDOFF_CODES.has(code);
268
269
  }
269
270
  /**
270
- * True when the server's `formatErrorResponse` owns this error's tool result: an
271
- * auth hand-off code (the `auth_required` reconnect, or a pass-through such as
272
- * `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose `resolution` is connector
273
- * text. A handler's own result builder rethrows these instead of summarising them,
271
+ * True when the server's `formatErrorResponse` owns this error's tool result: a
272
+ * wrapped Google auth failure, an auth hand-off code (the `auth_required` reconnect,
273
+ * or a pass-through such as `CREDENTIAL_FILE_REFUSED`) or any `AccountError`, whose
274
+ * `resolution` is connector text. A handler's result builder rethrows these instead of summarising them,
274
275
  * so the resolution and the hand-off are written in one place.
275
276
  */
276
277
  export function isServerFormattedError(error) {
277
- return isAuthHandoffError(error) || error instanceof AccountError;
278
+ return isAuthHandoffError(error) || error instanceof AccountError || isGoogleAuthFailure(error);
278
279
  }
279
280
  /** Keep structured recovery decisions out of lossy string-only error results. */
280
281
  export function isPassthroughGoogleError(error) {
281
- return isAuthHandoffError(error) || isGoogleRecoveryExhausted(error) || extractHttpStatus(error) === 429 || isShortWindowRateLimit(error);
282
+ return isAuthHandoffError(error) || isGoogleAuthFailure(error) || isGoogleRecoveryExhausted(error) || extractHttpStatus(error) === 429 || isShortWindowRateLimit(error);
282
283
  }
283
284
  /**
284
285
  * Normalizes any thrown value into an error suitable for a tool handler's outer
@@ -8,6 +8,12 @@ export declare function rateLimitReason(error: unknown, status: number | undefin
8
8
  export declare function isShortWindowRateLimit(error: unknown): boolean;
9
9
  /** Only this request policy can declare a terminal retry decision. */
10
10
  export declare function isGoogleRecoveryExhausted(error: unknown): boolean;
11
+ /**
12
+ * Marks a failure from an operation that may already have changed the user's data,
13
+ * so a token renewal never re-runs it (the retry would repeat those writes).
14
+ */
15
+ export declare function markMayHaveWritten<T extends object>(target: T): T;
16
+ export declare function mayHaveWritten(error: unknown): boolean;
11
17
  export declare function preserveGoogleRetryDecision<T extends object>(target: T, cause: unknown): T;
12
18
  export declare function createGoogleRetryConfig({ sleep, random, }?: {
13
19
  sleep?: (ms: number) => Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { extractHttpStatus } from './apiError.js';
2
2
  const TERMINAL_RETRY_DECISION = Symbol.for('google-workspace.terminal-retry-decision');
3
+ const MAY_HAVE_WRITTEN = Symbol.for('google-workspace.may-have-written');
3
4
  const RETRY_METHODS = new Set(['GET', 'HEAD', 'PUT', 'OPTIONS', 'DELETE']);
4
5
  const EXTENDED_RATE_LIMIT_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
5
6
  // Google's documented exponential backoff caps at 32–64 seconds. Our 32-second
@@ -44,18 +45,34 @@ export function isShortWindowRateLimit(error) {
44
45
  }
45
46
  /** Only this request policy can declare a terminal retry decision. */
46
47
  export function isGoogleRecoveryExhausted(error) {
48
+ return hasMark(error, TERMINAL_RETRY_DECISION);
49
+ }
50
+ function hasMark(error, mark) {
47
51
  const seen = new Set();
48
52
  while (typeof error === 'object' && error !== null && !seen.has(error)) {
49
- if (error[TERMINAL_RETRY_DECISION] === true)
53
+ if (error[mark] === true)
50
54
  return true;
51
55
  seen.add(error);
52
56
  error = error.cause;
53
57
  }
54
58
  return false;
55
59
  }
60
+ /**
61
+ * Marks a failure from an operation that may already have changed the user's data,
62
+ * so a token renewal never re-runs it (the retry would repeat those writes).
63
+ */
64
+ export function markMayHaveWritten(target) {
65
+ Object.defineProperty(target, MAY_HAVE_WRITTEN, { value: true });
66
+ return target;
67
+ }
68
+ export function mayHaveWritten(error) {
69
+ return hasMark(error, MAY_HAVE_WRITTEN);
70
+ }
56
71
  export function preserveGoogleRetryDecision(target, cause) {
57
72
  if (isGoogleRecoveryExhausted(cause))
58
73
  Object.defineProperty(target, TERMINAL_RETRY_DECISION, { value: true });
74
+ if (mayHaveWritten(cause))
75
+ markMayHaveWritten(target);
59
76
  return target;
60
77
  }
61
78
  function retryAfterMs(error) {