@mindstone/mcp-server-google-workspace 0.1.5 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +28 -9
  2. package/dist/modules/accounts/manager.js +20 -2
  3. package/dist/modules/accounts/token.d.ts +13 -0
  4. package/dist/modules/accounts/token.js +73 -58
  5. package/dist/modules/accounts/types.d.ts +1 -0
  6. package/dist/modules/calendar/service.js +9 -0
  7. package/dist/modules/chat/index.d.ts +12 -0
  8. package/dist/modules/chat/index.js +18 -0
  9. package/dist/modules/chat/scopes.d.ts +14 -0
  10. package/dist/modules/chat/scopes.js +32 -0
  11. package/dist/modules/chat/types.d.ts +88 -0
  12. package/dist/modules/chat/types.js +14 -0
  13. package/dist/modules/comments/service.js +26 -5
  14. package/dist/modules/contacts/scopes.d.ts +1 -0
  15. package/dist/modules/contacts/scopes.js +2 -2
  16. package/dist/modules/contacts/types.d.ts +34 -0
  17. package/dist/modules/docs/index.js +2 -1
  18. package/dist/modules/docs/service.js +36 -7
  19. package/dist/modules/drive/activity-service.d.ts +45 -0
  20. package/dist/modules/drive/activity-service.js +114 -0
  21. package/dist/modules/drive/index.d.ts +4 -0
  22. package/dist/modules/drive/index.js +12 -0
  23. package/dist/modules/drive/scopes.d.ts +1 -0
  24. package/dist/modules/drive/scopes.js +3 -0
  25. package/dist/modules/drive/service.d.ts +2 -1
  26. package/dist/modules/drive/service.js +29 -0
  27. package/dist/modules/drive/types.d.ts +8 -0
  28. package/dist/modules/forms/service.js +16 -3
  29. package/dist/modules/gmail/services/attachment.js +2 -1
  30. package/dist/modules/gmail/services/base.d.ts +5 -1
  31. package/dist/modules/gmail/services/base.js +10 -1
  32. package/dist/modules/gmail/services/draft.js +13 -7
  33. package/dist/modules/gmail/services/email.js +4 -3
  34. package/dist/modules/gmail/services/label.js +10 -9
  35. package/dist/modules/gmail/services/settings.d.ts +14 -1
  36. package/dist/modules/gmail/services/settings.js +96 -1
  37. package/dist/modules/gmail/types.d.ts +36 -0
  38. package/dist/modules/meet/index.d.ts +12 -0
  39. package/dist/modules/meet/index.js +18 -0
  40. package/dist/modules/meet/scopes.d.ts +9 -0
  41. package/dist/modules/meet/scopes.js +25 -0
  42. package/dist/modules/meet/types.d.ts +97 -0
  43. package/dist/modules/meet/types.js +14 -0
  44. package/dist/modules/sheets/service.js +49 -0
  45. package/dist/modules/slides/service.js +31 -6
  46. package/dist/modules/tasks/service.js +31 -6
  47. package/dist/resources/compose-email-template.d.ts +1 -1
  48. package/dist/resources/compose-email-template.js +388 -19
  49. package/dist/services/base/BaseGoogleService.d.ts +9 -1
  50. package/dist/services/base/BaseGoogleService.js +33 -1
  51. package/dist/services/chat/index.d.ts +34 -0
  52. package/dist/services/chat/index.js +120 -0
  53. package/dist/services/contacts/index.d.ts +19 -1
  54. package/dist/services/contacts/index.js +124 -0
  55. package/dist/services/meet/index.d.ts +35 -0
  56. package/dist/services/meet/index.js +116 -0
  57. package/dist/tools/calendar-handlers.js +28 -23
  58. package/dist/tools/chat-handlers.d.ts +14 -0
  59. package/dist/tools/chat-handlers.js +126 -0
  60. package/dist/tools/contacts-handlers.d.ts +31 -0
  61. package/dist/tools/contacts-handlers.js +96 -23
  62. package/dist/tools/definitions/account.js +8 -1
  63. package/dist/tools/definitions/chat.d.ts +3 -0
  64. package/dist/tools/definitions/chat.js +137 -0
  65. package/dist/tools/definitions/contacts.js +82 -0
  66. package/dist/tools/definitions/destructive-overrides.json +12 -0
  67. package/dist/tools/definitions/drive.js +132 -6
  68. package/dist/tools/definitions/gmail.js +94 -0
  69. package/dist/tools/definitions/index.d.ts +2 -0
  70. package/dist/tools/definitions/index.js +6 -0
  71. package/dist/tools/definitions/meet.d.ts +3 -0
  72. package/dist/tools/definitions/meet.js +149 -0
  73. package/dist/tools/definitions/open-world-overrides.json +12 -0
  74. package/dist/tools/drive-handlers.d.ts +27 -0
  75. package/dist/tools/drive-handlers.js +93 -2
  76. package/dist/tools/forms-handlers.js +5 -12
  77. package/dist/tools/gmail-handlers.d.ts +31 -1
  78. package/dist/tools/gmail-handlers.js +167 -35
  79. package/dist/tools/meet-handlers.d.ts +42 -0
  80. package/dist/tools/meet-handlers.js +144 -0
  81. package/dist/tools/server.js +67 -5
  82. package/dist/tools/tasks-handlers.js +7 -18
  83. package/dist/tools/type-guards.d.ts +3 -1
  84. package/dist/tools/type-guards.js +22 -2
  85. package/dist/tools/types.d.ts +13 -0
  86. package/dist/utils/apiError.d.ts +49 -0
  87. package/dist/utils/apiError.js +96 -0
  88. package/dist/utils/scope-hierarchy.js +10 -0
  89. package/dist/utils/service-initializer.js +9 -0
  90. package/dist/utils/untrusted-content.d.ts +37 -1
  91. package/dist/utils/untrusted-content.js +61 -6
  92. package/package.json +5 -1
  93. package/dist/services/calendar/index.d.ts +0 -27
  94. package/dist/services/calendar/index.js +0 -146
  95. package/dist/services/gmail/index.d.ts +0 -39
  96. package/dist/services/gmail/index.js +0 -337
package/README.md CHANGED
@@ -2,15 +2,15 @@
2
2
 
3
3
  [![License: FSL-1.1-MIT](https://img.shields.io/badge/License-FSL--1.1--MIT-blue.svg)](./LICENSE)
4
4
 
5
- Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Comments, and account diagnostics, with optional Tasks and Forms behind a feature flag.
5
+ Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Comments, and account diagnostics, with optional Tasks and Forms behind a feature flag.
6
6
 
7
7
  *Multi-account Google Workspace MCP. Host-orchestrated OAuth (the connector neither runs a callback server nor mints OAuth URLs), atomic per-account credential writes, and a structured `auth_required` handoff so the host drives the sign-in flow rather than the server.*
8
8
 
9
9
  ## Status
10
10
 
11
- - **Version:** [0.1.5](./CHANGELOG.md) · npm: not yet published
11
+ - **Version:** [0.3.0](./CHANGELOG.md) · npm: not yet published
12
12
  - **Auth:** OAuth (host-orchestrated) ([`GOOGLE_CLIENT_SECRET`](./server.json))
13
- - **Tools:** [94](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Comments, Account; +10 gated Tasks/Forms behind `ENABLE_GOOGLE_TASKS_FORMS=true`)
13
+ - **Tools:** [106](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Comments, Account; +10 gated Tasks/Forms behind `ENABLE_GOOGLE_TASKS_FORMS=true`)
14
14
  - **Surface:** cloud-api
15
15
  - **Machine-readable:** [`STATUS.json`](./STATUS.json)
16
16
 
@@ -18,7 +18,7 @@ This connector is based on [aaronsb/google-workspace-mcp](https://github.com/aar
18
18
 
19
19
  ## Why this exists
20
20
 
21
- When we ported this in early 2026, Google had not published a first-party MCP server for the Workspace surface. The community options at the time each got parts of the job right — Aaron Brown's [aaronsb/google-workspace-mcp](https://github.com/aaronsb/google-workspace-mcp), which we used as the starting point, covered the breadth of Workspace APIs but ran its own browser-callback server during OAuth, which our host application already does. We forked it so that the MCP host can own the entire OAuth flow (the connector returns a structured `auth_required` response instead of running a callback server or computing OAuth URLs), per-account token files are written atomically with restrictive permissions and symlink rejection, and the connector goes through our own security review before each release. Google's [Workspace MCP](https://github.com/googleworkspace/mcp) has since shipped; we continue to maintain this one because it integrates with our host's credential-file layout, host-orchestrated OAuth handoff, and recovery-guidance contract.
21
+ When we ported this in early 2026, Google had not published a first-party MCP server for the Workspace surface. The community options at the time each got parts of the job right — Aaron Brown's [aaronsb/google-workspace-mcp](https://github.com/aaronsb/google-workspace-mcp), which we used as the starting point, covered the breadth of Workspace APIs but ran its own browser-callback server during OAuth, which our host application already does. We forked it so that the MCP host can own the entire OAuth flow (the connector returns a structured `auth_required` response instead of running a callback server or computing OAuth URLs), per-account token files are written atomically with restrictive permissions and symlink rejection, and the connector goes through our own security review before each release. Google's [Workspace MCP](https://github.com/googleworkspace/mcp) has since shipped; we continue to maintain this one because it integrates with our host's credential-file layout, host-orchestrated OAuth handoff, and recovery-guidance contract. This is now a hard fork maintained independently in this repository — we do not sync changes from the upstream project.
22
22
 
23
23
  ## Example interaction
24
24
 
@@ -153,26 +153,45 @@ Until the host has written `${ACCOUNTS_PATH}` and the matching per-account token
153
153
  }
154
154
  ```
155
155
 
156
- ## Tools (94)
156
+ ## Tools (106)
157
157
 
158
158
  The full list lives under [`src/tools/definitions/`](./src/tools/definitions/) and is also surfaced in [`tools-inventory.json`](./tools-inventory.json). Grouped by domain:
159
159
 
160
160
  | Domain | Tools | Notes |
161
161
  | --- | --- | --- |
162
- | Gmail | 21 | Email search/thread/send/compose, drafts, labels, label filters, attachments, archive/trash/read-state helpers. |
162
+ | Gmail | 23 | Email search/thread/send/compose, drafts, labels, label filters, attachments, archive/trash/read-state helpers, settings, vacation responder, and send-as aliases/signatures. |
163
163
  | Calendar | 9 | Current time, free-slot lookup, calendar/event listing, event creation, updates, responses, and deletion. |
164
- | Drive | 13 | List/search/upload/download/copy/move/trash/untrash files, folders, permissions, and revisions. |
164
+ | Drive | 15 | List/search/upload/download/copy/move/trash/untrash files, folders, permissions, revisions, shared-drive discovery, and activity queries (what changed, when, by whom). |
165
165
  | Docs | 8 | Read, create, append, replace, find/replace, tab listing, and batch updates. |
166
166
  | Sheets | 14 | Read/write ranges, create spreadsheets, sheet management, batch operations, find/replace, and formatting. |
167
167
  | Slides | 7 | Read, create, list/get slides, batch update, thumbnails, and ID extraction. |
168
168
  | Labels | 12 | Gmail label CRUD and filter rules. |
169
- | Contacts | 2 | List and search contacts. |
169
+ | Contacts | 4 | List, search, create, and update contacts. |
170
+ | Chat | 3 | List spaces, list messages in a space, and send text messages. |
171
+ | Meet | 3 | List conference records, list transcripts, and read transcript entries (speaker + text). |
170
172
  | Comments | 5 | List/create/reply/resolve/delete Drive comments. |
171
173
  | Account | 3 | List, authenticate, and remove workspace accounts. |
172
174
  | Tasks (gated) | 6 | Registered only when `ENABLE_GOOGLE_TASKS_FORMS=true`. |
173
175
  | Forms (gated) | 4 | Registered only when `ENABLE_GOOGLE_TASKS_FORMS=true`. |
174
176
 
175
- The `## Status` block counts the 94 default-enabled tools; the additional 10 Tasks + Forms tools register when the feature flag is set.
177
+ The `## Status` block counts the 106 default-enabled tools; the additional 10 Tasks + Forms tools register when the feature flag is set.
178
+
179
+ ### Shared drives
180
+
181
+ All Drive file, permission, and comment tools work on shared-drive files (the `files.*` and `permissions.*` calls pass `supportsAllDrives`; the Comments API addresses files by ID and defines no such flag). Listing and search default to the user's own corpus plus files shared with them, so shared-drive content the user has access to but has never opened may not surface by default. To work with shared drives explicitly:
182
+
183
+ - **Discover drives:** `list_shared_drives` returns the shared drives the account can access (id, name, creation time).
184
+ - **Target one drive:** pass `options.driveId` to `list_drive_files` / `search_drive_files`. The connector forces `corpora: 'drive'` whenever `driveId` is set (the Drive API rejects any other pairing), overriding a caller-supplied `corpora`.
185
+ - **Search everything:** pass `options.corpora: 'allDrives'` (no `driveId`) to search across My Drive and all shared drives in one query. Google recommends this only for targeted searches; prefer a specific `driveId` for browsing.
186
+
187
+ Known Drive API limitations for shared-drive files (not fixable in this connector):
188
+
189
+ - Files native to a shared drive have no `owners[]` — ownership belongs to the drive itself. Use `lastModifyingUser` and `createdTime` as proxies when attributing files.
190
+ - The Revisions API does not support shared-drive files, so `list_file_revisions` / `download_file_revision` only work for My Drive files.
191
+
192
+ ### Vacation responder
193
+
194
+ `update_workspace_vacation_responder` merges with the existing settings (the Gmail API otherwise replaces the whole resource): omitted subject/body are kept, an existing HTML body stays HTML, and a pending scheduled end is preserved when `end_time` is omitted. To remove a scheduled end and make the auto-reply open-ended, pass `clear_end_time: true` (mutually exclusive with `end_time`). An already-past end is never carried into a re-enable.
176
195
 
177
196
  ## Security notes
178
197
 
@@ -41,8 +41,20 @@ export class AccountManager {
41
41
  status: renewalResult.status
42
42
  };
43
43
  }
44
+ else if (renewalResult.canRetry) {
45
+ // Transient refresh failure (temporary network error, not a revoked grant):
46
+ // the grant is still good and no reconnect is required. Report valid:true so an
47
+ // agent keying off the boolean doesn't wrongly send the user to reconnect over a
48
+ // blip — this mirrors withTokenRenewal, which proceeds when canRetry is set. The
49
+ // status + reason still carry the transient detail for consumers that look deeper.
50
+ account.auth_status = {
51
+ valid: true,
52
+ status: renewalResult.status,
53
+ reason: renewalResult.reason
54
+ };
55
+ }
44
56
  else {
45
- // If auto-renewal failed, try to get an auth URL for re-authentication
57
+ // Refresh token invalid/revoked (or otherwise non-retryable) — reconnect required.
46
58
  account.auth_status = {
47
59
  valid: false,
48
60
  status: renewalResult.status,
@@ -274,8 +286,14 @@ export class AccountManager {
274
286
  status: tokenStatus.status
275
287
  };
276
288
  break;
277
- case 'INVALID':
278
289
  case 'REFRESH_FAILED':
290
+ // Transient refresh blip (canRetry) keeps the grant valid — no reconnect required,
291
+ // mirroring listAccounts. A non-retryable REFRESH_FAILED still reports as invalid.
292
+ account.auth_status = tokenStatus.canRetry
293
+ ? { valid: true, status: tokenStatus.status, reason: tokenStatus.reason }
294
+ : { valid: false, status: tokenStatus.status, reason: tokenStatus.reason, authUrl: undefined };
295
+ break;
296
+ case 'INVALID':
279
297
  case 'EXPIRED':
280
298
  account.auth_status = {
281
299
  valid: false,
@@ -18,6 +18,19 @@ export declare class TokenManager {
18
18
  private isRefreshDisabled;
19
19
  private authRequiredResult;
20
20
  deleteToken(email: string): Promise<void>;
21
+ /**
22
+ * Refreshes the access token, retrying once on a non-invalid_grant failure.
23
+ *
24
+ * Shared by autoRenewToken and validateToken so the retry + failure-classification
25
+ * logic can't drift between the two paths. On success the refreshed token is persisted
26
+ * (scope + refresh_token preserved, since Google omits them on refresh). The outcome
27
+ * distinguishes a dead grant (invalidGrant: true → reconnect) from a transient blip
28
+ * (invalidGrant: false → retryable), including the case where a transient first attempt
29
+ * is followed by an invalid_grant on retry.
30
+ *
31
+ * Callers must have already established that token.refresh_token and this.oauthClient exist.
32
+ */
33
+ private refreshWithRetry;
21
34
  /**
22
35
  * Basic token validation - just checks if token exists and isn't expired.
23
36
  * No scope validation - auth issues handled via 401 responses.
@@ -83,6 +83,52 @@ export class TokenManager {
83
83
  }
84
84
  }
85
85
  }
86
+ /**
87
+ * Refreshes the access token, retrying once on a non-invalid_grant failure.
88
+ *
89
+ * Shared by autoRenewToken and validateToken so the retry + failure-classification
90
+ * logic can't drift between the two paths. On success the refreshed token is persisted
91
+ * (scope + refresh_token preserved, since Google omits them on refresh). The outcome
92
+ * distinguishes a dead grant (invalidGrant: true → reconnect) from a transient blip
93
+ * (invalidGrant: false → retryable), including the case where a transient first attempt
94
+ * is followed by an invalid_grant on retry.
95
+ *
96
+ * Callers must have already established that token.refresh_token and this.oauthClient exist.
97
+ */
98
+ async refreshWithRetry(email, token) {
99
+ const attemptRefresh = async () => {
100
+ const newToken = await this.oauthClient.refreshToken(token.refresh_token);
101
+ // Preserve original scope and refresh_token - Google doesn't return these on refresh
102
+ newToken.scope = newToken.scope || token.scope;
103
+ newToken.refresh_token = newToken.refresh_token || token.refresh_token;
104
+ await this.saveToken(email, newToken);
105
+ return newToken;
106
+ };
107
+ try {
108
+ return { ok: true, token: await attemptRefresh() };
109
+ }
110
+ catch (error) {
111
+ if (isRefreshTokenInvalidError(error)) {
112
+ logger.error('Refresh token is invalid or revoked');
113
+ return { ok: false, invalidGrant: true };
114
+ }
115
+ // Not a refresh-token problem — a transient blip. Try once more.
116
+ try {
117
+ logger.warn('First refresh attempt failed, trying once more');
118
+ return { ok: true, token: await attemptRefresh() };
119
+ }
120
+ catch (secondError) {
121
+ // Re-classify the retry failure: a transient blip followed by an invalid_grant is
122
+ // still a dead grant, so it must not be mislabelled as retryable.
123
+ if (isRefreshTokenInvalidError(secondError)) {
124
+ logger.error('Refresh token is invalid or revoked (surfaced on retry)');
125
+ return { ok: false, invalidGrant: true };
126
+ }
127
+ logger.error('Both refresh attempts failed, but refresh token may still be valid');
128
+ return { ok: false, invalidGrant: false };
129
+ }
130
+ }
131
+ }
86
132
  /**
87
133
  * Basic token validation - just checks if token exists and isn't expired.
88
134
  * No scope validation - auth issues handled via 401 responses.
@@ -123,52 +169,17 @@ export class TokenManager {
123
169
  reason: 'No refresh token or OAuth client available'
124
170
  };
125
171
  }
126
- try {
127
- // Attempt to refresh the token
128
- const newToken = await this.oauthClient.refreshToken(token.refresh_token);
129
- // Preserve original scope - Google doesn't return scope on refresh
130
- newToken.scope = newToken.scope || token.scope;
131
- // Preserve refresh_token if not returned (Google sometimes omits it)
132
- newToken.refresh_token = newToken.refresh_token || token.refresh_token;
133
- await this.saveToken(email, newToken);
172
+ const outcome = await this.refreshWithRetry(email, token);
173
+ if (outcome.ok) {
134
174
  logger.info('Token refreshed successfully');
135
175
  return {
136
176
  success: true,
137
177
  status: 'REFRESHED',
138
- token: newToken
178
+ token: outcome.token
139
179
  };
140
180
  }
141
- catch (error) {
142
- // Check if the error indicates an invalid/revoked refresh token
143
- const isRefreshTokenInvalid = isRefreshTokenInvalidError(error);
144
- if (!isRefreshTokenInvalid) {
145
- // If it's not a refresh token issue, try one more time
146
- try {
147
- logger.warn('First refresh attempt failed, trying once more');
148
- const newToken = await this.oauthClient.refreshToken(token.refresh_token);
149
- // Preserve original scope and refresh_token
150
- newToken.scope = newToken.scope || token.scope;
151
- newToken.refresh_token = newToken.refresh_token || token.refresh_token;
152
- await this.saveToken(email, newToken);
153
- logger.info('Token refreshed successfully on second attempt');
154
- return {
155
- success: true,
156
- status: 'REFRESHED',
157
- token: newToken
158
- };
159
- }
160
- catch (secondError) {
161
- logger.error('Both refresh attempts failed, but refresh token may still be valid');
162
- return {
163
- success: false,
164
- status: 'REFRESH_FAILED',
165
- reason: 'Token refresh failed, temporary error',
166
- canRetry: true
167
- };
168
- }
169
- }
181
+ if (outcome.invalidGrant) {
170
182
  // Refresh token is invalid, need full reauth
171
- logger.error('Refresh token is invalid or revoked');
172
183
  return {
173
184
  success: false,
174
185
  status: 'AUTH_REQUIRED',
@@ -176,6 +187,12 @@ export class TokenManager {
176
187
  canRetry: false
177
188
  };
178
189
  }
190
+ return {
191
+ success: false,
192
+ status: 'REFRESH_FAILED',
193
+ reason: 'Token refresh failed, temporary error',
194
+ canRetry: true
195
+ };
179
196
  }
180
197
  // Token is still valid
181
198
  return {
@@ -233,35 +250,33 @@ export class TokenManager {
233
250
  };
234
251
  }
235
252
  if (token.refresh_token && this.oauthClient) {
236
- try {
237
- const newToken = await this.oauthClient.refreshToken(token.refresh_token);
238
- // Preserve original scope and refresh_token - Google doesn't return these on refresh
239
- newToken.scope = newToken.scope || token.scope;
240
- newToken.refresh_token = newToken.refresh_token || token.refresh_token;
241
- await this.saveToken(email, newToken);
253
+ // Retry-once + failure classification lives in refreshWithRetry (shared with
254
+ // autoRenewToken). A single transient network blip shouldn't be reported as a
255
+ // dead grant; the canRetry flag lets callers (e.g. BaseGoogleService) surface a
256
+ // retryable error instead of demanding a reconnect.
257
+ const outcome = await this.refreshWithRetry(email, token);
258
+ if (outcome.ok) {
242
259
  logger.info('Token refreshed successfully');
243
260
  return {
244
261
  valid: true,
245
262
  status: 'REFRESHED',
246
- token: newToken,
247
- requiredScopes: newToken.scope ? newToken.scope.split(' ') : undefined
263
+ token: outcome.token,
264
+ requiredScopes: outcome.token.scope ? outcome.token.scope.split(' ') : undefined
248
265
  };
249
266
  }
250
- catch (error) {
251
- logger.error('Token refresh failed', error);
252
- if (isRefreshTokenInvalidError(error)) {
253
- return {
254
- valid: false,
255
- status: 'AUTH_REQUIRED',
256
- reason: 'Refresh token is invalid or revoked'
257
- };
258
- }
267
+ if (outcome.invalidGrant) {
259
268
  return {
260
269
  valid: false,
261
- status: 'REFRESH_FAILED',
262
- reason: 'Token refresh failed'
270
+ status: 'AUTH_REQUIRED',
271
+ reason: 'Refresh token is invalid or revoked'
263
272
  };
264
273
  }
274
+ return {
275
+ valid: false,
276
+ status: 'REFRESH_FAILED',
277
+ reason: 'Token refresh failed, temporary error',
278
+ canRetry: true
279
+ };
265
280
  }
266
281
  logger.debug('No refresh token available');
267
282
  return {
@@ -30,6 +30,7 @@ export interface TokenStatus {
30
30
  reason?: string;
31
31
  authUrl?: string;
32
32
  requiredScopes?: string[];
33
+ canRetry?: boolean;
33
34
  }
34
35
  export interface AuthenticationError extends AccountError {
35
36
  authUrl: string;
@@ -116,6 +116,10 @@ export class CalendarService {
116
116
  const accountManager = getAccountManager();
117
117
  try {
118
118
  const tokenStatus = await accountManager.validateToken(email);
119
+ if (!tokenStatus.valid && tokenStatus.canRetry) {
120
+ // Transient refresh blip, not a dead grant — retryable, not a reconnect demand.
121
+ throw new CalendarError('Calendar sign-in refresh hit a temporary error', 'TEMPORARY_AUTH_ERROR', 'Please try again in a moment');
122
+ }
119
123
  if (!tokenStatus.valid || !tokenStatus.token) {
120
124
  throw new CalendarError('Calendar authentication required', 'AUTH_REQUIRED', 'Please authenticate to access calendar');
121
125
  }
@@ -147,6 +151,11 @@ export class CalendarService {
147
151
  this.oauth2Client.setCredentials(tokenStatus.token);
148
152
  return await operation();
149
153
  }
154
+ if (!tokenStatus.valid && tokenStatus.canRetry) {
155
+ // Transient refresh blip during 401 recovery — retryable, not a reconnect demand.
156
+ // Mirrors withTokenRenewal so the raw 401 doesn't fall through to the reconnect CTA.
157
+ throw new AccountError('Calendar sign-in refresh hit a temporary error', 'TEMPORARY_AUTH_ERROR', 'Please try again in a moment');
158
+ }
150
159
  }
151
160
  const status = error && typeof error === 'object'
152
161
  ? error.code
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Chat module entry point.
3
+ * Exports types, services, and initialization functions for the Google Chat module.
4
+ */
5
+ export * from './types.js';
6
+ export { CHAT_SCOPES, registerChatScopes } from './scopes.js';
7
+ /**
8
+ * Initialize the chat module.
9
+ * This function is called during server startup to set up any required resources.
10
+ */
11
+ export declare function initializeChatModule(): Promise<void>;
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Chat module entry point.
3
+ * Exports types, services, and initialization functions for the Google Chat module.
4
+ */
5
+ // Export types
6
+ export * from './types.js';
7
+ // Export scopes
8
+ export { CHAT_SCOPES, registerChatScopes } from './scopes.js';
9
+ /**
10
+ * Initialize the chat module.
11
+ * This function is called during server startup to set up any required resources.
12
+ */
13
+ export async function initializeChatModule() {
14
+ // Currently no async initialization needed
15
+ // This function is a placeholder for future initialization logic
16
+ return Promise.resolve();
17
+ }
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,14 @@
1
+ export declare const CHAT_SCOPES: {
2
+ SPACES_READONLY: string;
3
+ MESSAGES_READONLY: string;
4
+ MESSAGES_CREATE: string;
5
+ };
6
+ /**
7
+ * Register Google Chat OAuth scopes at startup.
8
+ * Auth issues will be handled via 401 responses rather than pre-validation.
9
+ *
10
+ * Read scopes are registered first, followed by the write scope (order matters
11
+ * for auth URL generation).
12
+ */
13
+ export declare function registerChatScopes(): void;
14
+ //# sourceMappingURL=scopes.d.ts.map
@@ -0,0 +1,32 @@
1
+ import { scopeRegistry } from "../tools/scope-registry.js";
2
+ // Define Google Chat scopes as constants for reuse and testing
3
+ // Reference: https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/list
4
+ // (and the spaces.messages.list / spaces.messages.create method docs)
5
+ export const CHAT_SCOPES = {
6
+ // List spaces the authenticated user belongs to (spaces.list)
7
+ SPACES_READONLY: "https://www.googleapis.com/auth/chat.spaces.readonly",
8
+ // Read messages in a space (spaces.messages.list)
9
+ MESSAGES_READONLY: "https://www.googleapis.com/auth/chat.messages.readonly",
10
+ // Post a message to a space as the authenticated user (spaces.messages.create)
11
+ MESSAGES_CREATE: "https://www.googleapis.com/auth/chat.messages.create"
12
+ };
13
+ /**
14
+ * Register Google Chat OAuth scopes at startup.
15
+ * Auth issues will be handled via 401 responses rather than pre-validation.
16
+ *
17
+ * Read scopes are registered first, followed by the write scope (order matters
18
+ * for auth URL generation).
19
+ */
20
+ export function registerChatScopes() {
21
+ scopeRegistry.registerScope("chat", CHAT_SCOPES.SPACES_READONLY);
22
+ scopeRegistry.registerScope("chat", CHAT_SCOPES.MESSAGES_READONLY);
23
+ scopeRegistry.registerScope("chat", CHAT_SCOPES.MESSAGES_CREATE);
24
+ // Verify all scopes are registered
25
+ const registeredScopes = scopeRegistry.getAllScopes();
26
+ const requiredScopes = Object.values(CHAT_SCOPES);
27
+ const missingScopes = requiredScopes.filter(scope => !registeredScopes.includes(scope));
28
+ if (missingScopes.length > 0) {
29
+ throw new Error(`Failed to register Chat scopes: ${missingScopes.join(', ')}`);
30
+ }
31
+ }
32
+ //# sourceMappingURL=scopes.js.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Parameters for listing Google Chat spaces.
3
+ */
4
+ export interface ListChatSpacesParams {
5
+ email: string;
6
+ pageSize?: number;
7
+ pageToken?: string;
8
+ filter?: string;
9
+ }
10
+ /**
11
+ * Response structure for listing spaces.
12
+ */
13
+ export interface ListChatSpacesResponse {
14
+ spaces: ChatSpace[];
15
+ nextPageToken?: string;
16
+ }
17
+ /**
18
+ * Parameters for listing messages in a space.
19
+ */
20
+ export interface ListChatMessagesParams {
21
+ email: string;
22
+ parent: string;
23
+ pageSize?: number;
24
+ pageToken?: string;
25
+ filter?: string;
26
+ orderBy?: string;
27
+ }
28
+ /**
29
+ * Response structure for listing messages.
30
+ */
31
+ export interface ListChatMessagesResponse {
32
+ messages: ChatMessage[];
33
+ nextPageToken?: string;
34
+ }
35
+ /**
36
+ * Parameters for sending a text message to a space.
37
+ */
38
+ export interface SendChatMessageParams {
39
+ email: string;
40
+ parent: string;
41
+ text: string;
42
+ }
43
+ /**
44
+ * Represents a Google Chat space (DM, group chat, or named space).
45
+ * Based on the Chat API Space resource.
46
+ * Reference: https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces#Space
47
+ */
48
+ export interface ChatSpace {
49
+ name: string;
50
+ displayName?: string;
51
+ spaceType?: string;
52
+ singleUserBotDm?: boolean;
53
+ threaded?: boolean;
54
+ externalUserAllowed?: boolean;
55
+ spaceUri?: string;
56
+ createTime?: string;
57
+ }
58
+ /**
59
+ * Represents a user (sender) on a Chat message.
60
+ */
61
+ export interface ChatUser {
62
+ name?: string;
63
+ displayName?: string;
64
+ type?: string;
65
+ }
66
+ /**
67
+ * Represents a Google Chat message.
68
+ * Based on the Chat API Message resource.
69
+ * Reference: https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages#Message
70
+ */
71
+ export interface ChatMessage {
72
+ name: string;
73
+ text?: string;
74
+ createTime?: string;
75
+ sender?: ChatUser;
76
+ thread?: {
77
+ name?: string;
78
+ };
79
+ }
80
+ /**
81
+ * Base error class for Chat service.
82
+ */
83
+ export declare class ChatError extends Error {
84
+ code: string;
85
+ details?: string;
86
+ constructor(message: string, code: string, details?: string);
87
+ }
88
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Base error class for Chat service.
3
+ */
4
+ export class ChatError extends Error {
5
+ code;
6
+ details;
7
+ constructor(message, code, details) {
8
+ super(message);
9
+ this.name = "ChatError";
10
+ this.code = code;
11
+ this.details = details;
12
+ }
13
+ }
14
+ //# sourceMappingURL=types.js.map
@@ -1,5 +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
4
  import { DRIVE_SCOPES } from '../drive/scopes.js';
4
5
  const DEFAULT_PAGE_SIZE = 20;
5
6
  // Fields parameter for comments.list — Google API requires explicit field selection
@@ -96,9 +97,13 @@ export class CommentsService extends BaseGoogleService {
96
97
  };
97
98
  }
98
99
  catch (error) {
100
+ // An expired/revoked grant must keep its reconnect signal — folding it
101
+ // into a plain error string would skip the host's auth_required handoff.
102
+ if (isAuthHandoffError(error))
103
+ throw error;
99
104
  return {
100
105
  success: false,
101
- error: error instanceof Error ? error.message : 'Unknown error occurred',
106
+ error: describeApiError(error),
102
107
  };
103
108
  }
104
109
  }
@@ -134,9 +139,13 @@ export class CommentsService extends BaseGoogleService {
134
139
  };
135
140
  }
136
141
  catch (error) {
142
+ // An expired/revoked grant must keep its reconnect signal — folding it
143
+ // into a plain error string would skip the host's auth_required handoff.
144
+ if (isAuthHandoffError(error))
145
+ throw error;
137
146
  return {
138
147
  success: false,
139
- error: error instanceof Error ? error.message : 'Unknown error occurred',
148
+ error: describeApiError(error),
140
149
  };
141
150
  }
142
151
  }
@@ -164,9 +173,13 @@ export class CommentsService extends BaseGoogleService {
164
173
  };
165
174
  }
166
175
  catch (error) {
176
+ // An expired/revoked grant must keep its reconnect signal — folding it
177
+ // into a plain error string would skip the host's auth_required handoff.
178
+ if (isAuthHandoffError(error))
179
+ throw error;
167
180
  return {
168
181
  success: false,
169
- error: error instanceof Error ? error.message : 'Unknown error occurred',
182
+ error: describeApiError(error),
170
183
  };
171
184
  }
172
185
  }
@@ -193,9 +206,13 @@ export class CommentsService extends BaseGoogleService {
193
206
  };
194
207
  }
195
208
  catch (error) {
209
+ // An expired/revoked grant must keep its reconnect signal — folding it
210
+ // into a plain error string would skip the host's auth_required handoff.
211
+ if (isAuthHandoffError(error))
212
+ throw error;
196
213
  return {
197
214
  success: false,
198
- error: error instanceof Error ? error.message : 'Unknown error occurred',
215
+ error: describeApiError(error),
199
216
  };
200
217
  }
201
218
  }
@@ -217,9 +234,13 @@ export class CommentsService extends BaseGoogleService {
217
234
  };
218
235
  }
219
236
  catch (error) {
237
+ // An expired/revoked grant must keep its reconnect signal — folding it
238
+ // into a plain error string would skip the host's auth_required handoff.
239
+ if (isAuthHandoffError(error))
240
+ throw error;
220
241
  return {
221
242
  success: false,
222
- error: error instanceof Error ? error.message : 'Unknown error occurred',
243
+ error: describeApiError(error),
223
244
  };
224
245
  }
225
246
  }
@@ -1,4 +1,5 @@
1
1
  export declare const CONTACTS_SCOPES: {
2
2
  READONLY: string;
3
+ CONTACTS: string;
3
4
  };
4
5
  //# sourceMappingURL=scopes.d.ts.map
@@ -3,8 +3,8 @@ import { scopeRegistry } from "../../modules/tools/scope-registry.js";
3
3
  // Reference: https://developers.google.com/people/api/rest/v1/people.connections/list (and other People API docs)
4
4
  export const CONTACTS_SCOPES = {
5
5
  READONLY: "https://www.googleapis.com/auth/contacts.readonly",
6
- // Add other scopes like write/modify later if needed
7
- // CONTACTS: 'https://www.googleapis.com/auth/contacts'
6
+ // Full contacts access (read + write); required for people.createContact / people.updateContact
7
+ CONTACTS: "https://www.googleapis.com/auth/contacts"
8
8
  };
9
9
  // Register the contacts scopes with the scope registry
10
10
  scopeRegistry.registerScope("contacts", CONTACTS_SCOPES.READONLY);