@mindstone/mcp-server-google-workspace 0.1.4 → 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 +448 -22
  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,146 +0,0 @@
1
- import { google } from 'googleapis';
2
- import { BaseGoogleService, GoogleServiceError } from '../base/BaseGoogleService.js';
3
- /**
4
- * Google Calendar Service Implementation extending BaseGoogleService.
5
- * Provides calendar functionality while leveraging common Google API patterns.
6
- */
7
- export class CalendarService extends BaseGoogleService {
8
- constructor(config) {
9
- super({
10
- serviceName: 'calendar',
11
- version: 'v3'
12
- });
13
- }
14
- /**
15
- * Get an authenticated Calendar client
16
- */
17
- async getCalendarClient(email) {
18
- return this.getAuthenticatedClient(email, (auth) => google.calendar({ version: 'v3', auth }));
19
- }
20
- /**
21
- * Retrieve calendar events with optional filtering
22
- */
23
- async getEvents({ email, query, maxResults = 10, timeMin, timeMax }) {
24
- try {
25
- const calendar = await this.getCalendarClient(email);
26
- // Prepare search parameters
27
- const params = {
28
- calendarId: 'primary',
29
- maxResults,
30
- singleEvents: true,
31
- orderBy: 'startTime'
32
- };
33
- if (query) {
34
- params.q = query;
35
- }
36
- if (timeMin) {
37
- params.timeMin = new Date(timeMin).toISOString();
38
- }
39
- if (timeMax) {
40
- params.timeMax = new Date(timeMax).toISOString();
41
- }
42
- // List events matching criteria
43
- const { data } = await calendar.events.list(params);
44
- if (!data.items || data.items.length === 0) {
45
- return [];
46
- }
47
- // Map response to our EventResponse type
48
- return data.items.map(event => ({
49
- id: event.id,
50
- summary: event.summary || '',
51
- description: event.description || undefined,
52
- start: {
53
- dateTime: event.start?.dateTime || event.start?.date || '',
54
- timeZone: event.start?.timeZone || 'UTC'
55
- },
56
- end: {
57
- dateTime: event.end?.dateTime || event.end?.date || '',
58
- timeZone: event.end?.timeZone || 'UTC'
59
- },
60
- attendees: event.attendees?.map(attendee => ({
61
- email: attendee.email,
62
- responseStatus: attendee.responseStatus || undefined
63
- })),
64
- organizer: event.organizer ? {
65
- email: event.organizer.email,
66
- self: event.organizer.self || false
67
- } : undefined
68
- }));
69
- }
70
- catch (error) {
71
- throw this.handleError(error, 'Failed to get events');
72
- }
73
- }
74
- /**
75
- * Retrieve a single calendar event by ID
76
- */
77
- async getEvent(email, eventId) {
78
- try {
79
- const calendar = await this.getCalendarClient(email);
80
- const { data: event } = await calendar.events.get({
81
- calendarId: 'primary',
82
- eventId
83
- });
84
- if (!event) {
85
- throw new GoogleServiceError('Event not found', 'NOT_FOUND', `No event found with ID: ${eventId}`);
86
- }
87
- return {
88
- id: event.id,
89
- summary: event.summary || '',
90
- description: event.description || undefined,
91
- start: {
92
- dateTime: event.start?.dateTime || event.start?.date || '',
93
- timeZone: event.start?.timeZone || 'UTC'
94
- },
95
- end: {
96
- dateTime: event.end?.dateTime || event.end?.date || '',
97
- timeZone: event.end?.timeZone || 'UTC'
98
- },
99
- attendees: event.attendees?.map(attendee => ({
100
- email: attendee.email,
101
- responseStatus: attendee.responseStatus || undefined
102
- })),
103
- organizer: event.organizer ? {
104
- email: event.organizer.email,
105
- self: event.organizer.self || false
106
- } : undefined
107
- };
108
- }
109
- catch (error) {
110
- throw this.handleError(error, 'Failed to get event');
111
- }
112
- }
113
- /**
114
- * Create a new calendar event
115
- */
116
- async createEvent({ email, summary, description, start, end, attendees }) {
117
- try {
118
- const calendar = await this.getCalendarClient(email);
119
- const eventData = {
120
- summary,
121
- description,
122
- start,
123
- end,
124
- attendees: attendees?.map(attendee => ({ email: attendee.email }))
125
- };
126
- const { data: event } = await calendar.events.insert({
127
- calendarId: 'primary',
128
- requestBody: eventData,
129
- sendUpdates: 'all' // Send emails to attendees
130
- });
131
- if (!event.id || !event.summary) {
132
- throw new GoogleServiceError('Failed to create event', 'CREATE_ERROR', 'Event creation response was incomplete');
133
- }
134
- return {
135
- id: event.id,
136
- summary: event.summary,
137
- htmlLink: event.htmlLink || '',
138
- scheduledFor: '' // Legacy service - not actively used
139
- };
140
- }
141
- catch (error) {
142
- throw this.handleError(error, 'Failed to create event');
143
- }
144
- }
145
- }
146
- //# sourceMappingURL=index.js.map
@@ -1,39 +0,0 @@
1
- import { google } from 'googleapis';
2
- import { BaseGoogleService } from '../base/BaseGoogleService.js';
3
- import { GetEmailsParams, SendEmailParams, SendEmailResponse, GetGmailSettingsParams, GetGmailSettingsResponse, GetEmailsResponse } from '../../modules/gmail/types.js';
4
- /**
5
- * Gmail service implementation extending BaseGoogleService.
6
- * Handles Gmail-specific operations while leveraging common Google API functionality.
7
- */
8
- export declare class GmailService extends BaseGoogleService<ReturnType<typeof google.gmail>> {
9
- constructor();
10
- /**
11
- * Gets an authenticated Gmail client
12
- */
13
- private getGmailClient;
14
- /**
15
- * Extracts all headers into a key-value map
16
- */
17
- private extractHeaders;
18
- /**
19
- * Groups emails by thread ID and extracts thread information
20
- */
21
- private groupEmailsByThread;
22
- /**
23
- * Builds a Gmail search query string from SearchCriteria
24
- */
25
- private buildSearchQuery;
26
- /**
27
- * Gets emails with proper scope handling for search and content access.
28
- */
29
- getEmails({ email, search, options, messageIds }: GetEmailsParams): Promise<GetEmailsResponse>;
30
- /**
31
- * Sends an email from the specified account
32
- */
33
- sendEmail({ email, to, subject, body, cc, bcc }: SendEmailParams): Promise<SendEmailResponse>;
34
- /**
35
- * Gets Gmail settings and profile information
36
- */
37
- getWorkspaceGmailSettings({ email }: GetGmailSettingsParams): Promise<GetGmailSettingsResponse>;
38
- }
39
- //# sourceMappingURL=index.d.ts.map
@@ -1,337 +0,0 @@
1
- import { google } from 'googleapis';
2
- import { BaseGoogleService } from '../base/BaseGoogleService.js';
3
- /**
4
- * Gmail service implementation extending BaseGoogleService.
5
- * Handles Gmail-specific operations while leveraging common Google API functionality.
6
- */
7
- export class GmailService extends BaseGoogleService {
8
- constructor() {
9
- super({
10
- serviceName: 'gmail',
11
- version: 'v1'
12
- });
13
- }
14
- /**
15
- * Gets an authenticated Gmail client
16
- */
17
- async getGmailClient(email) {
18
- return this.getAuthenticatedClient(email, (auth) => google.gmail({ version: 'v1', auth }));
19
- }
20
- /**
21
- * Extracts all headers into a key-value map
22
- */
23
- extractHeaders(headers) {
24
- return headers.reduce((acc, header) => {
25
- acc[header.name] = header.value;
26
- return acc;
27
- }, {});
28
- }
29
- /**
30
- * Groups emails by thread ID and extracts thread information
31
- */
32
- groupEmailsByThread(emails) {
33
- return emails.reduce((threads, email) => {
34
- if (!threads[email.threadId]) {
35
- threads[email.threadId] = {
36
- messages: [],
37
- participants: [],
38
- subject: email.subject,
39
- lastUpdated: email.date
40
- };
41
- }
42
- const thread = threads[email.threadId];
43
- thread.messages.push(email.id);
44
- if (!thread.participants.includes(email.from)) {
45
- thread.participants.push(email.from);
46
- }
47
- if (email.to && !thread.participants.includes(email.to)) {
48
- thread.participants.push(email.to);
49
- }
50
- const emailDate = new Date(email.date);
51
- const threadDate = new Date(thread.lastUpdated);
52
- if (emailDate > threadDate) {
53
- thread.lastUpdated = email.date;
54
- }
55
- return threads;
56
- }, {});
57
- }
58
- /**
59
- * Builds a Gmail search query string from SearchCriteria
60
- */
61
- buildSearchQuery(criteria = {}) {
62
- const queryParts = [];
63
- if (criteria.from) {
64
- const fromAddresses = Array.isArray(criteria.from) ? criteria.from : [criteria.from];
65
- if (fromAddresses.length === 1) {
66
- queryParts.push(`from:${fromAddresses[0]}`);
67
- }
68
- else {
69
- queryParts.push(`{${fromAddresses.map(f => `from:${f}`).join(' OR ')}}`);
70
- }
71
- }
72
- if (criteria.to) {
73
- const toAddresses = Array.isArray(criteria.to) ? criteria.to : [criteria.to];
74
- if (toAddresses.length === 1) {
75
- queryParts.push(`to:${toAddresses[0]}`);
76
- }
77
- else {
78
- queryParts.push(`{${toAddresses.map(t => `to:${t}`).join(' OR ')}}`);
79
- }
80
- }
81
- if (criteria.subject) {
82
- const escapedSubject = criteria.subject.replace(/["\\]/g, '\\$&');
83
- queryParts.push(`subject:"${escapedSubject}"`);
84
- }
85
- if (criteria.content) {
86
- const escapedContent = criteria.content.replace(/["\\]/g, '\\$&');
87
- queryParts.push(`"${escapedContent}"`);
88
- }
89
- if (criteria.after) {
90
- const afterDate = new Date(criteria.after);
91
- const afterStr = `${afterDate.getFullYear()}/${(afterDate.getMonth() + 1).toString().padStart(2, '0')}/${afterDate.getDate().toString().padStart(2, '0')}`;
92
- queryParts.push(`after:${afterStr}`);
93
- }
94
- if (criteria.before) {
95
- const beforeDate = new Date(criteria.before);
96
- const beforeStr = `${beforeDate.getFullYear()}/${(beforeDate.getMonth() + 1).toString().padStart(2, '0')}/${beforeDate.getDate().toString().padStart(2, '0')}`;
97
- queryParts.push(`before:${beforeStr}`);
98
- }
99
- if (criteria.hasAttachment) {
100
- queryParts.push('has:attachment');
101
- }
102
- if (criteria.labels && criteria.labels.length > 0) {
103
- criteria.labels.forEach(label => {
104
- queryParts.push(`label:${label}`);
105
- });
106
- }
107
- if (criteria.excludeLabels && criteria.excludeLabels.length > 0) {
108
- criteria.excludeLabels.forEach(label => {
109
- queryParts.push(`-label:${label}`);
110
- });
111
- }
112
- if (criteria.includeSpam) {
113
- queryParts.push('in:anywhere');
114
- }
115
- if (criteria.isUnread !== undefined) {
116
- queryParts.push(criteria.isUnread ? 'is:unread' : 'is:read');
117
- }
118
- return queryParts.join(' ');
119
- }
120
- /**
121
- * Gets emails with proper scope handling for search and content access.
122
- */
123
- async getEmails({ email, search = {}, options = {}, messageIds }) {
124
- try {
125
- const gmail = await this.getGmailClient(email);
126
- const maxResults = options.maxResults || 10;
127
- let messages;
128
- let nextPageToken;
129
- if (messageIds && messageIds.length > 0) {
130
- messages = { messages: messageIds.map(id => ({ id })) };
131
- }
132
- else {
133
- const query = this.buildSearchQuery(search);
134
- const { data } = await gmail.users.messages.list({
135
- userId: 'me',
136
- q: query,
137
- maxResults,
138
- pageToken: options.pageToken,
139
- });
140
- messages = data;
141
- nextPageToken = data.nextPageToken || undefined;
142
- }
143
- if (!messages.messages || messages.messages.length === 0) {
144
- return {
145
- emails: [],
146
- resultSummary: {
147
- total: 0,
148
- returned: 0,
149
- hasMore: false,
150
- searchCriteria: search
151
- }
152
- };
153
- }
154
- const emails = await Promise.all(messages.messages.map(async (message) => {
155
- const { data: email } = await gmail.users.messages.get({
156
- userId: 'me',
157
- id: message.id,
158
- format: options.format || 'full',
159
- });
160
- const headers = (email.payload?.headers || []).map(h => ({
161
- name: h.name || '',
162
- value: h.value || ''
163
- }));
164
- const subject = headers.find(h => h.name === 'Subject')?.value || '';
165
- const from = headers.find(h => h.name === 'From')?.value || '';
166
- const to = headers.find(h => h.name === 'To')?.value || '';
167
- const date = headers.find(h => h.name === 'Date')?.value || '';
168
- let body = '';
169
- if (email.payload?.body?.data) {
170
- body = Buffer.from(email.payload.body.data, 'base64').toString();
171
- }
172
- else if (email.payload?.parts) {
173
- const textPart = email.payload.parts.find(part => part.mimeType === 'text/plain');
174
- if (textPart?.body?.data) {
175
- body = Buffer.from(textPart.body.data, 'base64').toString();
176
- }
177
- }
178
- const response = {
179
- id: email.id,
180
- threadId: email.threadId,
181
- labelIds: email.labelIds || undefined,
182
- snippet: email.snippet || undefined,
183
- subject,
184
- from,
185
- to,
186
- date,
187
- body,
188
- headers: options.includeHeaders ? this.extractHeaders(headers) : undefined,
189
- isUnread: email.labelIds?.includes('UNREAD') || false,
190
- hasAttachment: email.payload?.parts?.some(part => part.filename && part.filename.length > 0) || false
191
- };
192
- return response;
193
- }));
194
- const threads = options.threadedView ? this.groupEmailsByThread(emails) : undefined;
195
- if (options.sortOrder) {
196
- emails.sort((a, b) => {
197
- const dateA = new Date(a.date).getTime();
198
- const dateB = new Date(b.date).getTime();
199
- return options.sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
200
- });
201
- }
202
- return {
203
- emails,
204
- nextPageToken,
205
- resultSummary: {
206
- total: messages.resultSizeEstimate || emails.length,
207
- returned: emails.length,
208
- hasMore: Boolean(nextPageToken),
209
- searchCriteria: search
210
- },
211
- threads
212
- };
213
- }
214
- catch (error) {
215
- throw this.handleError(error, 'Failed to get emails');
216
- }
217
- }
218
- /**
219
- * Sends an email from the specified account
220
- */
221
- async sendEmail({ email, to, subject, body, cc = [], bcc = [] }) {
222
- try {
223
- const gmail = await this.getGmailClient(email);
224
- const message = [
225
- 'Content-Type: text/plain; charset="UTF-8"\n',
226
- 'MIME-Version: 1.0\n',
227
- 'Content-Transfer-Encoding: 7bit\n',
228
- `To: ${to.join(', ')}\n`,
229
- cc.length > 0 ? `Cc: ${cc.join(', ')}\n` : '',
230
- bcc.length > 0 ? `Bcc: ${bcc.join(', ')}\n` : '',
231
- `Subject: ${subject}\n\n`,
232
- body,
233
- ].join('');
234
- const encodedMessage = Buffer.from(message)
235
- .toString('base64')
236
- .replace(/\+/g, '-')
237
- .replace(/\//g, '_')
238
- .replace(/=+$/, '');
239
- const { data } = await gmail.users.messages.send({
240
- userId: 'me',
241
- requestBody: {
242
- raw: encodedMessage,
243
- },
244
- });
245
- return {
246
- messageId: data.id,
247
- threadId: data.threadId,
248
- labelIds: data.labelIds || undefined,
249
- };
250
- }
251
- catch (error) {
252
- throw this.handleError(error, 'Failed to send email');
253
- }
254
- }
255
- /**
256
- * Gets Gmail settings and profile information
257
- */
258
- async getWorkspaceGmailSettings({ email }) {
259
- try {
260
- const gmail = await this.getGmailClient(email);
261
- const { data: profile } = await gmail.users.getProfile({
262
- userId: 'me'
263
- });
264
- const [{ data: autoForwarding }, { data: imap }, { data: language }, { data: pop }, { data: vacation }] = await Promise.all([
265
- gmail.users.settings.getAutoForwarding({ userId: 'me' }),
266
- gmail.users.settings.getImap({ userId: 'me' }),
267
- gmail.users.settings.getLanguage({ userId: 'me' }),
268
- gmail.users.settings.getPop({ userId: 'me' }),
269
- gmail.users.settings.getVacation({ userId: 'me' })
270
- ]);
271
- const nullSafeString = (value) => value === null ? undefined : value;
272
- return {
273
- profile: {
274
- emailAddress: profile.emailAddress ?? '',
275
- messagesTotal: typeof profile.messagesTotal === 'number' ? profile.messagesTotal : 0,
276
- threadsTotal: typeof profile.threadsTotal === 'number' ? profile.threadsTotal : 0,
277
- historyId: profile.historyId ?? ''
278
- },
279
- settings: {
280
- ...(language?.displayLanguage && {
281
- language: {
282
- displayLanguage: language.displayLanguage
283
- }
284
- }),
285
- ...(autoForwarding && {
286
- autoForwarding: {
287
- enabled: Boolean(autoForwarding.enabled),
288
- ...(autoForwarding.emailAddress && {
289
- emailAddress: autoForwarding.emailAddress
290
- })
291
- }
292
- }),
293
- ...(imap && {
294
- imap: {
295
- enabled: Boolean(imap.enabled),
296
- ...(typeof imap.autoExpunge === 'boolean' && {
297
- autoExpunge: imap.autoExpunge
298
- }),
299
- ...(imap.expungeBehavior && {
300
- expungeBehavior: imap.expungeBehavior
301
- })
302
- }
303
- }),
304
- ...(pop && {
305
- pop: {
306
- enabled: Boolean(pop.accessWindow),
307
- ...(pop.accessWindow && {
308
- accessWindow: pop.accessWindow
309
- })
310
- }
311
- }),
312
- ...(vacation && {
313
- vacationResponder: {
314
- enabled: Boolean(vacation.enableAutoReply),
315
- ...(vacation.startTime && {
316
- startTime: vacation.startTime
317
- }),
318
- ...(vacation.endTime && {
319
- endTime: vacation.endTime
320
- }),
321
- ...(vacation.responseSubject && {
322
- responseSubject: vacation.responseSubject
323
- }),
324
- ...((vacation.responseBodyHtml || vacation.responseBodyPlainText) && {
325
- message: vacation.responseBodyHtml ?? vacation.responseBodyPlainText ?? ''
326
- })
327
- }
328
- })
329
- }
330
- };
331
- }
332
- catch (error) {
333
- throw this.handleError(error, 'Failed to get Gmail settings');
334
- }
335
- }
336
- }
337
- //# sourceMappingURL=index.js.map