@teamnetwork-nz/m365-mcp-server 1.0.5

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 (35) hide show
  1. package/README.md +264 -0
  2. package/config.example.json +27 -0
  3. package/dist/auth/AuthManager.js +19 -0
  4. package/dist/auth/TokenCache.js +25 -0
  5. package/dist/config/loader.js +31 -0
  6. package/dist/config/schema.js +23 -0
  7. package/dist/config/types.js +1 -0
  8. package/dist/graph/attachments.js +71 -0
  9. package/dist/graph/calendar.js +109 -0
  10. package/dist/graph/clientFactory.js +8 -0
  11. package/dist/graph/email.js +138 -0
  12. package/dist/index.js +30 -0
  13. package/dist/middleware/readonlyGuard.js +29 -0
  14. package/dist/tools/calendar/createEvent.js +38 -0
  15. package/dist/tools/calendar/getEvent.js +25 -0
  16. package/dist/tools/calendar/listCalendars.js +24 -0
  17. package/dist/tools/calendar/listEvents.js +42 -0
  18. package/dist/tools/calendar/updateEvent.js +40 -0
  19. package/dist/tools/email/downloadAttachment.js +43 -0
  20. package/dist/tools/email/getMessage.js +25 -0
  21. package/dist/tools/email/listFolders.js +26 -0
  22. package/dist/tools/email/listMailboxes.js +30 -0
  23. package/dist/tools/email/listMessageAttachments.js +26 -0
  24. package/dist/tools/email/listMessages.js +50 -0
  25. package/dist/tools/email/moveMessage.js +26 -0
  26. package/dist/tools/email/replyMessage.js +28 -0
  27. package/dist/tools/email/sendMessage.js +32 -0
  28. package/dist/tools/registry.js +39 -0
  29. package/dist/tools/schemas.js +91 -0
  30. package/dist/utils/datetime.js +162 -0
  31. package/dist/utils/errors.js +48 -0
  32. package/dist/utils/logger.js +32 -0
  33. package/dist/utils/resolveMailbox.js +52 -0
  34. package/dist/utils/selectFields.js +83 -0
  35. package/package.json +47 -0
@@ -0,0 +1,32 @@
1
+ import { SendMessageSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { sendMessage } from '../../graph/email.js';
4
+ import { assertWritable } from '../../middleware/readonlyGuard.js';
5
+ import { errorResponse } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveMailbox } from '../../utils/resolveMailbox.js';
8
+ export function registerSendMessage(server, config, auth) {
9
+ server.tool('send_message', 'Send an email from a configured mailbox. Requires the mailbox to be non-readonly. Omit accountId/mailbox to use the first configured account and mailbox.', SendMessageSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('send_message', { accountId: resolved.accountId, mailbox: resolved.mailbox });
13
+ assertWritable(config, resolved.accountId, resolved.mailbox);
14
+ const token = await auth.getAccessToken(resolved.accountId);
15
+ const client = createGraphClient(token);
16
+ await sendMessage(client, resolved.mailbox, {
17
+ to: params.to,
18
+ subject: params.subject,
19
+ body: params.body,
20
+ bodyType: params.bodyType,
21
+ saveToSent: params.saveToSent,
22
+ ...(params.cc !== undefined && { cc: params.cc }),
23
+ ...(params.bcc !== undefined && { bcc: params.bcc }),
24
+ });
25
+ return { content: [{ type: 'text', text: 'Message sent successfully.' }] };
26
+ }
27
+ catch (err) {
28
+ logger.error('send_message failed', { accountId: params.accountId, mailbox: params.mailbox });
29
+ return errorResponse(err);
30
+ }
31
+ });
32
+ }
@@ -0,0 +1,39 @@
1
+ // Email tools
2
+ import { registerListMailboxes } from './email/listMailboxes.js';
3
+ import { registerListFolders } from './email/listFolders.js';
4
+ import { registerListMessages } from './email/listMessages.js';
5
+ import { registerGetMessage } from './email/getMessage.js';
6
+ import { registerSendMessage } from './email/sendMessage.js';
7
+ import { registerReplyMessage } from './email/replyMessage.js';
8
+ import { registerMoveMessage } from './email/moveMessage.js';
9
+ import { registerListMessageAttachments } from './email/listMessageAttachments.js';
10
+ import { registerDownloadAttachment } from './email/downloadAttachment.js';
11
+ // Calendar tools
12
+ import { registerListCalendars } from './calendar/listCalendars.js';
13
+ import { registerListEvents } from './calendar/listEvents.js';
14
+ import { registerGetEvent } from './calendar/getEvent.js';
15
+ import { registerCreateEvent } from './calendar/createEvent.js';
16
+ import { registerUpdateEvent } from './calendar/updateEvent.js';
17
+ function registerEmailTools(server, config, auth) {
18
+ registerListMailboxes(server, config);
19
+ registerListFolders(server, config, auth);
20
+ registerListMessages(server, config, auth);
21
+ registerGetMessage(server, config, auth);
22
+ registerSendMessage(server, config, auth);
23
+ registerReplyMessage(server, config, auth);
24
+ registerMoveMessage(server, config, auth);
25
+ registerListMessageAttachments(server, config, auth);
26
+ registerDownloadAttachment(server, config, auth);
27
+ }
28
+ function registerCalendarTools(server, config, auth) {
29
+ registerListCalendars(server, config, auth);
30
+ registerListEvents(server, config, auth);
31
+ registerGetEvent(server, config, auth);
32
+ registerCreateEvent(server, config, auth);
33
+ registerUpdateEvent(server, config, auth);
34
+ }
35
+ export function registerAllTools(server, config, auth) {
36
+ registerEmailTools(server, config, auth);
37
+ registerCalendarTools(server, config, auth);
38
+ // Future: registerTeamsTools(server, config, auth);
39
+ }
@@ -0,0 +1,91 @@
1
+ import { z } from 'zod';
2
+ // ── Common ─────────────────────────────────────────────────────────────────
3
+ const AccountMailbox = z.object({
4
+ accountId: z.string().optional().describe('Account ID as defined in the config file. Omit to use the first configured account.'),
5
+ mailbox: z.string().email().optional().describe('Mailbox email address as defined in the config file. Omit to use the first mailbox of the resolved account.'),
6
+ });
7
+ // ── Email tools ────────────────────────────────────────────────────────────
8
+ export const ListMailboxesSchema = z.object({
9
+ accountId: z.string().optional().describe('Filter to a specific account ID. Omit to list all accounts and their mailboxes.'),
10
+ });
11
+ export const ListFoldersSchema = AccountMailbox.extend({
12
+ parentFolderId: z.string().optional().describe('ID of the parent folder to list child folders from. Omit for top-level folders.'),
13
+ });
14
+ export const ListMessagesSchema = AccountMailbox.extend({
15
+ folderId: z.string().default('Inbox').describe('Folder ID or well-known name (e.g. "Inbox", "SentItems", "Drafts")'),
16
+ 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
+ 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
+ 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
+ });
24
+ export const GetMessageSchema = AccountMailbox.extend({
25
+ messageId: z.string().describe('The message ID'),
26
+ includeBody: z.boolean().default(true).describe('Whether to include the full message body in the response'),
27
+ includeAttachments: z.boolean().default(false).describe('Whether to expand and include attachment metadata in the response'),
28
+ includeInternetMessageHeaders: z.boolean().default(false).describe('Whether to include raw internet message headers (e.g. Message-ID, X-Mailer, received chain). Useful for spam analysis and routing diagnostics.'),
29
+ });
30
+ export const ListMessageAttachmentsSchema = AccountMailbox.extend({
31
+ messageId: z.string().describe('The message ID to list attachments for'),
32
+ });
33
+ export const DownloadAttachmentSchema = AccountMailbox.extend({
34
+ messageId: z.string().describe('The message ID'),
35
+ attachmentId: z.string().describe('The attachment ID to download'),
36
+ });
37
+ export const SendMessageSchema = AccountMailbox.extend({
38
+ to: z.array(z.string().email()).min(1).describe('List of recipient email addresses'),
39
+ cc: z.array(z.string().email()).optional().describe('CC recipients'),
40
+ bcc: z.array(z.string().email()).optional().describe('BCC recipients'),
41
+ subject: z.string().min(1).describe('Message subject'),
42
+ body: z.string().describe('Message body content'),
43
+ bodyType: z.enum(['text', 'html']).default('text').describe('Body content type'),
44
+ saveToSent: z.boolean().default(true).describe('Whether to save the message to Sent Items'),
45
+ });
46
+ export const ReplyMessageSchema = AccountMailbox.extend({
47
+ messageId: z.string().describe('The ID of the message to reply to'),
48
+ body: z.string().describe('Reply body content'),
49
+ bodyType: z.enum(['text', 'html']).default('text'),
50
+ replyAll: z.boolean().default(false).describe('If true, reply to all recipients; otherwise reply only to sender'),
51
+ });
52
+ export const MoveMessageSchema = AccountMailbox.extend({
53
+ messageId: z.string().describe('The ID of the message to move'),
54
+ destinationFolderId: z.string().describe('The destination folder ID or well-known name (e.g. "DeletedItems")'),
55
+ });
56
+ // ── Calendar tools ─────────────────────────────────────────────────────────
57
+ export const ListCalendarsSchema = AccountMailbox;
58
+ export const ListEventsSchema = AccountMailbox.extend({
59
+ calendarId: z.string().optional().describe('Calendar ID. Omit to use the default calendar.'),
60
+ 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
+ endDate: z.string().describe('End of the date range. Naive format is interpreted as the configured local timezone (DATETIME_FORMAT).'),
62
+ 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'),
64
+ });
65
+ export const GetEventSchema = AccountMailbox.extend({
66
+ eventId: z.string().describe('The event ID'),
67
+ calendarId: z.string().optional().describe('Calendar ID. Omit to search across all calendars.'),
68
+ });
69
+ export const CreateEventSchema = AccountMailbox.extend({
70
+ calendarId: z.string().optional().describe('Calendar ID. Omit to create in the default calendar.'),
71
+ subject: z.string().min(1).describe('Event subject / title'),
72
+ body: z.string().optional().describe('Event description / body'),
73
+ bodyType: z.enum(['text', 'html']).default('text'),
74
+ startTime: z.string().describe('Event start time. Naive format ("2024-01-15T09:00:00") is interpreted as the configured local timezone (DATETIME_FORMAT).'),
75
+ endTime: z.string().describe('Event end time. Naive format is interpreted as the configured local timezone (DATETIME_FORMAT).'),
76
+ timeZone: z.string().optional().describe('IANA timezone name override (e.g. "Pacific/Auckland"). Defaults to the server\'s configured timezone (DATETIME_FORMAT env var).'),
77
+ location: z.string().optional().describe('Location display name'),
78
+ attendees: z.array(z.string().email()).optional().describe('List of attendee email addresses'),
79
+ isOnlineMeeting: z.boolean().default(false).describe('Whether to create an online meeting link'),
80
+ });
81
+ export const UpdateEventSchema = AccountMailbox.extend({
82
+ eventId: z.string().describe('The ID of the event to update'),
83
+ subject: z.string().optional(),
84
+ body: z.string().optional(),
85
+ bodyType: z.enum(['text', 'html']).optional(),
86
+ startTime: z.string().optional().describe('New start time. Naive format is interpreted as the configured local timezone (DATETIME_FORMAT).'),
87
+ endTime: z.string().optional().describe('New end time. Naive format is interpreted as the configured local timezone (DATETIME_FORMAT).'),
88
+ timeZone: z.string().optional().describe('IANA timezone name override. Defaults to the server\'s configured timezone (DATETIME_FORMAT env var).'),
89
+ location: z.string().optional(),
90
+ attendees: z.array(z.string().email()).optional(),
91
+ });
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Timezone-aware datetime conversion for the MCP server.
3
+ *
4
+ * Controlled by the DATETIME_FORMAT env var:
5
+ * 'local' (default) → use the process's system local timezone
6
+ * 'UTC' → no conversion; pass through UTC as-is
7
+ * <IANA name> → use that timezone (e.g. "Pacific/Auckland")
8
+ *
9
+ * User-supplied datetimes may be naive ("2024-01-15T09:00:00") or include an
10
+ * explicit offset ("2024-01-15T09:00:00+13:00"). Naive strings are always
11
+ * interpreted as belonging to the configured timezone.
12
+ */
13
+ export function getConfiguredTimezone() {
14
+ const env = (process.env['DATETIME_FORMAT'] ?? 'local').trim();
15
+ if (env.toLowerCase() === 'local') {
16
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
17
+ }
18
+ return env;
19
+ }
20
+ function isUtcMode() {
21
+ return getConfiguredTimezone().toUpperCase() === 'UTC';
22
+ }
23
+ function hasTimezoneInfo(s) {
24
+ return /Z$|[+-]\d{2}:?\d{2}$/.test(s);
25
+ }
26
+ /**
27
+ * Formats a Date as a naive datetime string ("YYYY-MM-DDTHH:mm:ss") expressed
28
+ * in the given IANA timezone. No offset or Z suffix.
29
+ */
30
+ function formatNaive(date, tz) {
31
+ const fmt = new Intl.DateTimeFormat('en-CA', {
32
+ timeZone: tz,
33
+ year: 'numeric', month: '2-digit', day: '2-digit',
34
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
35
+ hourCycle: 'h23',
36
+ });
37
+ const p = Object.fromEntries(fmt.formatToParts(date).map((x) => [x.type, x.value]));
38
+ return `${p['year']}-${p['month']}-${p['day']}T${p['hour']}:${p['minute']}:${p['second']}`;
39
+ }
40
+ /**
41
+ * Formats a Date as an ISO 8601 string with the UTC offset of the given IANA
42
+ * timezone at that moment (e.g. "2024-01-15T09:00:00+13:00").
43
+ */
44
+ function formatWithOffset(date, tz) {
45
+ const naiveStr = formatNaive(date, tz);
46
+ const naiveMs = new Date(naiveStr + 'Z').getTime();
47
+ const offsetMs = naiveMs - date.getTime();
48
+ const sign = offsetMs >= 0 ? '+' : '-';
49
+ const abs = Math.abs(offsetMs);
50
+ const h = String(Math.floor(abs / 3_600_000)).padStart(2, '0');
51
+ const m = String(Math.floor((abs % 3_600_000) / 60_000)).padStart(2, '0');
52
+ return `${naiveStr}${sign}${h}:${m}`;
53
+ }
54
+ /**
55
+ * Parses a naive datetime string (no offset) as if it represents a time in
56
+ * the given IANA timezone, returning the equivalent UTC Date.
57
+ *
58
+ * Uses the Intl trick: treat the naive string as UTC to get a reference Date,
59
+ * then find how far off that is from what the timezone would display, and
60
+ * subtract the difference to get the true UTC moment.
61
+ */
62
+ function parseNaiveInTimezone(naive, tz) {
63
+ const asIfUtc = new Date(naive + 'Z');
64
+ const fmt = new Intl.DateTimeFormat('en-CA', {
65
+ timeZone: tz,
66
+ year: 'numeric', month: '2-digit', day: '2-digit',
67
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
68
+ hourCycle: 'h23',
69
+ });
70
+ const p = Object.fromEntries(fmt.formatToParts(asIfUtc).map((x) => [x.type, x.value]));
71
+ const tzEquivalentMs = new Date(`${p['year']}-${p['month']}-${p['day']}T${p['hour']}:${p['minute']}:${p['second']}Z`).getTime();
72
+ const offsetMs = tzEquivalentMs - asIfUtc.getTime();
73
+ return new Date(asIfUtc.getTime() - offsetMs);
74
+ }
75
+ /**
76
+ * Converts a user-supplied datetime string to a UTC ISO 8601 string for use
77
+ * in Graph API filter parameters (email date ranges, calendar view windows).
78
+ */
79
+ export function toUtcIso(input) {
80
+ const tz = getConfiguredTimezone();
81
+ if (tz.toUpperCase() === 'UTC') {
82
+ return hasTimezoneInfo(input) ? new Date(input).toISOString() : new Date(input + 'Z').toISOString();
83
+ }
84
+ const utc = hasTimezoneInfo(input) ? new Date(input) : parseNaiveInTimezone(input, tz);
85
+ return utc.toISOString();
86
+ }
87
+ /**
88
+ * Converts a user-supplied datetime to a {dateTime, timeZone} pair for the
89
+ * Graph calendar create/update API. The dateTime is expressed as a naive
90
+ * string in the configured timezone so Graph stores the event correctly.
91
+ */
92
+ export function toCalendarDatetime(input) {
93
+ const tz = getConfiguredTimezone();
94
+ if (hasTimezoneInfo(input)) {
95
+ // Explicit offset: convert to the configured timezone
96
+ return { dateTime: formatNaive(new Date(input), tz), timeZone: tz };
97
+ }
98
+ // Naive: already in the configured timezone — pass through unchanged
99
+ return { dateTime: input, timeZone: tz };
100
+ }
101
+ /**
102
+ * Converts a UTC ISO 8601 string from the API to a local datetime string with
103
+ * the configured timezone offset (e.g. "2024-01-15T09:00:00+13:00").
104
+ */
105
+ export function toLocalIso(utcStr) {
106
+ const tz = getConfiguredTimezone();
107
+ if (tz.toUpperCase() === 'UTC')
108
+ return utcStr;
109
+ return formatWithOffset(new Date(utcStr), tz);
110
+ }
111
+ // Matches ISO 8601 datetime strings with or without an offset/Z/fractional seconds
112
+ const ISO_DT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})?$/;
113
+ function isApiDatetime(val) {
114
+ return typeof val === 'string' && ISO_DT_RE.test(val);
115
+ }
116
+ /**
117
+ * Recursively walks an API response object and converts all ISO 8601 datetime
118
+ * strings to the configured local timezone.
119
+ *
120
+ * Graph calendar {dateTime, timeZone} objects are handled as a unit so the
121
+ * source timezone is respected before conversion.
122
+ */
123
+ export function localizeResponseDates(obj) {
124
+ if (isUtcMode())
125
+ return obj;
126
+ if (obj === null || obj === undefined)
127
+ return obj;
128
+ if (typeof obj === 'string') {
129
+ return isApiDatetime(obj) ? toLocalIso(obj) : obj;
130
+ }
131
+ if (Array.isArray(obj)) {
132
+ return obj.map(localizeResponseDates);
133
+ }
134
+ if (typeof obj === 'object') {
135
+ const record = obj;
136
+ // Graph calendar start/end: {dateTime: "...", timeZone: "..."}
137
+ if (typeof record['dateTime'] === 'string' && typeof record['timeZone'] === 'string') {
138
+ const dt = record['dateTime'];
139
+ const apiTz = record['timeZone'];
140
+ const configuredTz = getConfiguredTimezone();
141
+ if (isApiDatetime(dt)) {
142
+ let utcDate;
143
+ if (hasTimezoneInfo(dt)) {
144
+ utcDate = new Date(dt);
145
+ }
146
+ else if (apiTz.toUpperCase() === 'UTC') {
147
+ utcDate = new Date(dt + 'Z');
148
+ }
149
+ else {
150
+ utcDate = parseNaiveInTimezone(dt, apiTz);
151
+ }
152
+ return { dateTime: formatWithOffset(utcDate, configuredTz), timeZone: configuredTz };
153
+ }
154
+ }
155
+ const out = {};
156
+ for (const [k, v] of Object.entries(record)) {
157
+ out[k] = localizeResponseDates(v);
158
+ }
159
+ return out;
160
+ }
161
+ return obj;
162
+ }
@@ -0,0 +1,48 @@
1
+ export class ToolError extends Error {
2
+ code;
3
+ retryable;
4
+ constructor(message, code, retryable = false) {
5
+ super(message);
6
+ this.code = code;
7
+ this.retryable = retryable;
8
+ this.name = 'ToolError';
9
+ }
10
+ }
11
+ export function mapGraphError(err, context) {
12
+ if (err instanceof ToolError)
13
+ return err;
14
+ const status = err?.['statusCode'];
15
+ const msg = err?.message ?? String(err);
16
+ // Never include response body in mapped errors — it may contain email/calendar content
17
+ switch (status) {
18
+ case 400:
19
+ return new ToolError(`Bad request to Graph API (${context}): ${msg}`, 'GRAPH_BAD_REQUEST');
20
+ case 401:
21
+ return new ToolError(`Authentication failed (${context}) — verify tenant ID, client ID, and client secret`, 'GRAPH_UNAUTHORIZED');
22
+ case 403:
23
+ return new ToolError(`Access denied (${context}) — verify ApplicationAccessPolicy is configured and app permissions are admin-consented`, 'GRAPH_FORBIDDEN');
24
+ case 404:
25
+ return new ToolError(`Resource not found (${context})`, 'GRAPH_NOT_FOUND');
26
+ case 429: {
27
+ const headers = err?.['headers'];
28
+ const retryAfter = headers?.['retry-after'] ?? 'unknown';
29
+ return new ToolError(`Graph API rate limit hit (${context}). Retry after ${retryAfter}s`, 'GRAPH_RATE_LIMIT', true);
30
+ }
31
+ case 503:
32
+ case 504:
33
+ return new ToolError(`Graph API service unavailable (${context}) — try again shortly`, 'GRAPH_UNAVAILABLE', true);
34
+ default:
35
+ if (status !== undefined) {
36
+ return new ToolError(`Graph API error ${status} (${context})`, 'GRAPH_ERROR');
37
+ }
38
+ return new ToolError(`Unexpected error (${context}): ${msg}`, 'UNKNOWN');
39
+ }
40
+ }
41
+ /** Format a tool error response for the MCP SDK */
42
+ export function errorResponse(err) {
43
+ const toolErr = err instanceof ToolError ? err : mapGraphError(err, 'unknown');
44
+ return {
45
+ content: [{ type: 'text', text: toolErr.message }],
46
+ isError: true,
47
+ };
48
+ }
@@ -0,0 +1,32 @@
1
+ // Structured logger with scrubbing of secrets, tokens, and email body content.
2
+ // Only tool name, account ID, mailbox address, status codes, and timestamps are safe to log.
3
+ const SCRUB_PATTERNS = [
4
+ /clientSecret['":\s]+[^\s,}"']+/gi,
5
+ /Bearer\s+[A-Za-z0-9\-_.]+/gi,
6
+ /accessToken['":\s]+[A-Za-z0-9\-_.]+/gi,
7
+ /"content"\s*:\s*"[^"]{50,}"/gi, // long content strings (likely email body)
8
+ /"body"\s*:\s*\{[^}]{20,}\}/gi, // body objects
9
+ ];
10
+ function scrub(value) {
11
+ let result = value;
12
+ for (const pattern of SCRUB_PATTERNS) {
13
+ result = result.replace(pattern, '[REDACTED]');
14
+ }
15
+ return result;
16
+ }
17
+ function format(level, message, meta) {
18
+ const ts = new Date().toISOString();
19
+ const metaStr = meta ? ' ' + scrub(JSON.stringify(meta)) : '';
20
+ return `[${ts}] [${level}] ${message}${metaStr}`;
21
+ }
22
+ export const logger = {
23
+ info(message, meta) {
24
+ process.stderr.write(format('INFO', message, meta) + '\n');
25
+ },
26
+ warn(message, meta) {
27
+ process.stderr.write(format('WARN', message, meta) + '\n');
28
+ },
29
+ error(message, meta) {
30
+ process.stderr.write(format('ERROR', message, meta) + '\n');
31
+ },
32
+ };
@@ -0,0 +1,52 @@
1
+ import { ToolError } from './errors.js';
2
+ /**
3
+ * Resolves optional accountId / mailbox params to concrete values using config defaults.
4
+ *
5
+ * Resolution rules:
6
+ * - accountId omitted → config.accounts[0].id (first account in config)
7
+ * - accountId given → must match a configured account ID (throws CONFIG_ERROR if not)
8
+ * - mailbox omitted → resolvedAccount.mailboxes[0].email (first mailbox in account)
9
+ * - mailbox given → must exist in the resolved account (throws CONFIG_ERROR if not)
10
+ *
11
+ * The ordering of accounts and mailboxes in the config file is the source of truth for
12
+ * "which is the default". Operations always target exactly one mailbox per request.
13
+ *
14
+ * Note: readonly enforcement is NOT performed here. Callers that require write access
15
+ * must call assertWritable() after this function.
16
+ */
17
+ export function resolveMailbox(config, rawAccountId, rawMailbox) {
18
+ // ── Resolve account ──────────────────────────────────────────────────────
19
+ if (config.accounts.length === 0) {
20
+ throw new ToolError('No accounts are configured. Add at least one account to your config file.', 'CONFIG_ERROR');
21
+ }
22
+ let accountId;
23
+ if (rawAccountId === undefined) {
24
+ accountId = config.accounts[0].id;
25
+ }
26
+ else {
27
+ const found = config.accounts.find((a) => a.id === rawAccountId);
28
+ if (!found) {
29
+ const available = config.accounts.map((a) => a.id).join(', ');
30
+ throw new ToolError(`Unknown account ID: "${rawAccountId}". Configured accounts: ${available}`, 'CONFIG_ERROR');
31
+ }
32
+ accountId = found.id;
33
+ }
34
+ // ── Resolve mailbox ──────────────────────────────────────────────────────
35
+ const account = config.accounts.find((a) => a.id === accountId);
36
+ if (account.mailboxes.length === 0) {
37
+ throw new ToolError(`Account "${accountId}" has no configured mailboxes.`, 'CONFIG_ERROR');
38
+ }
39
+ let mailbox;
40
+ if (rawMailbox === undefined) {
41
+ mailbox = account.mailboxes[0].email;
42
+ }
43
+ else {
44
+ const found = account.mailboxes.find((m) => m.email.toLowerCase() === rawMailbox.toLowerCase());
45
+ if (!found) {
46
+ const available = account.mailboxes.map((m) => m.email).join(', ');
47
+ throw new ToolError(`Mailbox "${rawMailbox}" is not configured for account "${accountId}". Configured mailboxes: ${available}`, 'CONFIG_ERROR');
48
+ }
49
+ mailbox = found.email;
50
+ }
51
+ return { accountId, mailbox };
52
+ }
@@ -0,0 +1,83 @@
1
+ // Allowed $select field lists and validation for list_messages and list_events.
2
+ // id is always forced into the select regardless of what the caller requests.
3
+ export const MESSAGE_SELECT_FIELDS = new Set([
4
+ 'id',
5
+ 'subject',
6
+ 'from',
7
+ 'toRecipients',
8
+ 'ccRecipients',
9
+ 'bccRecipients',
10
+ 'receivedDateTime',
11
+ 'sentDateTime',
12
+ 'bodyPreview',
13
+ 'body',
14
+ 'hasAttachments',
15
+ 'attachmentCount',
16
+ 'importance',
17
+ 'isRead',
18
+ 'isDraft',
19
+ 'webLink',
20
+ 'parentFolderId',
21
+ 'conversationId',
22
+ ]);
23
+ export const EVENT_SELECT_FIELDS = new Set([
24
+ 'id',
25
+ 'subject',
26
+ 'start',
27
+ 'end',
28
+ 'location',
29
+ 'isOnlineMeeting',
30
+ 'onlineMeetingUrl',
31
+ 'organizer',
32
+ 'attendees',
33
+ 'body',
34
+ 'bodyPreview',
35
+ 'categories',
36
+ 'isRecurring',
37
+ 'recurrence',
38
+ 'sensitivity',
39
+ 'showAs',
40
+ 'uid',
41
+ ]);
42
+ export const MESSAGE_SELECT_DEFAULT = [
43
+ 'subject',
44
+ 'from',
45
+ 'receivedDateTime',
46
+ 'isRead',
47
+ 'hasAttachments',
48
+ 'bodyPreview',
49
+ ];
50
+ export const EVENT_SELECT_DEFAULT = [
51
+ 'subject',
52
+ 'start',
53
+ 'end',
54
+ 'location',
55
+ 'isOnlineMeeting',
56
+ ];
57
+ /**
58
+ * Validate, normalise, and force-include `id` in a select list.
59
+ * Returns the final comma-separated string for Graph API $select,
60
+ * or throws with a descriptive message listing valid fields.
61
+ */
62
+ export function resolveSelect(rawSelect, allowed, defaults) {
63
+ // Empty array → treat as omitted, use defaults
64
+ const fields = rawSelect && rawSelect.length > 0
65
+ ? rawSelect.map((f) => f.trim()).filter(Boolean)
66
+ : defaults;
67
+ // Validate each field
68
+ for (const field of fields) {
69
+ if (!allowed.has(field)) {
70
+ throw new SelectValidationError(field, allowed);
71
+ }
72
+ }
73
+ // id must always be present
74
+ const withId = fields.includes('id') ? fields : ['id', ...fields];
75
+ return withId.join(',');
76
+ }
77
+ export class SelectValidationError extends Error {
78
+ constructor(invalidField, allowed) {
79
+ const validList = [...allowed].sort().join(', ');
80
+ super(`Invalid select field: "${invalidField}". Valid fields: ${validList}`);
81
+ this.name = 'SelectValidationError';
82
+ }
83
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@teamnetwork-nz/m365-mcp-server",
3
+ "version": "1.0.5",
4
+ "description": "MCP server for Microsoft 365 Email and Calendar access using client credentials (app-only auth). Supports multiple accounts, shared mailboxes, per-mailbox read-only access, folder navigation, and date/content filtering.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "bin": {
8
+ "m365-mcp": "./dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "config.example.json"
13
+ ],
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "prepare": "npm run build",
17
+ "start": "node dist/index.js",
18
+ "dev": "tsx watch src/index.ts"
19
+ },
20
+ "keywords": [
21
+ "mcp",
22
+ "model-context-protocol",
23
+ "microsoft-365",
24
+ "m365",
25
+ "outlook",
26
+ "email",
27
+ "calendar",
28
+ "microsoft-graph",
29
+ "claude",
30
+ "ai"
31
+ ],
32
+ "license": "MIT",
33
+ "engines": {
34
+ "node": ">=18.0.0"
35
+ },
36
+ "dependencies": {
37
+ "@azure/msal-node": "^2.16.0",
38
+ "@microsoft/microsoft-graph-client": "^3.0.7",
39
+ "@modelcontextprotocol/sdk": "^1.10.0",
40
+ "zod": "^3.23.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^20.0.0",
44
+ "tsx": "^4.10.0",
45
+ "typescript": "^5.4.0"
46
+ }
47
+ }