@mindstone/mcp-server-google-workspace 0.1.5 → 0.2.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 (47) hide show
  1. package/README.md +19 -6
  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/comments/service.js +6 -5
  8. package/dist/modules/docs/index.js +2 -1
  9. package/dist/modules/docs/service.js +8 -7
  10. package/dist/modules/drive/service.d.ts +2 -1
  11. package/dist/modules/drive/service.js +29 -0
  12. package/dist/modules/drive/types.d.ts +8 -0
  13. package/dist/modules/forms/service.js +4 -3
  14. package/dist/modules/gmail/services/attachment.js +2 -1
  15. package/dist/modules/gmail/services/base.js +2 -1
  16. package/dist/modules/gmail/services/draft.js +13 -7
  17. package/dist/modules/gmail/services/email.js +4 -3
  18. package/dist/modules/gmail/services/label.js +10 -9
  19. package/dist/modules/gmail/services/settings.js +2 -1
  20. package/dist/modules/slides/service.js +7 -6
  21. package/dist/modules/tasks/service.js +7 -6
  22. package/dist/resources/compose-email-template.d.ts +1 -1
  23. package/dist/resources/compose-email-template.js +388 -19
  24. package/dist/services/base/BaseGoogleService.js +7 -0
  25. package/dist/tools/calendar-handlers.js +28 -23
  26. package/dist/tools/contacts-handlers.js +8 -23
  27. package/dist/tools/definitions/account.js +8 -1
  28. package/dist/tools/definitions/destructive-overrides.json +1 -0
  29. package/dist/tools/definitions/drive.js +84 -6
  30. package/dist/tools/definitions/open-world-overrides.json +1 -0
  31. package/dist/tools/drive-handlers.d.ts +10 -0
  32. package/dist/tools/drive-handlers.js +44 -1
  33. package/dist/tools/forms-handlers.js +5 -12
  34. package/dist/tools/gmail-handlers.d.ts +7 -1
  35. package/dist/tools/gmail-handlers.js +38 -24
  36. package/dist/tools/server.js +15 -3
  37. package/dist/tools/tasks-handlers.js +7 -18
  38. package/dist/tools/type-guards.d.ts +3 -1
  39. package/dist/tools/type-guards.js +22 -2
  40. package/dist/tools/types.d.ts +13 -0
  41. package/dist/utils/apiError.d.ts +49 -0
  42. package/dist/utils/apiError.js +93 -0
  43. package/package.json +5 -1
  44. package/dist/services/calendar/index.d.ts +0 -27
  45. package/dist/services/calendar/index.js +0 -146
  46. package/dist/services/gmail/index.d.ts +0 -39
  47. package/dist/services/gmail/index.js +0 -337
@@ -1,7 +1,7 @@
1
1
  import { getGmailService } from '../modules/gmail/index.js';
2
2
  import { getAccountManager, validateEmail, resolveEmail } from '../modules/accounts/index.js';
3
3
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
- import { GmailError } from '../modules/gmail/types.js';
4
+ import { toMcpError } from '../utils/apiError.js';
5
5
  import { AttachmentService } from '../modules/attachments/service.js';
6
6
  import { ATTACHMENT_FOLDERS } from '../modules/attachments/types.js';
7
7
  import { lstatSync, readFileSync, realpathSync, statSync } from 'fs';
@@ -221,6 +221,14 @@ function normalizeDraftData(data) {
221
221
  references: data.references,
222
222
  };
223
223
  }
224
+ // Fail loudly on a malformed recipient list — a non-array crashes buildMimeMessage
225
+ // deep in the service and used to surface as an opaque InternalError. Empty arrays are
226
+ // valid for drafts, so only the shape is checked here. Covers to/cc/bcc alike.
227
+ function assertRecipientsArray(value, field) {
228
+ if (value !== undefined && !Array.isArray(value)) {
229
+ throw new McpError(ErrorCode.InvalidParams, `Draft recipients (${field}) must be an array of email addresses`);
230
+ }
231
+ }
224
232
  export async function handleComposeWorkspaceEmail(params) {
225
233
  const to = Array.isArray(params.to)
226
234
  ? params.to.filter((addr) => typeof addr === 'string' && addr.trim().length > 0)
@@ -340,7 +348,7 @@ export async function handleSearchWorkspaceEmails(params) {
340
348
  return formatEmailsAsText(result);
341
349
  }
342
350
  catch (error) {
343
- throw new McpError(ErrorCode.InternalError, `Failed to search emails: ${error instanceof Error ? error.message : 'Unknown error'}`);
351
+ throw toMcpError(error, 'Failed to search emails');
344
352
  }
345
353
  });
346
354
  }
@@ -435,7 +443,7 @@ export async function handleGetWorkspaceEmailThread(params) {
435
443
  return formatThreadAsText(result, offset, includeFullBodies);
436
444
  }
437
445
  catch (error) {
438
- throw new McpError(ErrorCode.InternalError, `Failed to get thread: ${error instanceof Error ? error.message : 'Unknown error'}`);
446
+ throw toMcpError(error, 'Failed to get thread');
439
447
  }
440
448
  });
441
449
  }
@@ -507,15 +515,18 @@ export async function handleSendWorkspaceEmail(params) {
507
515
  references: threading.references,
508
516
  attachments: processOutgoingAttachments(attachments)
509
517
  };
510
- return await gmailService.sendEmail(emailParams);
518
+ const sendResult = await gmailService.sendEmail(emailParams);
519
+ // Return an McpToolResponse-shaped result so the identifiers survive as
520
+ // structuredContent (hoisted by super-mcp) — the compose-email UI reads
521
+ // { messageId, threadId } from it to build an "Open in Gmail" deep link.
522
+ // The text block preserves the same JSON the model saw before this change.
523
+ return {
524
+ content: [{ type: 'text', text: JSON.stringify(sendResult) }],
525
+ structuredContent: sendResult,
526
+ };
511
527
  }
512
528
  catch (error) {
513
- const details = error instanceof GmailError && error.details
514
- ? `${error.message}: ${error.details}`
515
- : error instanceof Error
516
- ? error.message
517
- : 'Unknown error';
518
- throw new McpError(ErrorCode.InternalError, `Failed to send email: ${details}`);
529
+ throw toMcpError(error, 'Failed to send email');
519
530
  }
520
531
  });
521
532
  }
@@ -528,7 +539,7 @@ export async function handleGetWorkspaceGmailSettings(params) {
528
539
  return await gmailService.getWorkspaceGmailSettings({ email });
529
540
  }
530
541
  catch (error) {
531
- throw new McpError(ErrorCode.InternalError, `Failed to get Gmail settings: ${error instanceof Error ? error.message : 'Unknown error'}`);
542
+ throw toMcpError(error, 'Failed to get Gmail settings');
532
543
  }
533
544
  });
534
545
  }
@@ -554,6 +565,9 @@ export async function handleManageWorkspaceDraft(params) {
554
565
  if (!data) {
555
566
  throw new McpError(ErrorCode.InvalidParams, 'Draft data is required for create action');
556
567
  }
568
+ assertRecipientsArray(data.to, 'to');
569
+ assertRecipientsArray(data.cc, 'cc');
570
+ assertRecipientsArray(data.bcc, 'bcc');
557
571
  if (data.to)
558
572
  data.to.forEach(validateEmail);
559
573
  if (data.cc)
@@ -585,6 +599,9 @@ export async function handleManageWorkspaceDraft(params) {
585
599
  if (!draftId || !data) {
586
600
  throw new McpError(ErrorCode.InvalidParams, 'Draft ID and data are required for update action');
587
601
  }
602
+ assertRecipientsArray(data.to, 'to');
603
+ assertRecipientsArray(data.cc, 'cc');
604
+ assertRecipientsArray(data.bcc, 'bcc');
588
605
  if (data.to)
589
606
  data.to.forEach(validateEmail);
590
607
  if (data.cc)
@@ -629,7 +646,7 @@ export async function handleManageWorkspaceDraft(params) {
629
646
  }
630
647
  }
631
648
  catch (error) {
632
- throw new McpError(ErrorCode.InternalError, `Failed to manage draft: ${error instanceof Error ? error.message : 'Unknown error'}`);
649
+ throw toMcpError(error, 'Failed to manage draft');
633
650
  }
634
651
  });
635
652
  }
@@ -660,7 +677,7 @@ export async function handleManageWorkspaceLabel(params) {
660
677
  });
661
678
  }
662
679
  catch (error) {
663
- throw new McpError(ErrorCode.InternalError, `Failed to manage label: ${error instanceof Error ? error.message : 'Unknown error'}`);
680
+ throw toMcpError(error, 'Failed to manage label');
664
681
  }
665
682
  });
666
683
  }
@@ -687,7 +704,7 @@ export async function handleManageWorkspaceLabelAssignment(params) {
687
704
  };
688
705
  }
689
706
  catch (error) {
690
- throw new McpError(ErrorCode.InternalError, `Failed to manage label assignment: ${error instanceof Error ? error.message : 'Unknown error'}`);
707
+ throw toMcpError(error, 'Failed to manage label assignment');
691
708
  }
692
709
  });
693
710
  }
@@ -783,10 +800,7 @@ export async function handleManageWorkspaceAttachment(params) {
783
800
  }
784
801
  }
785
802
  catch (error) {
786
- if (error instanceof McpError) {
787
- throw error;
788
- }
789
- throw new McpError(ErrorCode.InternalError, `Failed to manage attachment: ${error instanceof Error ? error.message : 'Unknown error'}`);
803
+ throw toMcpError(error, 'Failed to manage attachment');
790
804
  }
791
805
  });
792
806
  }
@@ -811,7 +825,7 @@ export async function handleManageWorkspaceLabelFilter(params) {
811
825
  });
812
826
  }
813
827
  catch (error) {
814
- throw new McpError(ErrorCode.InternalError, `Failed to manage label filter: ${error instanceof Error ? error.message : 'Unknown error'}`);
828
+ throw toMcpError(error, 'Failed to manage label filter');
815
829
  }
816
830
  });
817
831
  }
@@ -956,7 +970,7 @@ export async function handleArchiveWorkspaceEmail(params) {
956
970
  : `${ids.length} messages archived successfully.`;
957
971
  }
958
972
  catch (error) {
959
- throw new McpError(ErrorCode.InternalError, `Failed to archive email: ${error instanceof Error ? error.message : 'Unknown error'}`);
973
+ throw toMcpError(error, 'Failed to archive email');
960
974
  }
961
975
  });
962
976
  }
@@ -974,7 +988,7 @@ export async function handleTrashWorkspaceEmail(params) {
974
988
  : `${ids.length} messages moved to trash.`;
975
989
  }
976
990
  catch (error) {
977
- throw new McpError(ErrorCode.InternalError, `Failed to trash email: ${error instanceof Error ? error.message : 'Unknown error'}`);
991
+ throw toMcpError(error, 'Failed to trash email');
978
992
  }
979
993
  });
980
994
  }
@@ -992,7 +1006,7 @@ export async function handleUntrashWorkspaceEmail(params) {
992
1006
  : `${ids.length} messages restored from trash.`;
993
1007
  }
994
1008
  catch (error) {
995
- throw new McpError(ErrorCode.InternalError, `Failed to untrash email: ${error instanceof Error ? error.message : 'Unknown error'}`);
1009
+ throw toMcpError(error, 'Failed to untrash email');
996
1010
  }
997
1011
  });
998
1012
  }
@@ -1015,7 +1029,7 @@ export async function handleMarkWorkspaceEmailRead(params) {
1015
1029
  : `${ids.length} messages marked as read.`;
1016
1030
  }
1017
1031
  catch (error) {
1018
- throw new McpError(ErrorCode.InternalError, `Failed to mark email as read: ${error instanceof Error ? error.message : 'Unknown error'}`);
1032
+ throw toMcpError(error, 'Failed to mark email as read');
1019
1033
  }
1020
1034
  });
1021
1035
  }
@@ -1038,7 +1052,7 @@ export async function handleMarkWorkspaceEmailUnread(params) {
1038
1052
  : `${ids.length} messages marked as unread.`;
1039
1053
  }
1040
1054
  catch (error) {
1041
- throw new McpError(ErrorCode.InternalError, `Failed to mark email as unread: ${error instanceof Error ? error.message : 'Unknown error'}`);
1055
+ throw toMcpError(error, 'Failed to mark email as unread');
1042
1056
  }
1043
1057
  });
1044
1058
  }
@@ -14,7 +14,7 @@ import { ToolRegistry } from '../modules/tools/registry.js';
14
14
  import { handleListWorkspaceAccounts, handleAuthenticateWorkspaceAccount, handleRemoveWorkspaceAccount } from './account-handlers.js';
15
15
  import { handleSearchWorkspaceEmails, handleGetWorkspaceEmailThread, handleComposeWorkspaceEmail, handleSendWorkspaceEmail, handleGetWorkspaceGmailSettings, handleManageWorkspaceDraft, handleManageWorkspaceLabel, handleManageWorkspaceLabelAssignment, handleManageWorkspaceLabelFilter, handleManageWorkspaceAttachment, handleListWorkspaceDrafts, handleGetWorkspaceDraft, handleCreateWorkspaceDraft, handleUpdateWorkspaceDraft, handleDeleteWorkspaceDraft, handleSendWorkspaceDraft, handleDownloadWorkspaceAttachment, handleUploadWorkspaceAttachment, handleDeleteWorkspaceAttachment, handleListWorkspaceLabels, handleGetWorkspaceLabel, handleCreateWorkspaceLabel, handleUpdateWorkspaceLabel, handleDeleteWorkspaceLabel, handleListWorkspaceLabelFilters, handleCreateWorkspaceLabelFilter, handleUpdateWorkspaceLabelFilter, handleDeleteWorkspaceLabelFilter, handleArchiveWorkspaceEmail, handleTrashWorkspaceEmail, handleUntrashWorkspaceEmail, handleMarkWorkspaceEmailRead, handleMarkWorkspaceEmailUnread } from './gmail-handlers.js';
16
16
  import { handleGetCurrentTime, handleFindFreeSlots, handleListWorkspaceCalendars, handleListWorkspaceCalendarEvents, handleGetWorkspaceCalendarEvent, handleManageWorkspaceCalendarEvent, handleCreateWorkspaceCalendarEvent, handleDeleteWorkspaceCalendarEvent } from './calendar-handlers.js';
17
- import { handleListDriveFiles, handleSearchDriveFiles, handleUploadDriveFile, handleDownloadDriveFile, handleCreateDriveFolder, handleUpdateDrivePermissions, handleDeleteDriveFile, handleCopyDriveFile, handleMoveDriveFile, handleTrashDriveFile, handleUntrashDriveFile, handleListFileRevisions, handleDownloadFileRevision } from './drive-handlers.js';
17
+ import { handleListDriveFiles, handleSearchDriveFiles, handleListSharedDrives, handleUploadDriveFile, handleDownloadDriveFile, handleCreateDriveFolder, handleUpdateDrivePermissions, handleDeleteDriveFile, handleCopyDriveFile, handleMoveDriveFile, handleTrashDriveFile, handleUntrashDriveFile, handleListFileRevisions, handleDownloadFileRevision } from './drive-handlers.js';
18
18
  // Import contact handlers
19
19
  import { handleGetContacts, handleSearchContacts } from './contacts-handlers.js';
20
20
  // Import docs handlers
@@ -36,7 +36,7 @@ import { CalendarError } from '../modules/calendar/types.js';
36
36
  import { ContactsError } from '../modules/contacts/types.js';
37
37
  // Import service initializer
38
38
  import { initializeAllServices } from '../utils/service-initializer.js';
39
- import { assertBaseToolArguments, assertListCalendarsArgs, assertCalendarEventParams, assertEmailEventIdArgs, assertSendEmailArgs, assertManageDraftParams, assertManageLabelParams, assertManageLabelAssignmentParams, assertManageLabelFilterParams, assertDriveFileListArgs, assertDriveSearchArgs, assertDriveUploadArgs, assertDriveDownloadArgs, assertDriveFolderArgs, assertDrivePermissionArgs, assertDriveDeleteArgs, assertDriveCopyArgs, assertDriveMoveArgs, assertDriveTrashArgs, assertDriveRevisionsArgs, assertDriveDownloadRevisionArgs, assertManageAttachmentParams, assertGetContactsParams, assertReadDocumentArgs, assertCreateDocumentArgs, assertAppendDocumentArgs, assertReplaceDocumentArgs, assertFindReplaceArgs, assertExtractIdArgs, assertListTabsArgs, assertBatchUpdateDocumentArgs, assertReadPresentationArgs, assertCreatePresentationArgs, assertListSlidesArgs, assertGetSlideArgs, assertExtractPresentationIdArgs, assertReadSpreadsheetArgs, assertReadSpreadsheetValuesArgs, assertCreateSpreadsheetArgs, assertAppendSpreadsheetArgs, assertUpdateSpreadsheetValuesArgs, assertClearSpreadsheetValuesArgs, assertListSpreadsheetSheetsArgs, assertAddSpreadsheetSheetArgs, assertDeleteSpreadsheetSheetArgs, assertExtractSpreadsheetIdArgs, assertBatchGetSpreadsheetValuesArgs, assertBatchUpdateSpreadsheetValuesArgs, assertFindReplaceSpreadsheetArgs, assertFormatSpreadsheetCellsArgs, assertBatchUpdatePresentationArgs, assertGetSlideThumbnailArgs, assertListTaskListsArgs, assertListTasksArgs, assertCreateTaskArgs, assertUpdateTaskArgs, assertCompleteTaskArgs, assertDeleteTaskArgs, assertListFormsArgs, assertGetFormArgs, assertListFormResponsesArgs, assertGetFormResponseArgs, assertListCommentsArgs, assertCreateCommentArgs, assertResolveCommentArgs, assertReplyToCommentArgs, assertDeleteCommentArgs, assertGmailQuickActionArgs } from './type-guards.js';
39
+ import { assertBaseToolArguments, assertListCalendarsArgs, assertCalendarEventParams, assertEmailEventIdArgs, assertSendEmailArgs, assertManageDraftParams, assertManageLabelParams, assertManageLabelAssignmentParams, assertManageLabelFilterParams, assertDriveFileListArgs, assertDriveSearchArgs, assertListSharedDrivesArgs, assertDriveUploadArgs, assertDriveDownloadArgs, assertDriveFolderArgs, assertDrivePermissionArgs, assertDriveDeleteArgs, assertDriveCopyArgs, assertDriveMoveArgs, assertDriveTrashArgs, assertDriveRevisionsArgs, assertDriveDownloadRevisionArgs, assertManageAttachmentParams, assertGetContactsParams, assertReadDocumentArgs, assertCreateDocumentArgs, assertAppendDocumentArgs, assertReplaceDocumentArgs, assertFindReplaceArgs, assertExtractIdArgs, assertListTabsArgs, assertBatchUpdateDocumentArgs, assertReadPresentationArgs, assertCreatePresentationArgs, assertListSlidesArgs, assertGetSlideArgs, assertExtractPresentationIdArgs, assertReadSpreadsheetArgs, assertReadSpreadsheetValuesArgs, assertCreateSpreadsheetArgs, assertAppendSpreadsheetArgs, assertUpdateSpreadsheetValuesArgs, assertClearSpreadsheetValuesArgs, assertListSpreadsheetSheetsArgs, assertAddSpreadsheetSheetArgs, assertDeleteSpreadsheetSheetArgs, assertExtractSpreadsheetIdArgs, assertBatchGetSpreadsheetValuesArgs, assertBatchUpdateSpreadsheetValuesArgs, assertFindReplaceSpreadsheetArgs, assertFormatSpreadsheetCellsArgs, assertBatchUpdatePresentationArgs, assertGetSlideThumbnailArgs, assertListTaskListsArgs, assertListTasksArgs, assertCreateTaskArgs, assertUpdateTaskArgs, assertCompleteTaskArgs, assertDeleteTaskArgs, assertListFormsArgs, assertGetFormArgs, assertListFormResponsesArgs, assertGetFormResponseArgs, assertListCommentsArgs, assertCreateCommentArgs, assertResolveCommentArgs, assertReplyToCommentArgs, assertDeleteCommentArgs, assertGmailQuickActionArgs } from './type-guards.js';
40
40
  import { COMPOSE_EMAIL_HTML } from '../resources/compose-email-template.js';
41
41
  import { normalizeArgs } from './param-normalizer.js';
42
42
  function isInlineUiToolResult(result) {
@@ -358,6 +358,10 @@ export class GSuiteServer {
358
358
  assertDriveSearchArgs(args);
359
359
  result = await handleSearchDriveFiles(args);
360
360
  break;
361
+ case 'list_shared_drives':
362
+ assertListSharedDrivesArgs(args);
363
+ result = await handleListSharedDrives(args);
364
+ break;
361
365
  case 'upload_drive_file':
362
366
  assertDriveUploadArgs(args);
363
367
  result = await handleUploadDriveFile(args);
@@ -648,7 +652,15 @@ export class GSuiteServer {
648
652
  }
649
653
  formatErrorResponse(error) {
650
654
  const message = error instanceof Error ? error.message : 'Unknown error occurred';
651
- const code = error instanceof AccountError ? error.code : undefined;
655
+ // Read the string domain-error `code` from ANY domain error, not just AccountError:
656
+ // CalendarError/GmailError/ContactsError all expose a string `code`, and a
657
+ // `getCalendarClient` auth failure surfaces as `CalendarError('AUTH_REQUIRED')`, not an
658
+ // AccountError. Keying only on `instanceof AccountError` silently dropped those into the
659
+ // generic branch below and skipped the `auth_required` reconnect handoff. McpError's numeric
660
+ // `code` is naturally excluded by the `typeof … === 'string'` guard (its code never matches
661
+ // the string auth codes checked below).
662
+ const rawCode = error?.code;
663
+ const code = typeof rawCode === 'string' ? rawCode : undefined;
652
664
  const status = typeof error === 'object' && error !== null
653
665
  ? error.response?.status
654
666
  ?? error.status
@@ -1,6 +1,7 @@
1
1
  import { getTasksService } from '../modules/tasks/index.js';
2
2
  import { getAccountManager, resolveEmail } from '../modules/accounts/index.js';
3
3
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
4
+ import { toMcpError } from '../utils/apiError.js';
4
5
  import { readAliasedBoolean, readAliasedNumber, readAliasedString } from './arg-aliases.js';
5
6
  import { wrapUntrustedContent } from '../utils/untrusted-content.js';
6
7
  // Singleton instances
@@ -76,9 +77,7 @@ export async function handleListTaskLists(params) {
76
77
  return wrapUntrustedContent(lines.join('\n'), 'google-workspace:tasks:task-lists');
77
78
  }
78
79
  catch (error) {
79
- if (error instanceof McpError)
80
- throw error;
81
- throw new McpError(ErrorCode.InternalError, `Failed to list task lists: ${error instanceof Error ? error.message : 'Unknown error'}`);
80
+ throw toMcpError(error, 'Failed to list task lists');
82
81
  }
83
82
  });
84
83
  }
@@ -112,9 +111,7 @@ export async function handleListTasks(params) {
112
111
  return formatTasksAsText(tasks, taskListId, nextPageToken);
113
112
  }
114
113
  catch (error) {
115
- if (error instanceof McpError)
116
- throw error;
117
- throw new McpError(ErrorCode.InternalError, `Failed to list tasks: ${error instanceof Error ? error.message : 'Unknown error'}`);
114
+ throw toMcpError(error, 'Failed to list tasks');
118
115
  }
119
116
  });
120
117
  }
@@ -148,9 +145,7 @@ export async function handleCreateTask(params) {
148
145
  return wrapUntrustedContent(`Task created successfully!\n\nTitle: ${task.title}${dueInfo}${notesInfo}\nID: ${task.id}\nStatus: ${task.status}`, `google-workspace:tasks:task/${task.id}`);
149
146
  }
150
147
  catch (error) {
151
- if (error instanceof McpError)
152
- throw error;
153
- throw new McpError(ErrorCode.InternalError, `Failed to create task: ${error instanceof Error ? error.message : 'Unknown error'}`);
148
+ throw toMcpError(error, 'Failed to create task');
154
149
  }
155
150
  });
156
151
  }
@@ -191,9 +186,7 @@ export async function handleUpdateTask(params) {
191
186
  return wrapUntrustedContent(`Task updated successfully!\n\nTitle: ${task.title}${dueInfo}${notesInfo}\nID: ${task.id}\nStatus: ${task.status}`, `google-workspace:tasks:task/${task.id}`);
192
187
  }
193
188
  catch (error) {
194
- if (error instanceof McpError)
195
- throw error;
196
- throw new McpError(ErrorCode.InternalError, `Failed to update task: ${error instanceof Error ? error.message : 'Unknown error'}`);
189
+ throw toMcpError(error, 'Failed to update task');
197
190
  }
198
191
  });
199
192
  }
@@ -225,9 +218,7 @@ export async function handleCompleteTask(params) {
225
218
  return wrapUntrustedContent(`Task completed!\n\nTitle: ${task.title}\nID: ${task.id}\nCompleted: ${task.completed || 'Yes'}`, `google-workspace:tasks:task/${task.id}`);
226
219
  }
227
220
  catch (error) {
228
- if (error instanceof McpError)
229
- throw error;
230
- throw new McpError(ErrorCode.InternalError, `Failed to complete task: ${error instanceof Error ? error.message : 'Unknown error'}`);
221
+ throw toMcpError(error, 'Failed to complete task');
231
222
  }
232
223
  });
233
224
  }
@@ -256,9 +247,7 @@ export async function handleDeleteTask(params) {
256
247
  return `Task deleted successfully.\n\nTask ID: ${taskId}\nTask List: ${taskListId}`;
257
248
  }
258
249
  catch (error) {
259
- if (error instanceof McpError)
260
- throw error;
261
- throw new McpError(ErrorCode.InternalError, `Failed to delete task: ${error instanceof Error ? error.message : 'Unknown error'}`);
250
+ throw toMcpError(error, 'Failed to delete task');
262
251
  }
263
252
  });
264
253
  }
@@ -1,4 +1,4 @@
1
- import { BaseToolArguments, ListCalendarsArgs, CalendarEventParams, SendEmailArgs, ManageLabelParams, ManageLabelAssignmentParams, ManageLabelFilterParams, ManageDraftParams, DriveFileListArgs, DriveSearchArgs, DriveUploadArgs, DriveDownloadArgs, DriveFolderArgs, DrivePermissionArgs, DriveDeleteArgs, ManageAttachmentParams } from './types.js';
1
+ import { BaseToolArguments, ListCalendarsArgs, CalendarEventParams, SendEmailArgs, ManageLabelParams, ManageLabelAssignmentParams, ManageLabelFilterParams, ManageDraftParams, DriveFileListArgs, DriveSearchArgs, ListSharedDrivesArgs, DriveUploadArgs, DriveDownloadArgs, DriveFolderArgs, DrivePermissionArgs, DriveDeleteArgs, ManageAttachmentParams } from './types.js';
2
2
  import { GetContactsParams } from '../modules/contacts/types.js';
3
3
  export declare function isBaseToolArguments(args: Record<string, unknown>): args is BaseToolArguments;
4
4
  export declare function assertBaseToolArguments(args: Record<string, unknown>): asserts args is BaseToolArguments;
@@ -21,6 +21,8 @@ export declare function isDriveFileListArgs(args: unknown): args is DriveFileLis
21
21
  export declare function assertDriveFileListArgs(args: unknown): asserts args is DriveFileListArgs;
22
22
  export declare function isDriveSearchArgs(args: unknown): args is DriveSearchArgs;
23
23
  export declare function assertDriveSearchArgs(args: unknown): asserts args is DriveSearchArgs;
24
+ export declare function isListSharedDrivesArgs(args: Record<string, unknown>): args is ListSharedDrivesArgs;
25
+ export declare function assertListSharedDrivesArgs(args: Record<string, unknown>): asserts args is ListSharedDrivesArgs;
24
26
  export declare function isDriveUploadArgs(args: unknown): args is DriveUploadArgs;
25
27
  export declare function assertDriveUploadArgs(args: unknown): asserts args is DriveUploadArgs;
26
28
  export declare function isDriveDownloadArgs(args: unknown): args is DriveDownloadArgs;
@@ -111,6 +111,10 @@ export function assertSendEmailArgs(args) {
111
111
  }
112
112
  }
113
113
  // Drive Type Guards
114
+ const DRIVE_CORPORA_VALUES = ['user', 'drive', 'allDrives'];
115
+ function isValidCorpora(value) {
116
+ return value === undefined || (typeof value === 'string' && DRIVE_CORPORA_VALUES.includes(value));
117
+ }
114
118
  export function isDriveFileListArgs(args) {
115
119
  if (typeof args !== 'object' || args === null)
116
120
  return false;
@@ -122,7 +126,9 @@ export function isDriveFileListArgs(args) {
122
126
  (opts.query === undefined || typeof opts.query === 'string') &&
123
127
  (opts.pageSize === undefined || typeof opts.pageSize === 'number') &&
124
128
  (opts.orderBy === undefined || (Array.isArray(opts.orderBy) && opts.orderBy.every((o) => typeof o === 'string'))) &&
125
- (opts.fields === undefined || (Array.isArray(opts.fields) && opts.fields.every((f) => typeof f === 'string')));
129
+ (opts.fields === undefined || (Array.isArray(opts.fields) && opts.fields.every((f) => typeof f === 'string'))) &&
130
+ (opts.driveId === undefined || typeof opts.driveId === 'string') &&
131
+ isValidCorpora(opts.corpora);
126
132
  })());
127
133
  }
128
134
  export function assertDriveFileListArgs(args) {
@@ -141,13 +147,27 @@ export function isDriveSearchArgs(args) {
141
147
  (params.options.folderId === undefined || typeof params.options.folderId === 'string') &&
142
148
  (params.options.trashed === undefined || typeof params.options.trashed === 'boolean') &&
143
149
  (params.options.query === undefined || typeof params.options.query === 'string') &&
144
- (params.options.pageSize === undefined || typeof params.options.pageSize === 'number');
150
+ (params.options.pageSize === undefined || typeof params.options.pageSize === 'number') &&
151
+ (params.options.driveId === undefined || typeof params.options.driveId === 'string') &&
152
+ isValidCorpora(params.options.corpora);
145
153
  }
146
154
  export function assertDriveSearchArgs(args) {
147
155
  if (!isDriveSearchArgs(args)) {
148
156
  throw new Error('Invalid search parameters. Required: email, options');
149
157
  }
150
158
  }
159
+ export function isListSharedDrivesArgs(args) {
160
+ const pageSize = readAliasedArg(args, 'page_size', 'pageSize');
161
+ const pageToken = readAliasedArg(args, 'page_token', 'pageToken');
162
+ return (args.email === undefined || typeof args.email === 'string') &&
163
+ (pageSize === undefined || typeof pageSize === 'number') &&
164
+ (pageToken === undefined || typeof pageToken === 'string');
165
+ }
166
+ export function assertListSharedDrivesArgs(args) {
167
+ if (!isListSharedDrivesArgs(args)) {
168
+ throw new Error('Invalid list shared drives parameters - page_size must be a number and page_token a string when provided');
169
+ }
170
+ }
151
171
  export function isDriveUploadArgs(args) {
152
172
  if (typeof args !== 'object' || args === null)
153
173
  return false;
@@ -136,6 +136,8 @@ export interface DriveFileListArgs extends BaseToolArguments {
136
136
  pageSize?: number;
137
137
  orderBy?: string[];
138
138
  fields?: string[];
139
+ driveId?: string;
140
+ corpora?: 'user' | 'drive' | 'allDrives';
139
141
  };
140
142
  }
141
143
  /**
@@ -149,8 +151,19 @@ export interface DriveSearchArgs extends BaseToolArguments {
149
151
  trashed?: boolean;
150
152
  query?: string;
151
153
  pageSize?: number;
154
+ driveId?: string;
155
+ corpora?: 'user' | 'drive' | 'allDrives';
152
156
  };
153
157
  }
158
+ /**
159
+ * Parameters for listing shared drives
160
+ */
161
+ export interface ListSharedDrivesArgs extends BaseToolArguments {
162
+ page_size?: number;
163
+ pageSize?: number;
164
+ page_token?: string;
165
+ pageToken?: string;
166
+ }
154
167
  /**
155
168
  * Parameters for uploading files to Drive
156
169
  */
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Extracts the HTTP status from a googleapis (GaxiosError-shaped) failure,
3
+ * preferring `response.status` and falling back to a top-level `status` or a
4
+ * numeric `code`. Returns undefined when no numeric status can be recovered
5
+ * (e.g. a DNS `ENOTFOUND` where `code` is a non-numeric string).
6
+ */
7
+ export declare function extractHttpStatus(error: unknown): number | undefined;
8
+ /**
9
+ * Turns an unknown thrown value into a diagnosable one-line string: the error
10
+ * message plus the HTTP status when one is recoverable. This is what should be
11
+ * stored in a domain error's `details` field so the real Google cause survives
12
+ * to the user instead of collapsing to "Unknown error".
13
+ */
14
+ export declare function describeApiError(error: unknown): string;
15
+ /**
16
+ * Structural check for this connector's domain error classes (GmailError,
17
+ * CalendarError, ContactsError, GoogleServiceError). They all share a
18
+ * `{ message, code, details }` shape with string `code` and string `details`,
19
+ * but have no common base class, so we key on that shape rather than any single
20
+ * `instanceof`. Requiring a string `code` (which every domain error sets when
21
+ * it carries details) guards against a raw transport error (e.g. a GaxiosError
22
+ * with a numeric/string HTTP `code` and some string `details`) being mistaken
23
+ * for a domain error.
24
+ */
25
+ export declare function hasErrorDetails(error: unknown): error is {
26
+ message: string;
27
+ code: string;
28
+ details: string;
29
+ };
30
+ /**
31
+ * True when `error` is a thrown value that signals the account needs
32
+ * (re)authentication — i.e. it exposes a string `code` in {@link AUTH_HANDOFF_CODES}.
33
+ */
34
+ export declare function isAuthHandoffError(error: unknown): boolean;
35
+ /**
36
+ * Normalizes any thrown value into an error suitable for a tool handler's outer
37
+ * catch. An McpError (e.g. an InvalidParams validation failure raised earlier
38
+ * in the handler) is passed through unchanged so its code and message survive.
39
+ * An **auth-handoff domain error** (code `AUTH_REQUIRED` /
40
+ * `HOST_ORCHESTRATED_AUTH_REQUIRED`) is ALSO passed through unchanged: wrapping
41
+ * it into `McpError(InternalError)` would erase the domain `code` that
42
+ * `formatErrorResponse` reads to emit the `auth_required` reconnect handoff,
43
+ * silently degrading an expired-token failure to a generic "Failed to …"
44
+ * message. Any other domain error surfaces its `details`; anything else is
45
+ * described with its HTTP status. Prevents the "Failed to X" opaque-error class
46
+ * where the real cause was silently dropped.
47
+ */
48
+ export declare function toMcpError(error: unknown, fallbackContext: string): Error;
49
+ //# sourceMappingURL=apiError.d.ts.map
@@ -0,0 +1,93 @@
1
+ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
2
+ /**
3
+ * Extracts the HTTP status from a googleapis (GaxiosError-shaped) failure,
4
+ * preferring `response.status` and falling back to a top-level `status` or a
5
+ * numeric `code`. Returns undefined when no numeric status can be recovered
6
+ * (e.g. a DNS `ENOTFOUND` where `code` is a non-numeric string).
7
+ */
8
+ export function extractHttpStatus(error) {
9
+ if (typeof error !== 'object' || error === null)
10
+ return undefined;
11
+ const candidate = error;
12
+ if (typeof candidate.response?.status === 'number')
13
+ return candidate.response.status;
14
+ if (typeof candidate.status === 'number')
15
+ return candidate.status;
16
+ if (typeof candidate.code === 'number')
17
+ return candidate.code;
18
+ if (typeof candidate.code === 'string' && /^\d+$/.test(candidate.code))
19
+ return Number(candidate.code);
20
+ return undefined;
21
+ }
22
+ /**
23
+ * Turns an unknown thrown value into a diagnosable one-line string: the error
24
+ * message plus the HTTP status when one is recoverable. This is what should be
25
+ * stored in a domain error's `details` field so the real Google cause survives
26
+ * to the user instead of collapsing to "Unknown error".
27
+ */
28
+ export function describeApiError(error) {
29
+ const message = error instanceof Error ? error.message : 'Unknown error';
30
+ const status = extractHttpStatus(error);
31
+ return status !== undefined ? `${message} (status ${status})` : message;
32
+ }
33
+ /**
34
+ * Structural check for this connector's domain error classes (GmailError,
35
+ * CalendarError, ContactsError, GoogleServiceError). They all share a
36
+ * `{ message, code, details }` shape with string `code` and string `details`,
37
+ * but have no common base class, so we key on that shape rather than any single
38
+ * `instanceof`. Requiring a string `code` (which every domain error sets when
39
+ * it carries details) guards against a raw transport error (e.g. a GaxiosError
40
+ * with a numeric/string HTTP `code` and some string `details`) being mistaken
41
+ * for a domain error.
42
+ */
43
+ export function hasErrorDetails(error) {
44
+ if (typeof error !== 'object' || error === null)
45
+ return false;
46
+ const candidate = error;
47
+ return (typeof candidate.message === 'string' &&
48
+ typeof candidate.code === 'string' &&
49
+ typeof candidate.details === 'string');
50
+ }
51
+ /**
52
+ * Auth-handoff error codes: a domain error (AccountError / CalendarError / …)
53
+ * carrying one of these codes must NOT be wrapped into a generic McpError —
54
+ * `server.ts` `formatErrorResponse` keys the structured `auth_required`
55
+ * reconnect handoff on the raw domain error's string `code`. Kept as a
56
+ * structural check (no class import) so it works uniformly across every domain
57
+ * error type without coupling this util to the accounts/calendar/gmail modules.
58
+ */
59
+ const AUTH_HANDOFF_CODES = new Set(['AUTH_REQUIRED', 'HOST_ORCHESTRATED_AUTH_REQUIRED']);
60
+ /**
61
+ * True when `error` is a thrown value that signals the account needs
62
+ * (re)authentication — i.e. it exposes a string `code` in {@link AUTH_HANDOFF_CODES}.
63
+ */
64
+ export function isAuthHandoffError(error) {
65
+ if (typeof error !== 'object' || error === null)
66
+ return false;
67
+ const code = error.code;
68
+ return typeof code === 'string' && AUTH_HANDOFF_CODES.has(code);
69
+ }
70
+ /**
71
+ * Normalizes any thrown value into an error suitable for a tool handler's outer
72
+ * catch. An McpError (e.g. an InvalidParams validation failure raised earlier
73
+ * in the handler) is passed through unchanged so its code and message survive.
74
+ * An **auth-handoff domain error** (code `AUTH_REQUIRED` /
75
+ * `HOST_ORCHESTRATED_AUTH_REQUIRED`) is ALSO passed through unchanged: wrapping
76
+ * it into `McpError(InternalError)` would erase the domain `code` that
77
+ * `formatErrorResponse` reads to emit the `auth_required` reconnect handoff,
78
+ * silently degrading an expired-token failure to a generic "Failed to …"
79
+ * message. Any other domain error surfaces its `details`; anything else is
80
+ * described with its HTTP status. Prevents the "Failed to X" opaque-error class
81
+ * where the real cause was silently dropped.
82
+ */
83
+ export function toMcpError(error, fallbackContext) {
84
+ if (error instanceof McpError)
85
+ return error;
86
+ if (isAuthHandoffError(error) && error instanceof Error)
87
+ return error;
88
+ const detail = hasErrorDetails(error) && error.details
89
+ ? `${error.message}: ${error.details}`
90
+ : describeApiError(error);
91
+ return new McpError(ErrorCode.InternalError, `${fallbackContext}: ${detail}`);
92
+ }
93
+ //# sourceMappingURL=apiError.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-google-workspace",
3
- "version": "0.1.5",
3
+ "version": "0.2.0",
4
4
  "mcpName": "io.github.mindstone/mcp-server-google-workspace",
5
5
  "description": "Google Workspace MCP server for Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Tasks, and Forms",
6
6
  "license": "FSL-1.1-MIT",
@@ -30,9 +30,12 @@
30
30
  "prepublishOnly": "npm run build && npm test",
31
31
  "watch": "tsc --watch",
32
32
  "start": "node dist/index.js",
33
+ "pretest": "npm run compose:template:check",
33
34
  "test": "vitest run",
34
35
  "test:watch": "vitest",
35
36
  "test:coverage": "vitest run --coverage",
37
+ "compose:template": "node scripts/gen-compose-html.mjs",
38
+ "compose:template:check": "node scripts/gen-compose-html.mjs --check",
36
39
  "tools:inventory": "node scripts/generate-tools-inventory.mjs",
37
40
  "tools:annotations": "node scripts/check-tool-annotations.mjs",
38
41
  "request:manifest": "node scripts/generate-request-manifest.mjs",
@@ -46,6 +49,7 @@
46
49
  "uuid": "^11.1.0"
47
50
  },
48
51
  "devDependencies": {
52
+ "@mindstone/mcp-app-compose": "file:../../packages/mcp-app-compose",
49
53
  "@types/node": "^22",
50
54
  "@types/uuid": "^10.0.0",
51
55
  "@vitest/coverage-v8": "^4.1.3",
@@ -1,27 +0,0 @@
1
- import { google } from 'googleapis';
2
- import { BaseGoogleService } from '../base/BaseGoogleService.js';
3
- import { GetEventsParams, CreateEventParams, EventResponse, CreateEventResponse, CalendarModuleConfig } from '../../modules/calendar/types.js';
4
- /**
5
- * Google Calendar Service Implementation extending BaseGoogleService.
6
- * Provides calendar functionality while leveraging common Google API patterns.
7
- */
8
- export declare class CalendarService extends BaseGoogleService<ReturnType<typeof google.calendar>> {
9
- constructor(config?: CalendarModuleConfig);
10
- /**
11
- * Get an authenticated Calendar client
12
- */
13
- private getCalendarClient;
14
- /**
15
- * Retrieve calendar events with optional filtering
16
- */
17
- getEvents({ email, query, maxResults, timeMin, timeMax }: GetEventsParams): Promise<EventResponse[]>;
18
- /**
19
- * Retrieve a single calendar event by ID
20
- */
21
- getEvent(email: string, eventId: string): Promise<EventResponse>;
22
- /**
23
- * Create a new calendar event
24
- */
25
- createEvent({ email, summary, description, start, end, attendees }: CreateEventParams): Promise<CreateEventResponse>;
26
- }
27
- //# sourceMappingURL=index.d.ts.map