ms365-mcp-server 1.1.1 → 1.1.3

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.
package/dist/index.js CHANGED
@@ -55,7 +55,7 @@ function parseArgs() {
55
55
  }
56
56
  const server = new Server({
57
57
  name: "ms365-mcp-server",
58
- version: "1.1.1"
58
+ version: "1.1.3"
59
59
  }, {
60
60
  capabilities: {
61
61
  resources: {
@@ -612,11 +612,32 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
612
612
  throw new Error("messageId is required for read action");
613
613
  }
614
614
  const email = await ms365Ops.getEmail(args.messageId, args?.includeAttachments);
615
+ let emailDetailsText = `šŸ“§ Email Details\n\nšŸ“‹ Subject: ${email.subject}\nšŸ‘¤ From: ${email.from.name} <${email.from.address}>\nšŸ“… Date: ${email.receivedDateTime}\n`;
616
+ if (email.attachments && email.attachments.length > 0) {
617
+ emailDetailsText += `\nšŸ“Ž Attachments (${email.attachments.length}):\n`;
618
+ email.attachments.forEach((attachment, index) => {
619
+ const sizeInMB = (attachment.size / (1024 * 1024)).toFixed(2);
620
+ emailDetailsText += `\n${index + 1}. ${attachment.name}\n`;
621
+ emailDetailsText += ` šŸ“¦ Size: ${sizeInMB} MB\n`;
622
+ emailDetailsText += ` šŸ“„ Type: ${attachment.contentType}\n`;
623
+ emailDetailsText += ` šŸ†” ID: ${attachment.id}\n`;
624
+ if (attachment.isInline) {
625
+ emailDetailsText += ` šŸ“Œ Inline: Yes\n`;
626
+ }
627
+ });
628
+ emailDetailsText += `\nšŸ’” To download an attachment, use the get_attachment tool with:\n`;
629
+ emailDetailsText += ` • messageId: ${email.id}\n`;
630
+ emailDetailsText += ` • attachmentId: (use the ID from above)\n`;
631
+ }
632
+ else {
633
+ emailDetailsText += `\nšŸ“Ž No attachments`;
634
+ }
635
+ emailDetailsText += `\n\nšŸ’¬ Body:\n${email.body || email.bodyPreview}`;
615
636
  return {
616
637
  content: [
617
638
  {
618
639
  type: "text",
619
- text: `šŸ“§ Email Details\n\nšŸ“‹ Subject: ${email.subject}\nšŸ‘¤ From: ${email.from.name} <${email.from.address}>\nšŸ“… Date: ${email.receivedDateTime}\nšŸ“Ž Attachments: ${email.attachments?.length || 0}\n\nšŸ’¬ Body:\n${email.body || email.bodyPreview}`
640
+ text: emailDetailsText
620
641
  }
621
642
  ]
622
643
  };
@@ -814,15 +835,44 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
814
835
  const graphClient = await enhancedMS365Auth.getGraphClient();
815
836
  ms365Ops.setGraphClient(graphClient);
816
837
  }
817
- const attachment = await ms365Ops.getAttachment(args?.messageId, args?.attachmentId);
818
- return {
819
- content: [
820
- {
821
- type: "text",
822
- text: `šŸ“Ž Attachment Downloaded\n\nšŸ“ Name: ${attachment.name}\nšŸ’¾ Size: ${attachment.size} bytes\nšŸ—‚ļø Type: ${attachment.contentType}\n\nšŸ“„ Content available in base64 format`
823
- }
824
- ]
825
- };
838
+ if (!args?.messageId || !args?.attachmentId) {
839
+ throw new Error("Both messageId and attachmentId are required");
840
+ }
841
+ try {
842
+ // First verify the email exists and has attachments
843
+ const email = await ms365Ops.getEmail(args.messageId, true);
844
+ if (!email.hasAttachments) {
845
+ throw new Error("This email has no attachments");
846
+ }
847
+ if (!email.attachments || email.attachments.length === 0) {
848
+ throw new Error("No attachment information available for this email");
849
+ }
850
+ // Verify the requested attachment exists
851
+ const attachmentExists = email.attachments.some(att => att.id === args.attachmentId);
852
+ if (!attachmentExists) {
853
+ throw new Error(`Attachment ID ${args.attachmentId} not found in this email. Available attachments:\n${email.attachments.map(att => `- ${att.name} (ID: ${att.id})`).join('\n')}`);
854
+ }
855
+ // Now get the attachment
856
+ const attachment = await ms365Ops.getAttachment(args.messageId, args.attachmentId);
857
+ return {
858
+ content: [
859
+ {
860
+ type: "text",
861
+ text: `šŸ“Ž Attachment Downloaded\n\nšŸ“ Name: ${attachment.name}\nšŸ’¾ Size: ${attachment.size} bytes\nšŸ—‚ļø Type: ${attachment.contentType}\n\nBelow is the base64-encoded content. You can save this to a file using a script or tool that decodes base64.\n\n---BASE64 START---\n${attachment.contentBytes}\n---BASE64 END---`
862
+ }
863
+ ],
864
+ base64Content: attachment.contentBytes,
865
+ filename: attachment.name,
866
+ contentType: attachment.contentType,
867
+ size: attachment.size
868
+ };
869
+ }
870
+ catch (error) {
871
+ if (error.message.includes("not found in the store")) {
872
+ throw new Error(`Email or attachment not found. Please verify:\n1. The email ID is correct\n2. The attachment ID is correct\n3. You have permission to access this email/attachment`);
873
+ }
874
+ throw error;
875
+ }
826
876
  case "list_folders":
827
877
  if (ms365Config.multiUser) {
828
878
  const userId = args?.userId;
@@ -24,6 +24,7 @@ const DEFAULT_TENANT_ID = "common";
24
24
  const CONFIG_DIR = path.join(os.homedir(), '.ms365-mcp');
25
25
  const CREDENTIALS_FILE = path.join(CONFIG_DIR, 'credentials.json');
26
26
  const DEVICE_CODE_FILE = path.join(CONFIG_DIR, 'device-code.json');
27
+ const TOKEN_CACHE_FILE = path.join(CONFIG_DIR, 'msal-cache.json');
27
28
  /**
28
29
  * Enhanced Microsoft 365 authentication manager with device code flow support
29
30
  */
@@ -97,13 +98,42 @@ export class EnhancedMS365Auth {
97
98
  }
98
99
  }
99
100
  /**
100
- * Initialize MSAL client based on auth type
101
+ * Initialize MSAL client based on auth type with persistent token cache
101
102
  */
102
103
  initializeMsalClient() {
103
104
  if (!this.credentials) {
104
105
  throw new Error('Credentials not loaded');
105
106
  }
107
+ // Return existing client if already initialized with same credentials
108
+ if (this.msalClient) {
109
+ return this.msalClient;
110
+ }
106
111
  const isConfidential = this.credentials.clientSecret && this.credentials.authType === 'redirect';
112
+ // Create persistent token cache
113
+ const cachePlugin = {
114
+ beforeCacheAccess: async (cacheContext) => {
115
+ try {
116
+ if (fs.existsSync(TOKEN_CACHE_FILE)) {
117
+ const cacheData = fs.readFileSync(TOKEN_CACHE_FILE, 'utf8');
118
+ cacheContext.tokenCache.deserialize(cacheData);
119
+ }
120
+ }
121
+ catch (error) {
122
+ logger.error('Error loading MSAL token cache:', error);
123
+ }
124
+ },
125
+ afterCacheAccess: async (cacheContext) => {
126
+ try {
127
+ if (cacheContext.cacheHasChanged) {
128
+ const cacheData = cacheContext.tokenCache.serialize();
129
+ fs.writeFileSync(TOKEN_CACHE_FILE, cacheData);
130
+ }
131
+ }
132
+ catch (error) {
133
+ logger.error('Error saving MSAL token cache:', error);
134
+ }
135
+ }
136
+ };
107
137
  if (isConfidential) {
108
138
  // Confidential client for redirect-based auth
109
139
  const config = {
@@ -112,6 +142,9 @@ export class EnhancedMS365Auth {
112
142
  clientSecret: this.credentials.clientSecret,
113
143
  authority: `https://login.microsoftonline.com/${this.credentials.tenantId}`
114
144
  },
145
+ cache: {
146
+ cachePlugin
147
+ },
115
148
  system: {
116
149
  loggerOptions: {
117
150
  loggerCallback: (level, message, containsPii) => {
@@ -133,6 +166,9 @@ export class EnhancedMS365Auth {
133
166
  clientId: this.credentials.clientId,
134
167
  authority: `https://login.microsoftonline.com/${this.credentials.tenantId}`
135
168
  },
169
+ cache: {
170
+ cachePlugin
171
+ },
136
172
  system: {
137
173
  loggerOptions: {
138
174
  loggerCallback: (level, message, containsPii) => {
@@ -147,6 +183,7 @@ export class EnhancedMS365Auth {
147
183
  };
148
184
  this.msalClient = new PublicClientApplication(config);
149
185
  }
186
+ logger.log('Initialized MSAL client with persistent token cache');
150
187
  return this.msalClient;
151
188
  }
152
189
  /**
@@ -266,14 +303,14 @@ export class EnhancedMS365Auth {
266
303
  try {
267
304
  const tokenData = {
268
305
  accessToken: token.accessToken,
269
- refreshToken: '',
306
+ refreshToken: '', // MSAL manages refresh tokens internally
270
307
  expiresOn: token.expiresOn?.getTime() || 0,
271
308
  account: token.account,
272
309
  authType: authType
273
310
  };
274
311
  // Always use a single account key for simplicity
275
312
  await credentialStore.setCredentials('ms365-user', tokenData);
276
- logger.log('Saved MS365 access token securely');
313
+ logger.log(`Saved MS365 access token securely (expires: ${new Date(tokenData.expiresOn).toLocaleString()})`);
277
314
  }
278
315
  catch (error) {
279
316
  logger.error('Error saving token:', error);
@@ -331,13 +368,19 @@ export class EnhancedMS365Auth {
331
368
  * Get authenticated Microsoft Graph client
332
369
  */
333
370
  async getGraphClient() {
334
- const storedToken = await this.loadStoredToken();
371
+ let storedToken = await this.loadStoredToken();
335
372
  if (!storedToken) {
336
373
  throw new Error('No stored token found. Please authenticate first.');
337
374
  }
338
375
  // Check if token is expired
339
376
  if (storedToken.expiresOn < Date.now()) {
377
+ logger.log('Access token expired, refreshing...');
340
378
  await this.refreshToken();
379
+ // Reload the token after refresh
380
+ storedToken = await this.loadStoredToken();
381
+ if (!storedToken) {
382
+ throw new Error('Failed to refresh token. Please re-authenticate.');
383
+ }
341
384
  }
342
385
  const client = Client.init({
343
386
  authProvider: (done) => {
@@ -399,9 +442,23 @@ export class EnhancedMS365Auth {
399
442
  }
400
443
  const msalClient = this.initializeMsalClient();
401
444
  try {
445
+ // Try to get all accounts from MSAL cache first (only available on PublicClientApplication)
446
+ let accountToUse = storedToken.account;
447
+ if (msalClient instanceof PublicClientApplication) {
448
+ const accounts = await msalClient.getAllAccounts();
449
+ // If we have accounts in MSAL cache, use the first one that matches
450
+ if (accounts.length > 0) {
451
+ const matchingAccount = accounts.find((acc) => acc.username === storedToken.account?.username ||
452
+ acc.homeAccountId === storedToken.account?.homeAccountId);
453
+ if (matchingAccount) {
454
+ accountToUse = matchingAccount;
455
+ logger.log('Using account from MSAL cache for token refresh');
456
+ }
457
+ }
458
+ }
402
459
  const tokenResponse = await msalClient.acquireTokenSilent({
403
460
  scopes: SCOPES,
404
- account: storedToken.account
461
+ account: accountToUse
405
462
  });
406
463
  if (!tokenResponse) {
407
464
  throw new Error('Failed to refresh token - please re-authenticate using: authenticate_with_device_code');
@@ -417,6 +474,9 @@ export class EnhancedMS365Auth {
417
474
  else if (error.errorCode === 'consent_required') {
418
475
  throw new Error('Additional consent required. Please re-authenticate using the "authenticate_with_device_code" tool.');
419
476
  }
477
+ else if (error.errorCode === 'no_account_in_silent_request') {
478
+ throw new Error('No account found in token cache. Please re-authenticate using the "authenticate_with_device_code" tool.');
479
+ }
420
480
  else {
421
481
  logger.error('Token refresh failed:', error);
422
482
  throw new Error(`Token refresh failed: ${error.message}. Please re-authenticate using the "authenticate_with_device_code" tool.`);
@@ -457,6 +517,13 @@ export class EnhancedMS365Auth {
457
517
  try {
458
518
  await credentialStore.deleteCredentials('ms365-user');
459
519
  await this.clearDeviceCodeState();
520
+ // Clear MSAL token cache
521
+ if (fs.existsSync(TOKEN_CACHE_FILE)) {
522
+ fs.unlinkSync(TOKEN_CACHE_FILE);
523
+ logger.log('Cleared MSAL token cache');
524
+ }
525
+ // Reset MSAL client instance to force re-initialization
526
+ this.msalClient = null;
460
527
  logger.log('Cleared stored authentication tokens');
461
528
  }
462
529
  catch (error) {
@@ -318,14 +318,16 @@ export class MS365Operations {
318
318
  async getEmail(messageId, includeAttachments = false) {
319
319
  try {
320
320
  const graphClient = await this.getGraphClient();
321
- let selectFields = 'id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink';
322
- if (includeAttachments) {
323
- selectFields += ',body';
324
- }
321
+ logger.log('Fetching email details...');
322
+ // First get the basic email info with attachments expanded
325
323
  const email = await graphClient
326
324
  .api(`/me/messages/${messageId}`)
327
- .select(selectFields)
325
+ .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink,body,attachments')
326
+ .expand('attachments')
328
327
  .get();
328
+ logger.log(`Email details retrieved. hasAttachments flag: ${email.hasAttachments}`);
329
+ logger.log(`Email subject: ${email.subject}`);
330
+ logger.log(`Direct attachments count: ${email.attachments?.length || 0}`);
329
331
  const emailInfo = {
330
332
  id: email.id,
331
333
  subject: email.subject || '',
@@ -349,22 +351,75 @@ export class MS365Operations {
349
351
  importance: email.importance || 'normal',
350
352
  conversationId: email.conversationId || '',
351
353
  parentFolderId: email.parentFolderId || '',
352
- webLink: email.webLink || ''
354
+ webLink: email.webLink || '',
355
+ attachments: email.attachments?.map((attachment) => ({
356
+ id: attachment.id,
357
+ name: attachment.name,
358
+ contentType: attachment.contentType,
359
+ size: attachment.size,
360
+ isInline: attachment.isInline,
361
+ contentId: attachment.contentId
362
+ })) || []
353
363
  };
354
- if (includeAttachments && email.body) {
364
+ if (email.body) {
355
365
  emailInfo.body = email.body.content || '';
356
366
  }
357
- // Get attachments if requested
358
- if (includeAttachments && email.hasAttachments) {
359
- const attachments = await graphClient
360
- .api(`/me/messages/${messageId}/attachments`)
361
- .get();
362
- emailInfo.attachments = attachments.value || [];
367
+ // Always try to get attachments if requested
368
+ if (includeAttachments) {
369
+ logger.log('Attempting to fetch attachments...');
370
+ try {
371
+ // First check if we got attachments from the expanded query
372
+ if (email.attachments && email.attachments.length > 0) {
373
+ logger.log(`Found ${email.attachments.length} attachments from expanded query`);
374
+ emailInfo.attachments = email.attachments.map((attachment) => ({
375
+ id: attachment.id,
376
+ name: attachment.name,
377
+ contentType: attachment.contentType,
378
+ size: attachment.size,
379
+ isInline: attachment.isInline,
380
+ contentId: attachment.contentId
381
+ }));
382
+ emailInfo.hasAttachments = true;
383
+ }
384
+ else {
385
+ // Try getting attachments directly
386
+ logger.log('Method 1: Direct attachment query...');
387
+ const attachments = await graphClient
388
+ .api(`/me/messages/${messageId}/attachments`)
389
+ .select('id,name,contentType,size,isInline,contentId')
390
+ .get();
391
+ logger.log(`Method 1 results: Found ${attachments.value?.length || 0} attachments`);
392
+ if (attachments && attachments.value && attachments.value.length > 0) {
393
+ emailInfo.attachments = attachments.value.map((attachment) => ({
394
+ id: attachment.id,
395
+ name: attachment.name,
396
+ contentType: attachment.contentType,
397
+ size: attachment.size,
398
+ isInline: attachment.isInline,
399
+ contentId: attachment.contentId
400
+ }));
401
+ emailInfo.hasAttachments = true;
402
+ logger.log(`Successfully retrieved ${emailInfo.attachments.length} attachments`);
403
+ }
404
+ else {
405
+ logger.log('No attachments found with either method');
406
+ emailInfo.attachments = [];
407
+ emailInfo.hasAttachments = false;
408
+ }
409
+ }
410
+ }
411
+ catch (attachmentError) {
412
+ logger.error('Error getting attachments:', attachmentError);
413
+ logger.error('Error details:', JSON.stringify(attachmentError, null, 2));
414
+ emailInfo.attachments = [];
415
+ emailInfo.hasAttachments = false;
416
+ }
363
417
  }
364
418
  return emailInfo;
365
419
  }
366
420
  catch (error) {
367
421
  logger.error('Error getting email:', error);
422
+ logger.error('Error details:', JSON.stringify(error, null, 2));
368
423
  throw error;
369
424
  }
370
425
  }
@@ -380,111 +435,13 @@ export class MS365Operations {
380
435
  if (cachedResults) {
381
436
  return cachedResults;
382
437
  }
383
- // For name-based searches, use enhanced approach for better partial matching
384
- if (criteria.from && !criteria.from.includes('@')) {
385
- logger.log(`Using enhanced name matching for: "${criteria.from}"`);
386
- // Get more emails and filter manually for better name matching
387
- const maxResults = criteria.maxResults || 100;
388
- try {
389
- // Optimized field selection for name search - only get essential fields first
390
- const essentialFields = 'id,subject,from,receivedDateTime,isRead,hasAttachments,importance';
391
- const apiCall = graphClient.api('/me/messages')
392
- .select(essentialFields)
393
- .orderby('receivedDateTime desc')
394
- .top(Math.min(maxResults * 3, 300)); // Get more emails for better filtering
395
- const result = await apiCall.get();
396
- // First pass: filter by name using minimal data
397
- const nameMatches = result.value?.filter((email) => {
398
- const fromName = email.from?.emailAddress?.name?.toLowerCase() || '';
399
- const fromAddress = email.from?.emailAddress?.address?.toLowerCase() || '';
400
- const searchTerm = criteria.from.toLowerCase().trim();
401
- // Quick name matching (subset of the full logic for performance)
402
- return fromName.includes(searchTerm) ||
403
- fromAddress.includes(searchTerm) ||
404
- fromName.split(/\s+/).some((part) => part.startsWith(searchTerm)) ||
405
- searchTerm.split(/\s+/).every((part) => fromName.includes(part));
406
- }) || [];
407
- if (nameMatches.length === 0) {
408
- const emptyResult = { messages: [], hasMore: false };
409
- this.setCachedResults(cacheKey, emptyResult);
410
- return emptyResult;
411
- }
412
- // Second pass: get full details for matched emails
413
- const messageIds = nameMatches.slice(0, maxResults).map((email) => email.id);
414
- const fullMessages = await this.getEmailsByIds(messageIds);
415
- // Apply remaining criteria filtering
416
- let messages = this.applyManualFiltering(fullMessages, criteria);
417
- // Apply maxResults limit
418
- const limitedMessages = messages.slice(0, maxResults);
419
- logger.log(`Enhanced name search found ${limitedMessages.length} emails matching "${criteria.from}"`);
420
- const result_final = {
421
- messages: limitedMessages,
422
- hasMore: messages.length > maxResults || nameMatches.length > maxResults
423
- };
424
- this.setCachedResults(cacheKey, result_final);
425
- return result_final;
426
- }
427
- catch (error) {
428
- logger.error('Error in enhanced name search, falling back to standard search:', error);
429
- // Fall through to standard search logic
430
- }
431
- }
432
- // Standard search logic (for email addresses and other criteria)
433
- const searchQuery = this.buildSearchQuery(criteria);
434
- const filterQuery = this.buildFilterQuery(criteria);
435
- // Debug logging
436
- if (searchQuery) {
437
- logger.log(`Search query: ${searchQuery}`);
438
- }
439
- if (filterQuery) {
440
- logger.log(`Filter query: ${filterQuery}`);
441
- }
442
- let apiCall;
443
- let useSearchAPI = !!searchQuery;
438
+ // For complex searches, use a simpler approach
444
439
  try {
445
- // Microsoft Graph doesn't support $orderBy with $search, so we need to choose one approach
446
- if (searchQuery) {
447
- // Use search API when we have search terms (no orderby allowed)
448
- // Add ConsistencyLevel header for search queries
449
- apiCall = graphClient.api('/me/messages')
450
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
451
- .header('ConsistencyLevel', 'eventual')
452
- .search(searchQuery)
453
- .top(criteria.maxResults || 50);
454
- // Can't use filter with search, so we'll need to filter results manually if needed
455
- }
456
- else {
457
- // Use filter API when we don't have search terms (orderby allowed)
458
- apiCall = graphClient.api('/me/messages')
459
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
460
- .orderby('receivedDateTime desc')
461
- .top(criteria.maxResults || 50);
462
- if (filterQuery) {
463
- apiCall = apiCall.filter(filterQuery);
464
- }
465
- }
466
- // Handle folder-specific searches
467
- if (criteria.folder && criteria.folder !== 'inbox') {
468
- if (searchQuery) {
469
- // For folder + search, we need to use a different approach
470
- apiCall = graphClient.api(`/me/mailFolders/${criteria.folder}/messages`)
471
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
472
- .top(criteria.maxResults || 50);
473
- if (filterQuery) {
474
- apiCall = apiCall.filter(filterQuery);
475
- }
476
- // Note: Folder-specific search is limited, we'll do text filtering on results
477
- }
478
- else {
479
- apiCall = graphClient.api(`/me/mailFolders/${criteria.folder}/messages`)
480
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
481
- .orderby('receivedDateTime desc')
482
- .top(criteria.maxResults || 50);
483
- if (filterQuery) {
484
- apiCall = apiCall.filter(filterQuery);
485
- }
486
- }
487
- }
440
+ // Start with a basic query to get recent emails
441
+ const apiCall = graphClient.api('/me/messages')
442
+ .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
443
+ .orderby('receivedDateTime desc')
444
+ .top(criteria.maxResults || 100);
488
445
  const result = await apiCall.get();
489
446
  let messages = result.value?.map((email) => ({
490
447
  id: email.id,
@@ -511,79 +468,34 @@ export class MS365Operations {
511
468
  parentFolderId: email.parentFolderId || '',
512
469
  webLink: email.webLink || ''
513
470
  })) || [];
514
- // Apply manual filtering when using search (since we can't use $filter with $search)
515
- if (useSearchAPI && (criteria.folder || filterQuery)) {
516
- messages = this.applyManualFiltering(messages, criteria);
471
+ // Apply manual filtering for all criteria
472
+ messages = this.applyManualFiltering(messages, criteria);
473
+ // For emails with attachments, get attachment counts
474
+ for (const message of messages) {
475
+ if (message.hasAttachments) {
476
+ try {
477
+ const attachments = await graphClient
478
+ .api(`/me/messages/${message.id}/attachments`)
479
+ .select('id')
480
+ .get();
481
+ message.attachments = new Array(attachments.value?.length || 0);
482
+ }
483
+ catch (error) {
484
+ logger.error(`Error getting attachment count for message ${message.id}:`, error);
485
+ message.attachments = [];
486
+ }
487
+ }
517
488
  }
518
- const standardResult = {
489
+ const searchResult = {
519
490
  messages,
520
491
  hasMore: !!result['@odata.nextLink']
521
492
  };
522
- this.setCachedResults(cacheKey, standardResult);
523
- return standardResult;
493
+ this.setCachedResults(cacheKey, searchResult);
494
+ return searchResult;
524
495
  }
525
- catch (searchError) {
526
- // If search API fails due to syntax error, fall back to filter-only approach
527
- if (searchError.message && searchError.message.includes('Syntax error')) {
528
- logger.log('Search API failed with syntax error, falling back to filter-only query');
529
- // Fallback: Use only filter-based query without search
530
- apiCall = graphClient.api('/me/messages')
531
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
532
- .orderby('receivedDateTime desc')
533
- .top(criteria.maxResults || 50);
534
- if (filterQuery) {
535
- apiCall = apiCall.filter(filterQuery);
536
- }
537
- // Handle folder-specific queries
538
- if (criteria.folder && criteria.folder !== 'inbox') {
539
- apiCall = graphClient.api(`/me/mailFolders/${criteria.folder}/messages`)
540
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
541
- .orderby('receivedDateTime desc')
542
- .top(criteria.maxResults || 50);
543
- if (filterQuery) {
544
- apiCall = apiCall.filter(filterQuery);
545
- }
546
- }
547
- const result = await apiCall.get();
548
- let messages = result.value?.map((email) => ({
549
- id: email.id,
550
- subject: email.subject || '',
551
- from: {
552
- name: email.from?.emailAddress?.name || '',
553
- address: email.from?.emailAddress?.address || ''
554
- },
555
- toRecipients: email.toRecipients?.map((recipient) => ({
556
- name: recipient.emailAddress?.name || '',
557
- address: recipient.emailAddress?.address || ''
558
- })) || [],
559
- ccRecipients: email.ccRecipients?.map((recipient) => ({
560
- name: recipient.emailAddress?.name || '',
561
- address: recipient.emailAddress?.address || ''
562
- })) || [],
563
- receivedDateTime: email.receivedDateTime,
564
- sentDateTime: email.sentDateTime,
565
- bodyPreview: email.bodyPreview || '',
566
- isRead: email.isRead || false,
567
- hasAttachments: email.hasAttachments || false,
568
- importance: email.importance || 'normal',
569
- conversationId: email.conversationId || '',
570
- parentFolderId: email.parentFolderId || '',
571
- webLink: email.webLink || ''
572
- })) || [];
573
- // Apply manual filtering for any criteria that couldn't be handled by the filter
574
- // This includes subject, to, cc, and query filters that need manual processing
575
- messages = this.applyManualFiltering(messages, criteria);
576
- const fallbackResult = {
577
- messages,
578
- hasMore: !!result['@odata.nextLink']
579
- };
580
- this.setCachedResults(cacheKey, fallbackResult);
581
- return fallbackResult;
582
- }
583
- else {
584
- // Re-throw other errors
585
- throw searchError;
586
- }
496
+ catch (error) {
497
+ logger.error('Error in email search:', error);
498
+ throw error;
587
499
  }
588
500
  }, 'searchEmails');
589
501
  }
@@ -935,53 +847,55 @@ export class MS365Operations {
935
847
  * Get multiple emails by their IDs efficiently
936
848
  */
937
849
  async getEmailsByIds(messageIds) {
938
- try {
939
- const graphClient = await this.getGraphClient();
940
- // Batch request for better performance when getting multiple emails
941
- const emails = [];
942
- // Process in batches of 20 to stay within Graph API limits
943
- const batchSize = 20;
944
- for (let i = 0; i < messageIds.length; i += batchSize) {
945
- const batch = messageIds.slice(i, i + batchSize);
946
- // Get full details for this batch
947
- const promises = batch.map(id => graphClient
948
- .api(`/me/messages/${id}`)
949
- .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
950
- .get());
951
- const results = await Promise.all(promises);
952
- const batchEmails = results.map((email) => ({
953
- id: email.id,
954
- subject: email.subject || '',
955
- from: {
956
- name: email.from?.emailAddress?.name || '',
957
- address: email.from?.emailAddress?.address || ''
958
- },
959
- toRecipients: email.toRecipients?.map((recipient) => ({
960
- name: recipient.emailAddress?.name || '',
961
- address: recipient.emailAddress?.address || ''
962
- })) || [],
963
- ccRecipients: email.ccRecipients?.map((recipient) => ({
964
- name: recipient.emailAddress?.name || '',
965
- address: recipient.emailAddress?.address || ''
966
- })) || [],
967
- receivedDateTime: email.receivedDateTime,
968
- sentDateTime: email.sentDateTime,
969
- bodyPreview: email.bodyPreview || '',
970
- isRead: email.isRead || false,
971
- hasAttachments: email.hasAttachments || false,
972
- importance: email.importance || 'normal',
973
- conversationId: email.conversationId || '',
974
- parentFolderId: email.parentFolderId || '',
975
- webLink: email.webLink || ''
976
- }));
977
- emails.push(...batchEmails);
978
- }
979
- return emails;
980
- }
981
- catch (error) {
982
- logger.error('Error getting emails by IDs:', error);
983
- throw error;
850
+ const emails = [];
851
+ const batchSize = 20;
852
+ for (let i = 0; i < messageIds.length; i += batchSize) {
853
+ const batch = messageIds.slice(i, i + batchSize);
854
+ const batchPromises = batch.map(async (id) => {
855
+ try {
856
+ const graphClient = await this.getGraphClient();
857
+ const email = await graphClient
858
+ .api(`/me/messages/${id}`)
859
+ .select('id,subject,from,toRecipients,ccRecipients,receivedDateTime,sentDateTime,bodyPreview,isRead,hasAttachments,importance,conversationId,parentFolderId,webLink')
860
+ .get();
861
+ const emailInfo = {
862
+ id: email.id,
863
+ subject: email.subject || '',
864
+ from: {
865
+ name: email.from?.emailAddress?.name || '',
866
+ address: email.from?.emailAddress?.address || ''
867
+ },
868
+ toRecipients: email.toRecipients?.map((recipient) => ({
869
+ name: recipient.emailAddress?.name || '',
870
+ address: recipient.emailAddress?.address || ''
871
+ })) || [],
872
+ ccRecipients: email.ccRecipients?.map((recipient) => ({
873
+ name: recipient.emailAddress?.name || '',
874
+ address: recipient.emailAddress?.address || ''
875
+ })) || [],
876
+ receivedDateTime: email.receivedDateTime,
877
+ sentDateTime: email.sentDateTime,
878
+ bodyPreview: email.bodyPreview || '',
879
+ isRead: email.isRead || false,
880
+ hasAttachments: email.hasAttachments || false,
881
+ importance: email.importance || 'normal',
882
+ conversationId: email.conversationId || '',
883
+ parentFolderId: email.parentFolderId || '',
884
+ webLink: email.webLink || '',
885
+ attachments: [] // Initialize empty attachments array
886
+ };
887
+ return emailInfo;
888
+ }
889
+ catch (error) {
890
+ logger.error(`Error getting email ${id}:`, error);
891
+ return null;
892
+ }
893
+ });
894
+ const batchResults = await Promise.all(batchPromises);
895
+ const batchEmails = batchResults.filter((email) => email !== null);
896
+ emails.push(...batchEmails);
984
897
  }
898
+ return emails;
985
899
  }
986
900
  /**
987
901
  * Clear cached graph client (used when authentication fails)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ms365-mcp-server",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "Microsoft 365 MCP Server for managing Microsoft 365 email through natural language interactions with full OAuth2 authentication support",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",