@teamnetwork-nz/m365-mcp-server 1.5.0 → 1.6.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.
package/README.md CHANGED
@@ -185,7 +185,8 @@ Operations always target exactly one mailbox per request, either the default or
185
185
  |---|---|
186
186
  | `list_mailboxes` | List configured accounts and mailboxes with read/write status |
187
187
  | `list_folders` | List mail folders (top-level or child folders) |
188
- | `list_messages` | List messages with optional filters: date range, subject, body keyword, sender |
188
+ | `list_messages` | Search one folder or the whole mailbox with composable date presets, subject/body, sender name/address, recipients, attachment filename, read state, importance, attachment and sensitivity filters. Supports compact/full body modes and `nextPageToken` pagination |
189
+ | `list_conversation_messages` | Fetch a complete Outlook thread by the `conversationId` returned from `list_messages` |
189
190
  | `get_message` | Get full message details. Set `includeBody`, `includeAttachments`, or `includeInternetMessageHeaders` as needed |
190
191
  | `send_message` | Send an email (non-readonly mailboxes only) |
191
192
  | `reply_message` | Reply or reply-all to a message (non-readonly mailboxes only) |
@@ -198,11 +199,22 @@ Operations always target exactly one mailbox per request, either the default or
198
199
  | Tool | Description |
199
200
  |---|---|
200
201
  | `list_calendars` | List calendars for a mailbox |
201
- | `list_events` | List events in a date range (recurring events expanded into instances) |
202
+ | `list_events` | Search a date window; recurring events are expanded into occurrences. Filter by attendee, organizer, show-as, location, category, or your response status |
203
+ | `get_schedule` | Retrieve free/busy grids for one or more attendees before proposing a meeting time |
204
+ | `find_meeting_times` | Ask Graph to rank available meeting slots for required attendees within a time window |
202
205
  | `get_event` | Get full event details |
203
206
  | `create_event` | Create a new event (non-readonly mailboxes only) |
204
207
  | `update_event` | Update an existing event (non-readonly mailboxes only) |
205
208
 
209
+ ### Agent search guidance
210
+
211
+ - Start with `relativeDate` (for example `last7days` or `thisMonth`) and `searchAllFolders: true` when the folder is unknown. Use the per-call `timeZone` override when the request's locale differs from server configuration.
212
+ - `sender` accepts a display-name or address substring. Combine it freely with `subject`, `bodySearch`, recipient, flag, and attachment filters. When Microsoft Graph cannot safely combine criteria, `searchMetadata` identifies the local filtering and candidate count.
213
+ - Use `bodyFormat: "none"` for triage, `"preview"` for screening, and `"text"` or `"html"` only when full content is required. Use `select` to further minimize payloads.
214
+ - Continue a search by passing the returned `nextPageToken` as `pageToken`. Treat the token as opaque and do not edit it.
215
+ - Request `conversationId` (included automatically by the search tool) and call `list_conversation_messages` to inspect a thread. Use `attachmentName` to locate messages before calling the attachment tools.
216
+ - Call `get_schedule` to inspect availability or `find_meeting_times` to get ranked candidate slots before creating a meeting. `list_events` already uses Graph `calendarView`, so recurring occurrences in the requested window are returned individually.
217
+
206
218
  ### To Do
207
219
 
208
220
  | Tool | Description |
@@ -10,13 +10,37 @@ export async function listCalendars(client, email) {
10
10
  throw mapGraphError(err, 'list_calendars');
11
11
  }
12
12
  }
13
+ export async function getSchedule(client, email, schedules, startDate, endDate, timeZone, intervalMinutes) {
14
+ try {
15
+ return await client.api(`/users/${email}/calendar/getSchedule`).post({ schedules, startTime: { dateTime: startDate, timeZone }, endTime: { dateTime: endDate, timeZone }, availabilityViewInterval: intervalMinutes });
16
+ }
17
+ catch (err) {
18
+ throw mapGraphError(err, 'get_schedule');
19
+ }
20
+ }
21
+ export async function findMeetingTimes(client, email, attendees, startDate, endDate, durationMinutes, maxCandidates, minimumAttendeePercentage) {
22
+ try {
23
+ return await client.api(`/users/${email}/findMeetingTimes`).post({
24
+ attendees: attendees.map((address) => ({ emailAddress: { address }, type: 'required' })),
25
+ timeConstraint: { timeslots: [{ start: { dateTime: startDate, timeZone: 'UTC' }, end: { dateTime: endDate, timeZone: 'UTC' } }] },
26
+ meetingDuration: `PT${durationMinutes}M`,
27
+ maxCandidates,
28
+ minimumAttendeePercentage,
29
+ returnSuggestionReasons: true,
30
+ isOrganizerOptional: false,
31
+ });
32
+ }
33
+ catch (err) {
34
+ throw mapGraphError(err, 'find_meeting_times');
35
+ }
36
+ }
13
37
  export async function listEvents(client, email, params) {
14
38
  try {
15
39
  // calendarView expands recurring events into individual instances within the window
16
40
  const basePath = params.calendarId
17
41
  ? `/users/${email}/calendars/${params.calendarId}/calendarView`
18
42
  : `/users/${email}/calendarView`;
19
- return await client
43
+ const response = await client
20
44
  .api(basePath)
21
45
  .query({
22
46
  startDateTime: params.startDate,
@@ -26,6 +50,24 @@ export async function listEvents(client, email, params) {
26
50
  .top(params.maxResults)
27
51
  .orderby('start/dateTime')
28
52
  .get();
53
+ const events = response.value ?? [];
54
+ const contains = (value, terms) => terms.some((term) => JSON.stringify(value ?? '').toLowerCase().includes(term.toLowerCase()));
55
+ const filtered = events.filter((event) => {
56
+ if (params.attendees?.length && !contains(event['attendees'], params.attendees))
57
+ return false;
58
+ if (params.organizer && !contains(event['organizer'], [params.organizer]))
59
+ return false;
60
+ if (params.showAs && event['showAs'] !== params.showAs)
61
+ return false;
62
+ if (params.location && !contains(event['location'], [params.location]))
63
+ return false;
64
+ if (params.categories?.length && !contains(event['categories'], params.categories))
65
+ return false;
66
+ if (params.myResponseStatus && event['responseStatus']?.['response'] !== params.myResponseStatus)
67
+ return false;
68
+ return true;
69
+ });
70
+ return { ...response, value: filtered, ...(filtered.length !== events.length ? { searchMetadata: { locallyApplied: true, candidateCount: events.length } } : {}) };
29
71
  }
30
72
  catch (err) {
31
73
  throw mapGraphError(err, 'list_events');
@@ -17,18 +17,26 @@ export async function listFolders(client, email, params) {
17
17
  }
18
18
  export async function listMessages(client, email, params) {
19
19
  try {
20
- // Body search requires $search which cannot be combined with $filter.
21
- // When bodySearch is provided alongside date/sender filters, we use $search
22
- // for the body keyword and apply date/sender filtering client-side on the results.
23
- const folderId = params.folderId === 'Inbox' ? 'Inbox' : params.folderId;
20
+ if (params.pageToken) {
21
+ const tokenUrl = new URL(params.pageToken);
22
+ const decodedPath = decodeURIComponent(tokenUrl.pathname).toLowerCase();
23
+ if (tokenUrl.protocol !== 'https:' || tokenUrl.hostname !== 'graph.microsoft.com' || !decodedPath.startsWith('/v1.0/') || !decodedPath.includes(`/users/${email.toLowerCase()}/`) || !decodedPath.includes('/messages')) {
24
+ throw new Error('Invalid pageToken: token is not a message page for the resolved mailbox');
25
+ }
26
+ return normalizePage(await client.api(params.pageToken).get());
27
+ }
28
+ const endpoint = params.searchAllFolders
29
+ ? `/users/${email}/messages`
30
+ : `/users/${email}/mailFolders/${params.folderId}/messages`;
24
31
  let req = client
25
- .api(`/users/${email}/mailFolders/${folderId}/messages`)
32
+ .api(endpoint)
26
33
  .select(params.select)
27
34
  .top(params.maxResults)
28
35
  .orderby('receivedDateTime desc');
29
36
  if (params.bodySearch) {
30
37
  // $search mode: body keyword search. Date/sender applied client-side below.
31
- req = req.search(`"body:${params.bodySearch}"`);
38
+ req = client.api(endpoint).select(params.select).top(Math.min(100, Math.max(params.maxResults * 2, 50)))
39
+ .search(`"${params.bodySearch.replace(/"/g, '\\"')}"`);
32
40
  }
33
41
  else {
34
42
  // $filter mode: supports date range and sender.
@@ -37,38 +45,71 @@ export async function listMessages(client, email, params) {
37
45
  filters.push(`receivedDateTime ge ${params.startDate}`);
38
46
  if (params.endDate)
39
47
  filters.push(`receivedDateTime le ${params.endDate}`);
40
- if (params.sender)
41
- filters.push(`from/emailAddress/address eq '${params.sender}'`);
42
- if (params.subject)
43
- filters.push(`contains(subject,'${params.subject.replace(/'/g, "''")}')`);
48
+ // Only stable indexed filters are sent to Graph. String/recipient criteria are
49
+ // deliberately evaluated below, avoiding Graph's ErrorInvalidRestriction failures.
50
+ if (params.isRead !== undefined)
51
+ filters.push(`isRead eq ${params.isRead}`);
52
+ if (params.importance)
53
+ filters.push(`importance eq '${params.importance}'`);
54
+ if (params.hasAttachments !== undefined)
55
+ filters.push(`hasAttachments eq ${params.hasAttachments}`);
56
+ if (params.sensitivity)
57
+ filters.push(`sensitivity eq '${params.sensitivity}'`);
44
58
  if (filters.length > 0)
45
59
  req = req.filter(filters.join(' and '));
46
60
  }
61
+ if (params.bodyFormat === 'text' || params.bodyFormat === 'html') {
62
+ req = req.header('Prefer', `outlook.body-content-type="${params.bodyFormat}"`);
63
+ }
64
+ if (params.attachmentName)
65
+ req = req.expand('attachments($select=id,name,contentType,size,isInline)');
47
66
  const response = await req.get();
48
67
  // Client-side post-filter when bodySearch was used with date/sender constraints
49
- if (params.bodySearch && (params.startDate || params.endDate || params.sender)) {
68
+ const localCriteria = Boolean(params.subject || params.sender || params.toRecipients?.length || params.ccRecipients?.length || params.attachmentName || params.bodySearch);
69
+ if (localCriteria) {
70
+ const includes = (value, needles) => {
71
+ const s = JSON.stringify(value ?? '').toLowerCase();
72
+ return needles.some((needle) => s.includes(needle.toLowerCase()));
73
+ };
50
74
  const filtered = (response.value ?? []).filter((msg) => {
51
75
  const received = new Date(msg['receivedDateTime']).getTime();
52
76
  if (params.startDate && received < new Date(params.startDate).getTime())
53
77
  return false;
54
78
  if (params.endDate && received > new Date(params.endDate).getTime())
55
79
  return false;
56
- if (params.sender) {
57
- const from = msg['from']
58
- ?.emailAddress?.address?.toLowerCase();
59
- if (from !== params.sender.toLowerCase())
60
- return false;
61
- }
80
+ if (params.subject && !String(msg['subject'] ?? '').toLowerCase().includes(params.subject.toLowerCase()))
81
+ return false;
82
+ if (params.sender && !includes(msg['from'] ?? msg['sender'], [params.sender]))
83
+ return false;
84
+ if (params.toRecipients?.length && !includes(msg['toRecipients'], params.toRecipients))
85
+ return false;
86
+ if (params.ccRecipients?.length && !includes(msg['ccRecipients'], params.ccRecipients))
87
+ return false;
88
+ if (params.attachmentName && !includes(msg['attachments'], [params.attachmentName]))
89
+ return false;
62
90
  return true;
63
91
  });
64
- return { value: filtered };
92
+ return { value: filtered.slice(0, params.maxResults), nextPageToken: response['@odata.nextLink'], searchMetadata: { locallyApplied: ['subject', 'sender', 'toRecipients', 'ccRecipients', 'attachmentName'].filter((k) => Boolean(params[k])), candidateCount: response.value?.length ?? 0, note: 'Graph-safe broad query followed by local filtering. Follow nextPageToken if more candidates may exist.' } };
65
93
  }
66
- return response;
94
+ return normalizePage(response);
67
95
  }
68
96
  catch (err) {
69
97
  throw mapGraphError(err, 'list_messages');
70
98
  }
71
99
  }
100
+ function normalizePage(response) {
101
+ const { ['@odata.nextLink']: nextPageToken, ...rest } = response;
102
+ return { ...rest, ...(nextPageToken ? { nextPageToken } : {}) };
103
+ }
104
+ export async function listConversationMessages(client, email, conversationId, maxResults) {
105
+ try {
106
+ const escaped = conversationId.replace(/'/g, "''");
107
+ return normalizePage(await client.api(`/users/${email}/messages`).select('id,conversationId,subject,from,toRecipients,ccRecipients,receivedDateTime,isRead,hasAttachments,bodyPreview').filter(`conversationId eq '${escaped}'`).orderby('receivedDateTime asc').top(maxResults).get());
108
+ }
109
+ catch (err) {
110
+ throw mapGraphError(err, 'list_conversation_messages');
111
+ }
112
+ }
72
113
  export async function getMessage(client, email, messageId, includeBody, includeAttachments, includeInternetMessageHeaders) {
73
114
  try {
74
115
  const selectFields = [
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ async function main() {
18
18
  const createConfiguredServer = () => {
19
19
  const server = new McpServer({
20
20
  name: '@teamnetwork/m365-mcp-server',
21
- version: '1.5.0',
21
+ version: '1.6.0',
22
22
  }, {
23
23
  instructions: `
24
24
  Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph API.
@@ -0,0 +1,21 @@
1
+ import { FindMeetingTimesSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { findMeetingTimes } from '../../graph/calendar.js';
4
+ import { assertMailboxConfigured } from '../../middleware/readonlyGuard.js';
5
+ import { resolveMailbox } from '../../utils/resolveMailbox.js';
6
+ import { errorResponse } from '../../utils/errors.js';
7
+ import { localizeResponseDates, toUtcIso } from '../../utils/datetime.js';
8
+ export function registerFindMeetingTimes(server, config, auth) {
9
+ server.tool('find_meeting_times', 'Ask Microsoft Graph to rank meeting slots for required attendees inside a window. Use when the agent should propose actionable times, then pass the chosen time to create_event.', FindMeetingTimesSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
13
+ const client = createGraphClient(await auth.getAccessToken(resolved.accountId));
14
+ const result = await findMeetingTimes(client, resolved.mailbox, params.attendees, toUtcIso(params.startDate, params.timeZone), toUtcIso(params.endDate, params.timeZone), params.durationMinutes, params.maxCandidates, params.minimumAttendeePercentage);
15
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
16
+ }
17
+ catch (err) {
18
+ return errorResponse(err);
19
+ }
20
+ });
21
+ }
@@ -0,0 +1,22 @@
1
+ import { GetScheduleSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getSchedule } from '../../graph/calendar.js';
4
+ import { assertMailboxConfigured } from '../../middleware/readonlyGuard.js';
5
+ import { resolveMailbox } from '../../utils/resolveMailbox.js';
6
+ import { errorResponse } from '../../utils/errors.js';
7
+ import { getConfiguredTimezone, localizeResponseDates, toUtcIso } from '../../utils/datetime.js';
8
+ export function registerGetSchedule(server, config, auth) {
9
+ server.tool('get_schedule', 'Get free/busy availability for one or more people over a time window. Use before proposing meeting times; availabilityView uses 0=free, 1=tentative, 2=busy, 3=out-of-office, 4=working elsewhere.', GetScheduleSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
13
+ const tz = params.timeZone ?? getConfiguredTimezone();
14
+ const client = createGraphClient(await auth.getAccessToken(resolved.accountId));
15
+ const result = await getSchedule(client, resolved.mailbox, params.schedules, toUtcIso(params.startDate, tz), toUtcIso(params.endDate, tz), 'UTC', params.intervalMinutes);
16
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
17
+ }
18
+ catch (err) {
19
+ return errorResponse(err);
20
+ }
21
+ });
22
+ }
@@ -8,14 +8,25 @@ import { resolveSelect, SelectValidationError, EVENT_SELECT_FIELDS, EVENT_SELECT
8
8
  import { resolveMailbox } from '../../utils/resolveMailbox.js';
9
9
  import { toUtcIso, localizeResponseDates } from '../../utils/datetime.js';
10
10
  export function registerListEvents(server, config, auth) {
11
- server.tool('list_events', 'List calendar events within a date range. Recurring events are expanded into individual instances.', ListEventsSchema.shape, async (params) => {
11
+ server.tool('list_events', 'Search calendar occurrences within a date range. Recurring series are already expanded into individual occurrences. Supports attendee, organizer, show-as, location, category, and your response-status filters; request those fields in select when needed.', ListEventsSchema.shape, async (params) => {
12
12
  try {
13
13
  const resolved = resolveMailbox(config, params.accountId, params.mailbox);
14
14
  logger.info('list_events', { accountId: resolved.accountId, mailbox: resolved.mailbox });
15
15
  assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
16
16
  let select;
17
17
  try {
18
- select = resolveSelect(params.select, EVENT_SELECT_FIELDS, EVENT_SELECT_DEFAULT);
18
+ const requested = params.select ? [...params.select] : [...EVENT_SELECT_DEFAULT];
19
+ if (params.attendees && !requested.includes('attendees'))
20
+ requested.push('attendees');
21
+ if (params.organizer && !requested.includes('organizer'))
22
+ requested.push('organizer');
23
+ if (params.showAs && !requested.includes('showAs'))
24
+ requested.push('showAs');
25
+ if (params.categories && !requested.includes('categories'))
26
+ requested.push('categories');
27
+ if (params.myResponseStatus && !requested.includes('responseStatus'))
28
+ requested.push('responseStatus');
29
+ select = resolveSelect(requested, EVENT_SELECT_FIELDS, EVENT_SELECT_DEFAULT);
19
30
  }
20
31
  catch (err) {
21
32
  if (err instanceof SelectValidationError) {
@@ -26,11 +37,17 @@ export function registerListEvents(server, config, auth) {
26
37
  const token = await auth.getAccessToken(resolved.accountId);
27
38
  const client = createGraphClient(token);
28
39
  const result = await listEvents(client, resolved.mailbox, {
29
- startDate: toUtcIso(params.startDate),
30
- endDate: toUtcIso(params.endDate),
40
+ startDate: toUtcIso(params.startDate, params.timeZone),
41
+ endDate: toUtcIso(params.endDate, params.timeZone),
31
42
  maxResults: params.maxResults,
32
43
  select,
33
44
  ...(params.calendarId !== undefined && { calendarId: params.calendarId }),
45
+ ...(params.attendees !== undefined && { attendees: params.attendees }),
46
+ ...(params.organizer !== undefined && { organizer: params.organizer }),
47
+ ...(params.showAs !== undefined && { showAs: params.showAs }),
48
+ ...(params.location !== undefined && { location: params.location }),
49
+ ...(params.categories !== undefined && { categories: params.categories }),
50
+ ...(params.myResponseStatus !== undefined && { myResponseStatus: params.myResponseStatus }),
34
51
  });
35
52
  return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
36
53
  }
@@ -0,0 +1,21 @@
1
+ import { ListConversationMessagesSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listConversationMessages } from '../../graph/email.js';
4
+ import { assertMailboxConfigured } from '../../middleware/readonlyGuard.js';
5
+ import { resolveMailbox } from '../../utils/resolveMailbox.js';
6
+ import { errorResponse } from '../../utils/errors.js';
7
+ import { localizeResponseDates } from '../../utils/datetime.js';
8
+ export function registerListConversationMessages(server, config, auth) {
9
+ server.tool('list_conversation_messages', 'Return all accessible messages in an Outlook conversation, oldest first. Obtain conversationId from list_messages. Use this instead of repeatedly searching for related subjects.', ListConversationMessagesSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
13
+ const client = createGraphClient(await auth.getAccessToken(resolved.accountId));
14
+ const result = await listConversationMessages(client, resolved.mailbox, params.conversationId, params.maxResults);
15
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
16
+ }
17
+ catch (err) {
18
+ return errorResponse(err);
19
+ }
20
+ });
21
+ }
@@ -6,9 +6,9 @@ import { errorResponse, ToolError } from '../../utils/errors.js';
6
6
  import { logger } from '../../utils/logger.js';
7
7
  import { resolveSelect, SelectValidationError, MESSAGE_SELECT_FIELDS, MESSAGE_SELECT_DEFAULT } from '../../utils/selectFields.js';
8
8
  import { resolveMailbox } from '../../utils/resolveMailbox.js';
9
- import { toUtcIso, localizeResponseDates } from '../../utils/datetime.js';
9
+ import { toUtcIso, localizeResponseDates, resolveRelativeDateRange } from '../../utils/datetime.js';
10
10
  export function registerListMessages(server, config, auth) {
11
- server.tool('list_messages', 'List email messages in a mailbox folder with optional filters for date range, subject, body content, and sender. Returns message metadata (not full body) to keep response size small.', ListMessagesSchema.shape, async (params) => {
11
+ server.tool('list_messages', 'Search Outlook mail with composable date, subject, body, sender/display-name, recipient, attachment, read-state, importance, and sensitivity filters. Defaults to 50 compact results. Use searchAllFolders for mailbox-wide search, bodyFormat to control payload size, conversationId with list_conversation_messages for threads, and nextPageToken/pageToken for pagination. searchMetadata reports filters applied locally for Graph compatibility.', ListMessagesSchema.shape, async (params) => {
12
12
  try {
13
13
  const resolved = resolveMailbox(config, params.accountId, params.mailbox);
14
14
  logger.info('list_messages', {
@@ -20,7 +20,19 @@ export function registerListMessages(server, config, auth) {
20
20
  assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
21
21
  let select;
22
22
  try {
23
- select = resolveSelect(params.select, MESSAGE_SELECT_FIELDS, MESSAGE_SELECT_DEFAULT);
23
+ const requested = params.select ? [...params.select] : [...MESSAGE_SELECT_DEFAULT];
24
+ if (params.bodyFormat === 'none') {
25
+ const index = requested.indexOf('bodyPreview');
26
+ if (index >= 0)
27
+ requested.splice(index, 1);
28
+ }
29
+ else if (params.bodyFormat === 'text' || params.bodyFormat === 'html')
30
+ requested.push('body');
31
+ for (const field of ['receivedDateTime', 'from', 'subject', 'toRecipients', 'ccRecipients', 'attachments', 'conversationId']) {
32
+ if (field !== 'attachments' && !requested.includes(field))
33
+ requested.push(field);
34
+ }
35
+ select = resolveSelect(requested, MESSAGE_SELECT_FIELDS, MESSAGE_SELECT_DEFAULT);
24
36
  }
25
37
  catch (err) {
26
38
  if (err instanceof SelectValidationError) {
@@ -30,15 +42,30 @@ export function registerListMessages(server, config, auth) {
30
42
  }
31
43
  const token = await auth.getAccessToken(resolved.accountId);
32
44
  const client = createGraphClient(token);
45
+ if (params.relativeDate && (params.startDate || params.endDate))
46
+ throw new ToolError('relativeDate cannot be combined with startDate or endDate', 'INVALID_DATE_RANGE');
47
+ const dates = params.relativeDate ? resolveRelativeDateRange(params.relativeDate, params.timeZone) : {
48
+ ...(params.startDate ? { startDate: toUtcIso(params.startDate, params.timeZone) } : {}),
49
+ ...(params.endDate ? { endDate: toUtcIso(params.endDate, params.timeZone) } : {}),
50
+ };
33
51
  const result = await listMessages(client, resolved.mailbox, {
34
52
  folderId: params.folderId,
35
53
  maxResults: params.maxResults,
36
54
  select,
37
- ...(params.startDate !== undefined && { startDate: toUtcIso(params.startDate) }),
38
- ...(params.endDate !== undefined && { endDate: toUtcIso(params.endDate) }),
55
+ ...dates,
56
+ searchAllFolders: params.searchAllFolders,
57
+ bodyFormat: params.bodyFormat,
58
+ ...(params.pageToken !== undefined && { pageToken: params.pageToken }),
39
59
  ...(params.subject !== undefined && { subject: params.subject }),
40
60
  ...(params.bodySearch !== undefined && { bodySearch: params.bodySearch }),
41
61
  ...(params.sender !== undefined && { sender: params.sender }),
62
+ ...(params.toRecipients !== undefined && { toRecipients: params.toRecipients }),
63
+ ...(params.ccRecipients !== undefined && { ccRecipients: params.ccRecipients }),
64
+ ...(params.isRead !== undefined && { isRead: params.isRead }),
65
+ ...(params.importance !== undefined && { importance: params.importance }),
66
+ ...(params.hasAttachments !== undefined && { hasAttachments: params.hasAttachments }),
67
+ ...(params.sensitivity !== undefined && { sensitivity: params.sensitivity }),
68
+ ...(params.attachmentName !== undefined && { attachmentName: params.attachmentName }),
42
69
  });
43
70
  return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
44
71
  }
@@ -8,12 +8,15 @@ import { registerReplyMessage } from './email/replyMessage.js';
8
8
  import { registerMoveMessage } from './email/moveMessage.js';
9
9
  import { registerListMessageAttachments } from './email/listMessageAttachments.js';
10
10
  import { registerDownloadAttachment } from './email/downloadAttachment.js';
11
+ import { registerListConversationMessages } from './email/listConversationMessages.js';
11
12
  // Calendar tools
12
13
  import { registerListCalendars } from './calendar/listCalendars.js';
13
14
  import { registerListEvents } from './calendar/listEvents.js';
14
15
  import { registerGetEvent } from './calendar/getEvent.js';
15
16
  import { registerCreateEvent } from './calendar/createEvent.js';
16
17
  import { registerUpdateEvent } from './calendar/updateEvent.js';
18
+ import { registerGetSchedule } from './calendar/getSchedule.js';
19
+ import { registerFindMeetingTimes } from './calendar/findMeetingTimes.js';
17
20
  // Todo tools
18
21
  import { registerListTodoLists } from './todo/listTodoLists.js';
19
22
  import { registerListTodoTasks } from './todo/listTodoTasks.js';
@@ -58,6 +61,7 @@ function registerEmailTools(server, config, auth) {
58
61
  registerMoveMessage(server, config, auth);
59
62
  registerListMessageAttachments(server, config, auth);
60
63
  registerDownloadAttachment(server, config, auth);
64
+ registerListConversationMessages(server, config, auth);
61
65
  }
62
66
  function registerCalendarTools(server, config, auth) {
63
67
  registerListCalendars(server, config, auth);
@@ -65,6 +69,8 @@ function registerCalendarTools(server, config, auth) {
65
69
  registerGetEvent(server, config, auth);
66
70
  registerCreateEvent(server, config, auth);
67
71
  registerUpdateEvent(server, config, auth);
72
+ registerGetSchedule(server, config, auth);
73
+ registerFindMeetingTimes(server, config, auth);
68
74
  }
69
75
  function registerTodoTools(server, config, auth) {
70
76
  registerListTodoLists(server, config, auth);
@@ -12,13 +12,25 @@ export const ListFoldersSchema = AccountMailbox.extend({
12
12
  parentFolderId: z.string().optional().describe('ID of the parent folder to list child folders from. Omit for top-level folders.'),
13
13
  });
14
14
  export const ListMessagesSchema = AccountMailbox.extend({
15
- folderId: z.string().default('Inbox').describe('Folder ID or well-known name (e.g. "Inbox", "SentItems", "Drafts")'),
15
+ folderId: z.string().default('Inbox').describe('Folder ID or well-known name. Ignored when searchAllFolders is true.'),
16
+ searchAllFolders: z.boolean().default(false).describe('Search every mail folder through the mailbox-wide messages endpoint.'),
17
+ pageToken: z.string().optional().describe('Opaque nextPageToken returned by a previous list_messages call. When set, other search parameters are ignored.'),
18
+ relativeDate: z.enum(['today', 'yesterday', 'last7days', 'thisMonth', 'lastMonth', 'thisQuarter', 'lastQuarter', 'thisYear']).optional().describe('Convenient date window. Do not combine with startDate/endDate.'),
19
+ timeZone: z.string().optional().describe('IANA timezone used to interpret naive dates and relativeDate, e.g. Pacific/Auckland.'),
16
20
  startDate: z.string().optional().describe('Filter messages received on or after this datetime. Naive format ("2024-01-15T09:00:00") is interpreted as the configured local timezone (DATETIME_FORMAT).'),
17
21
  endDate: z.string().optional().describe('Filter messages received on or before this datetime. Naive format is interpreted as the configured local timezone (DATETIME_FORMAT).'),
18
- subject: z.string().optional().describe('Filter messages whose subject contains this string (ignored when bodySearch is set)'),
19
- bodySearch: z.string().optional().describe('Full-text search in message body. Note: cannot be combined with $filter — date/sender filters are applied client-side when this is used.'),
20
- sender: z.string().email().optional().describe('Filter messages from this sender email address'),
21
- maxResults: z.number().int().min(1).max(100).default(25).describe('Maximum number of messages to return (1–100)'),
22
+ subject: z.string().optional().describe('Case-insensitive subject substring. Can be combined with every other filter.'),
23
+ bodySearch: z.string().optional().describe('Full-text Graph search term. Other criteria are safely applied to the returned candidates.'),
24
+ sender: z.string().optional().describe('Case-insensitive sender display-name or email-address substring; an exact address is not required.'),
25
+ toRecipients: z.array(z.string()).optional().describe('Keep messages with a To recipient whose name or address contains any supplied value.'),
26
+ ccRecipients: z.array(z.string()).optional().describe('Keep messages with a CC recipient whose name or address contains any supplied value.'),
27
+ isRead: z.boolean().optional().describe('Keep read or unread messages.'),
28
+ importance: z.enum(['low', 'normal', 'high']).optional().describe('Keep messages with this Outlook importance.'),
29
+ hasAttachments: z.boolean().optional().describe('Keep messages based on whether they have attachments.'),
30
+ sensitivity: z.enum(['normal', 'personal', 'private', 'confidential']).optional().describe('Keep messages with this sensitivity.'),
31
+ attachmentName: z.string().optional().describe('Keep messages having an attachment filename containing this substring. Attachment metadata is fetched automatically.'),
32
+ bodyFormat: z.enum(['none', 'preview', 'text', 'html']).default('preview').describe('Payload control: none omits body text, preview returns bodyPreview, text/html returns the full body in that format.'),
33
+ maxResults: z.number().int().min(1).max(100).default(50).describe('Maximum matches to return (default 50, maximum 100).'),
22
34
  select: z.array(z.string()).optional().describe('Fields to return. Omit for defaults (subject, from, receivedDateTime, isRead, hasAttachments, bodyPreview). Valid fields: id, subject, from, toRecipients, ccRecipients, bccRecipients, receivedDateTime, sentDateTime, bodyPreview, body, hasAttachments, attachmentCount, importance, isRead, isDraft, webLink, parentFolderId, conversationId'),
23
35
  });
24
36
  export const GetMessageSchema = AccountMailbox.extend({
@@ -59,8 +71,35 @@ export const ListEventsSchema = AccountMailbox.extend({
59
71
  calendarId: z.string().optional().describe('Calendar ID. Omit to use the default calendar.'),
60
72
  startDate: z.string().describe('Start of the date range. Naive format ("2024-01-15T09:00:00") is interpreted as the configured local timezone (DATETIME_FORMAT). Recurring events are expanded within this window.'),
61
73
  endDate: z.string().describe('End of the date range. Naive format is interpreted as the configured local timezone (DATETIME_FORMAT).'),
74
+ timeZone: z.string().optional().describe('IANA timezone override for interpreting this request, e.g. Pacific/Auckland.'),
75
+ attendees: z.array(z.string()).optional().describe('Keep events where an attendee name/address contains any supplied value.'),
76
+ organizer: z.string().optional().describe('Keep events whose organizer name/address contains this substring.'),
77
+ showAs: z.enum(['free', 'tentative', 'busy', 'oof', 'workingElsewhere', 'unknown']).optional(),
78
+ location: z.string().optional().describe('Case-insensitive location substring.'),
79
+ categories: z.array(z.string()).optional().describe('Keep events carrying any supplied Outlook category.'),
80
+ myResponseStatus: z.enum(['none', 'organizer', 'tentativelyAccepted', 'accepted', 'declined', 'notResponded']).optional(),
62
81
  maxResults: z.number().int().min(1).max(100).default(25),
63
- select: z.array(z.string()).optional().describe('Fields to return. Omit for defaults (subject, start, end, location, isOnlineMeeting). Valid fields: id, subject, start, end, location, isOnlineMeeting, onlineMeetingUrl, organizer, attendees, body, bodyPreview, categories, isRecurring, recurrence, sensitivity, showAs, uid'),
82
+ select: z.array(z.string()).optional().describe('Fields to return. Omit for defaults (subject, start, end, location, isOnlineMeeting). Valid fields: id, subject, start, end, location, isOnlineMeeting, onlineMeetingUrl, organizer, attendees, body, bodyPreview, categories, isRecurring, recurrence, sensitivity, showAs, responseStatus, uid'),
83
+ });
84
+ export const ListConversationMessagesSchema = AccountMailbox.extend({
85
+ conversationId: z.string().min(1).describe('conversationId returned by list_messages.'),
86
+ maxResults: z.number().int().min(1).max(100).default(50),
87
+ });
88
+ export const GetScheduleSchema = AccountMailbox.extend({
89
+ schedules: z.array(z.string().email()).min(1).describe('Mailbox addresses whose free/busy availability is required.'),
90
+ startDate: z.string().describe('Start of availability window.'),
91
+ endDate: z.string().describe('End of availability window.'),
92
+ timeZone: z.string().optional().describe('IANA timezone for naive inputs and returned schedule items.'),
93
+ intervalMinutes: z.number().int().min(5).max(1440).default(30).describe('Availability grid interval in minutes.'),
94
+ });
95
+ export const FindMeetingTimesSchema = AccountMailbox.extend({
96
+ attendees: z.array(z.string().email()).min(1).describe('Required attendee email addresses.'),
97
+ startDate: z.string().describe('Earliest allowed start.'),
98
+ endDate: z.string().describe('Latest allowed end.'),
99
+ durationMinutes: z.number().int().min(5).max(1440).default(30),
100
+ timeZone: z.string().optional().describe('IANA timezone for naive inputs, e.g. Pacific/Auckland.'),
101
+ maxCandidates: z.number().int().min(1).max(20).default(5),
102
+ minimumAttendeePercentage: z.number().min(0).max(100).default(100).describe('100 requires every attendee to be available.'),
64
103
  });
65
104
  export const GetEventSchema = AccountMailbox.extend({
66
105
  eventId: z.string().describe('The event ID'),
@@ -76,14 +76,44 @@ function parseNaiveInTimezone(naive, tz) {
76
76
  * Converts a user-supplied datetime string to a UTC ISO 8601 string for use
77
77
  * in Graph API filter parameters (email date ranges, calendar view windows).
78
78
  */
79
- export function toUtcIso(input) {
80
- const tz = getConfiguredTimezone();
79
+ export function toUtcIso(input, timezone) {
80
+ const tz = timezone ?? getConfiguredTimezone();
81
81
  if (tz.toUpperCase() === 'UTC') {
82
82
  return hasTimezoneInfo(input) ? new Date(input).toISOString() : new Date(input + 'Z').toISOString();
83
83
  }
84
84
  const utc = hasTimezoneInfo(input) ? new Date(input) : parseNaiveInTimezone(input, tz);
85
85
  return utc.toISOString();
86
86
  }
87
+ /** Resolve an agent-friendly date preset into an inclusive UTC window. */
88
+ export function resolveRelativeDateRange(preset, timezone, now = new Date()) {
89
+ const tz = timezone ?? getConfiguredTimezone();
90
+ const local = formatNaive(now, tz);
91
+ const [year, month, day] = local.slice(0, 10).split('-').map(Number);
92
+ let start = new Date(Date.UTC(year, month - 1, day));
93
+ let end = new Date(Date.UTC(year, month - 1, day + 1));
94
+ if (preset === 'yesterday') {
95
+ start.setUTCDate(start.getUTCDate() - 1);
96
+ end.setUTCDate(end.getUTCDate() - 1);
97
+ }
98
+ if (preset === 'last7days')
99
+ start.setUTCDate(start.getUTCDate() - 6);
100
+ if (preset === 'thisMonth')
101
+ start = new Date(Date.UTC(year, month - 1, 1));
102
+ if (preset === 'lastMonth') {
103
+ start = new Date(Date.UTC(year, month - 2, 1));
104
+ end = new Date(Date.UTC(year, month - 1, 1));
105
+ }
106
+ if (preset === 'thisQuarter')
107
+ start = new Date(Date.UTC(year, Math.floor((month - 1) / 3) * 3, 1));
108
+ if (preset === 'lastQuarter') {
109
+ const q = Math.floor((month - 1) / 3) * 3;
110
+ start = new Date(Date.UTC(year, q - 3, 1));
111
+ end = new Date(Date.UTC(year, q, 1));
112
+ }
113
+ if (preset === 'thisYear')
114
+ start = new Date(Date.UTC(year, 0, 1));
115
+ return { startDate: toUtcIso(formatNaive(start, 'UTC'), tz), endDate: toUtcIso(formatNaive(end, 'UTC'), tz) };
116
+ }
87
117
  /**
88
118
  * Converts a user-supplied datetime to a {dateTime, timeZone} pair for the
89
119
  * Graph calendar create/update API. The dateTime is expressed as a naive
@@ -16,6 +16,9 @@ export function mapGraphError(err, context) {
16
16
  // Never include response body in mapped errors — it may contain email/calendar content
17
17
  switch (status) {
18
18
  case 400:
19
+ if (/too complex|ErrorInvalidRestriction|InefficientFilter/i.test(msg)) {
20
+ return new ToolError(`Microsoft Graph rejected this filter combination as too complex (${context}). Reduce server-side filters or use list_messages string/recipient filters, which automatically use Graph-safe local filtering.`, 'GRAPH_FILTER_TOO_COMPLEX');
21
+ }
19
22
  return new ToolError(`Bad request to Graph API (${context}): ${msg}`, 'GRAPH_BAD_REQUEST');
20
23
  case 401:
21
24
  return new ToolError(`Authentication failed (${context}) — verify tenant ID, client ID, and client secret`, 'GRAPH_UNAUTHORIZED');
@@ -37,6 +37,7 @@ export const EVENT_SELECT_FIELDS = new Set([
37
37
  'recurrence',
38
38
  'sensitivity',
39
39
  'showAs',
40
+ 'responseStatus',
40
41
  'uid',
41
42
  ]);
42
43
  export const MESSAGE_SELECT_DEFAULT = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamnetwork-nz/m365-mcp-server",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "MCP server for Microsoft 365 — Email, Calendar, To Do, SharePoint document libraries, and Teams — using client credentials (app-only auth). Supports multiple accounts, shared mailboxes, per-mailbox read-only access, and grant-based SharePoint access control.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",