@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,138 @@
1
+ import { mapGraphError } from '../utils/errors.js';
2
+ export async function listFolders(client, email, params) {
3
+ try {
4
+ const basePath = params.parentFolderId
5
+ ? `/users/${email}/mailFolders/${params.parentFolderId}/childFolders`
6
+ : `/users/${email}/mailFolders`;
7
+ const response = await client
8
+ .api(basePath)
9
+ .select('id,displayName,totalItemCount,unreadItemCount,childFolderCount')
10
+ .top(100)
11
+ .get();
12
+ return response;
13
+ }
14
+ catch (err) {
15
+ throw mapGraphError(err, 'list_folders');
16
+ }
17
+ }
18
+ export async function listMessages(client, email, params) {
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;
24
+ let req = client
25
+ .api(`/users/${email}/mailFolders/${folderId}/messages`)
26
+ .select(params.select)
27
+ .top(params.maxResults)
28
+ .orderby('receivedDateTime desc');
29
+ if (params.bodySearch) {
30
+ // $search mode: body keyword search. Date/sender applied client-side below.
31
+ req = req.search(`"body:${params.bodySearch}"`);
32
+ }
33
+ else {
34
+ // $filter mode: supports date range and sender.
35
+ const filters = [];
36
+ if (params.startDate)
37
+ filters.push(`receivedDateTime ge ${params.startDate}`);
38
+ if (params.endDate)
39
+ 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, "''")}')`);
44
+ if (filters.length > 0)
45
+ req = req.filter(filters.join(' and '));
46
+ }
47
+ const response = await req.get();
48
+ // Client-side post-filter when bodySearch was used with date/sender constraints
49
+ if (params.bodySearch && (params.startDate || params.endDate || params.sender)) {
50
+ const filtered = (response.value ?? []).filter((msg) => {
51
+ const received = new Date(msg['receivedDateTime']).getTime();
52
+ if (params.startDate && received < new Date(params.startDate).getTime())
53
+ return false;
54
+ if (params.endDate && received > new Date(params.endDate).getTime())
55
+ 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
+ }
62
+ return true;
63
+ });
64
+ return { value: filtered };
65
+ }
66
+ return response;
67
+ }
68
+ catch (err) {
69
+ throw mapGraphError(err, 'list_messages');
70
+ }
71
+ }
72
+ export async function getMessage(client, email, messageId, includeBody, includeAttachments, includeInternetMessageHeaders) {
73
+ try {
74
+ const selectFields = [
75
+ 'id', 'subject', 'from', 'toRecipients', 'ccRecipients',
76
+ 'receivedDateTime', 'hasAttachments', 'isRead',
77
+ ];
78
+ if (includeBody)
79
+ selectFields.push('body');
80
+ if (includeInternetMessageHeaders)
81
+ selectFields.push('internetMessageHeaders');
82
+ let req = client
83
+ .api(`/users/${email}/messages/${messageId}`)
84
+ .select(selectFields.join(','));
85
+ if (includeAttachments) {
86
+ // Expand attachments inline — avoids a second round-trip for the caller
87
+ req = req.expand('attachments($select=id,name,contentType,size,isInline)');
88
+ }
89
+ return await req.get();
90
+ }
91
+ catch (err) {
92
+ throw mapGraphError(err, 'get_message');
93
+ }
94
+ }
95
+ export async function sendMessage(client, email, params) {
96
+ try {
97
+ const toRecipients = params.to.map((addr) => ({ emailAddress: { address: addr } }));
98
+ const ccRecipients = (params.cc ?? []).map((addr) => ({ emailAddress: { address: addr } }));
99
+ const bccRecipients = (params.bcc ?? []).map((addr) => ({ emailAddress: { address: addr } }));
100
+ await client.api(`/users/${email}/sendMail`).post({
101
+ message: {
102
+ subject: params.subject,
103
+ body: { contentType: params.bodyType === 'html' ? 'HTML' : 'Text', content: params.body },
104
+ toRecipients,
105
+ ...(ccRecipients.length > 0 && { ccRecipients }),
106
+ ...(bccRecipients.length > 0 && { bccRecipients }),
107
+ },
108
+ saveToSentItems: params.saveToSent,
109
+ });
110
+ }
111
+ catch (err) {
112
+ throw mapGraphError(err, 'send_message');
113
+ }
114
+ }
115
+ export async function replyToMessage(client, email, messageId, params) {
116
+ try {
117
+ const endpoint = params.replyAll
118
+ ? `/users/${email}/messages/${messageId}/replyAll`
119
+ : `/users/${email}/messages/${messageId}/reply`;
120
+ await client.api(endpoint).post({
121
+ message: {},
122
+ comment: params.body,
123
+ });
124
+ }
125
+ catch (err) {
126
+ throw mapGraphError(err, 'reply_message');
127
+ }
128
+ }
129
+ export async function moveMessage(client, email, messageId, params) {
130
+ try {
131
+ return await client.api(`/users/${email}/messages/${messageId}/move`).post({
132
+ destinationId: params.destinationFolderId,
133
+ });
134
+ }
135
+ catch (err) {
136
+ throw mapGraphError(err, 'move_message');
137
+ }
138
+ }
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { loadConfig } from './config/loader.js';
5
+ import { TokenCache } from './auth/TokenCache.js';
6
+ import { AuthManager } from './auth/AuthManager.js';
7
+ import { registerAllTools } from './tools/registry.js';
8
+ import { logger } from './utils/logger.js';
9
+ async function main() {
10
+ // 1. Load and validate config — aborts if invalid
11
+ const config = loadConfig();
12
+ logger.info('Config loaded', { accounts: config.accounts.map((a) => a.id) });
13
+ // 2. Initialise MSAL clients (one per account, in-memory token cache)
14
+ const tokenCache = new TokenCache(config);
15
+ const auth = new AuthManager(tokenCache);
16
+ // 3. Create MCP server and register all tools
17
+ const server = new McpServer({
18
+ name: '@teamnetwork/m365-mcp-server',
19
+ version: '1.0.0',
20
+ });
21
+ registerAllTools(server, config, auth);
22
+ // 4. Connect via stdio transport (Claude Desktop / Claude Code)
23
+ const transport = new StdioServerTransport();
24
+ await server.connect(transport);
25
+ logger.info('M365 MCP server running on stdio');
26
+ }
27
+ main().catch((err) => {
28
+ process.stderr.write(`Fatal: ${err.message ?? String(err)}\n`);
29
+ process.exit(1);
30
+ });
@@ -0,0 +1,29 @@
1
+ import { ToolError } from '../utils/errors.js';
2
+ /**
3
+ * Asserts that the given mailbox is configured and is NOT readonly.
4
+ * Must be called at the top of every write-path tool handler, before any Graph call.
5
+ */
6
+ export function assertWritable(config, accountId, mailbox) {
7
+ const account = config.accounts.find((a) => a.id === accountId);
8
+ if (!account) {
9
+ throw new ToolError(`Unknown account ID: "${accountId}". Check your config file.`, 'CONFIG_ERROR');
10
+ }
11
+ const mbConfig = account.mailboxes.find((m) => m.email.toLowerCase() === mailbox.toLowerCase());
12
+ if (!mbConfig) {
13
+ throw new ToolError(`Mailbox "${mailbox}" is not configured for account "${accountId}".`, 'CONFIG_ERROR');
14
+ }
15
+ if (mbConfig.readonly) {
16
+ throw new ToolError(`Mailbox "${mailbox}" is configured as read-only — write operations are not permitted.`, 'READONLY_VIOLATION');
17
+ }
18
+ }
19
+ /** Asserts that the given mailbox is configured (readable). Shared helper for read tools. */
20
+ export function assertMailboxConfigured(config, accountId, mailbox) {
21
+ const account = config.accounts.find((a) => a.id === accountId);
22
+ if (!account) {
23
+ throw new ToolError(`Unknown account ID: "${accountId}". Check your config file.`, 'CONFIG_ERROR');
24
+ }
25
+ const mbConfig = account.mailboxes.find((m) => m.email.toLowerCase() === mailbox.toLowerCase());
26
+ if (!mbConfig) {
27
+ throw new ToolError(`Mailbox "${mailbox}" is not configured for account "${accountId}".`, 'CONFIG_ERROR');
28
+ }
29
+ }
@@ -0,0 +1,38 @@
1
+ import { CreateEventSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { createEvent } from '../../graph/calendar.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
+ import { toCalendarDatetime, localizeResponseDates } from '../../utils/datetime.js';
9
+ export function registerCreateEvent(server, config, auth) {
10
+ server.tool('create_event', 'Create a new calendar event. Requires the mailbox to be non-readonly. Omit accountId/mailbox to use the first configured account and mailbox.', CreateEventSchema.shape, async (params) => {
11
+ try {
12
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
13
+ logger.info('create_event', { accountId: resolved.accountId, mailbox: resolved.mailbox });
14
+ assertWritable(config, resolved.accountId, resolved.mailbox);
15
+ const token = await auth.getAccessToken(resolved.accountId);
16
+ const client = createGraphClient(token);
17
+ const startDt = toCalendarDatetime(params.startTime);
18
+ const endDt = toCalendarDatetime(params.endTime);
19
+ const result = await createEvent(client, resolved.mailbox, {
20
+ subject: params.subject,
21
+ bodyType: params.bodyType,
22
+ startTime: startDt.dateTime,
23
+ endTime: endDt.dateTime,
24
+ timeZone: params.timeZone ?? startDt.timeZone,
25
+ isOnlineMeeting: params.isOnlineMeeting,
26
+ ...(params.calendarId !== undefined && { calendarId: params.calendarId }),
27
+ ...(params.body !== undefined && { body: params.body }),
28
+ ...(params.location !== undefined && { location: params.location }),
29
+ ...(params.attendees !== undefined && { attendees: params.attendees }),
30
+ });
31
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
32
+ }
33
+ catch (err) {
34
+ logger.error('create_event failed', { accountId: params.accountId, mailbox: params.mailbox });
35
+ return errorResponse(err);
36
+ }
37
+ });
38
+ }
@@ -0,0 +1,25 @@
1
+ import { GetEventSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getEvent } from '../../graph/calendar.js';
4
+ import { assertMailboxConfigured } 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
+ import { localizeResponseDates } from '../../utils/datetime.js';
9
+ export function registerGetEvent(server, config, auth) {
10
+ server.tool('get_event', 'Get full details of a specific calendar event by ID. Omit accountId/mailbox to use the first configured account and mailbox.', GetEventSchema.shape, async (params) => {
11
+ try {
12
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
13
+ logger.info('get_event', { accountId: resolved.accountId, mailbox: resolved.mailbox });
14
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
15
+ const token = await auth.getAccessToken(resolved.accountId);
16
+ const client = createGraphClient(token);
17
+ const result = await getEvent(client, resolved.mailbox, params.eventId);
18
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
19
+ }
20
+ catch (err) {
21
+ logger.error('get_event failed', { accountId: params.accountId, mailbox: params.mailbox });
22
+ return errorResponse(err);
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,24 @@
1
+ import { ListCalendarsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listCalendars } from '../../graph/calendar.js';
4
+ import { assertMailboxConfigured } 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 registerListCalendars(server, config, auth) {
9
+ server.tool('list_calendars', 'List all calendars for a mailbox. Omit accountId/mailbox to use the first configured account and mailbox.', ListCalendarsSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('list_calendars', { accountId: resolved.accountId, mailbox: resolved.mailbox });
13
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
14
+ const token = await auth.getAccessToken(resolved.accountId);
15
+ const client = createGraphClient(token);
16
+ const result = await listCalendars(client, resolved.mailbox);
17
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
18
+ }
19
+ catch (err) {
20
+ logger.error('list_calendars failed', { accountId: params.accountId, mailbox: params.mailbox });
21
+ return errorResponse(err);
22
+ }
23
+ });
24
+ }
@@ -0,0 +1,42 @@
1
+ import { ListEventsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listEvents } from '../../graph/calendar.js';
4
+ import { assertMailboxConfigured } from '../../middleware/readonlyGuard.js';
5
+ import { errorResponse, ToolError } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSelect, SelectValidationError, EVENT_SELECT_FIELDS, EVENT_SELECT_DEFAULT } from '../../utils/selectFields.js';
8
+ import { resolveMailbox } from '../../utils/resolveMailbox.js';
9
+ import { toUtcIso, localizeResponseDates } from '../../utils/datetime.js';
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) => {
12
+ try {
13
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
14
+ logger.info('list_events', { accountId: resolved.accountId, mailbox: resolved.mailbox });
15
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
16
+ let select;
17
+ try {
18
+ select = resolveSelect(params.select, EVENT_SELECT_FIELDS, EVENT_SELECT_DEFAULT);
19
+ }
20
+ catch (err) {
21
+ if (err instanceof SelectValidationError) {
22
+ return errorResponse(new ToolError(err.message, 'INVALID_SELECT_FIELD'));
23
+ }
24
+ throw err;
25
+ }
26
+ const token = await auth.getAccessToken(resolved.accountId);
27
+ const client = createGraphClient(token);
28
+ const result = await listEvents(client, resolved.mailbox, {
29
+ startDate: toUtcIso(params.startDate),
30
+ endDate: toUtcIso(params.endDate),
31
+ maxResults: params.maxResults,
32
+ select,
33
+ ...(params.calendarId !== undefined && { calendarId: params.calendarId }),
34
+ });
35
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
36
+ }
37
+ catch (err) {
38
+ logger.error('list_events failed', { accountId: params.accountId, mailbox: params.mailbox ?? 'default' });
39
+ return errorResponse(err);
40
+ }
41
+ });
42
+ }
@@ -0,0 +1,40 @@
1
+ import { UpdateEventSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { updateEvent } from '../../graph/calendar.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
+ import { toCalendarDatetime, localizeResponseDates } from '../../utils/datetime.js';
9
+ export function registerUpdateEvent(server, config, auth) {
10
+ server.tool('update_event', 'Update an existing calendar event. Only provided fields are changed. Requires the mailbox to be non-readonly. Omit accountId/mailbox to use the first configured account and mailbox.', UpdateEventSchema.shape, async (params) => {
11
+ try {
12
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
13
+ logger.info('update_event', { accountId: resolved.accountId, mailbox: resolved.mailbox });
14
+ assertWritable(config, resolved.accountId, resolved.mailbox);
15
+ const token = await auth.getAccessToken(resolved.accountId);
16
+ const client = createGraphClient(token);
17
+ const startDt = params.startTime !== undefined ? toCalendarDatetime(params.startTime) : undefined;
18
+ const endDt = params.endTime !== undefined ? toCalendarDatetime(params.endTime) : undefined;
19
+ const result = await updateEvent(client, resolved.mailbox, params.eventId, {
20
+ ...(params.subject !== undefined && { subject: params.subject }),
21
+ ...(params.body !== undefined && { body: params.body }),
22
+ ...(params.bodyType !== undefined && { bodyType: params.bodyType }),
23
+ ...(startDt !== undefined && { startTime: startDt.dateTime }),
24
+ ...(endDt !== undefined && { endTime: endDt.dateTime }),
25
+ ...(params.timeZone !== undefined
26
+ ? { timeZone: params.timeZone }
27
+ : (startDt ?? endDt) !== undefined
28
+ ? { timeZone: (startDt ?? endDt).timeZone }
29
+ : {}),
30
+ ...(params.location !== undefined && { location: params.location }),
31
+ ...(params.attendees !== undefined && { attendees: params.attendees }),
32
+ });
33
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
34
+ }
35
+ catch (err) {
36
+ logger.error('update_event failed', { accountId: params.accountId, mailbox: params.mailbox });
37
+ return errorResponse(err);
38
+ }
39
+ });
40
+ }
@@ -0,0 +1,43 @@
1
+ import { DownloadAttachmentSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { downloadAttachment } from '../../graph/attachments.js';
4
+ import { assertMailboxConfigured } 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 registerDownloadAttachment(server, config, auth) {
9
+ server.tool('download_attachment', 'Download a file attachment from an email message. Returns base64-encoded file content for file attachments, the preview URL for reference attachments (e.g. SharePoint links), or a descriptive message for embedded item attachments. Omit accountId/mailbox to use the first configured account and mailbox.', DownloadAttachmentSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('download_attachment', { accountId: resolved.accountId, mailbox: resolved.mailbox });
13
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
14
+ const token = await auth.getAccessToken(resolved.accountId);
15
+ const client = createGraphClient(token);
16
+ const result = await downloadAttachment(client, resolved.mailbox, params.messageId, params.attachmentId);
17
+ switch (result.kind) {
18
+ case 'file':
19
+ if (result.mimeType.startsWith('image/')) {
20
+ return {
21
+ content: [{ type: 'image', data: result.contentBytes, mimeType: result.mimeType }],
22
+ };
23
+ }
24
+ return {
25
+ content: [{
26
+ type: 'text',
27
+ text: JSON.stringify({ fileName: result.name, mimeType: result.mimeType, encoding: 'base64', data: result.contentBytes }, null, 2),
28
+ }],
29
+ };
30
+ case 'reference':
31
+ return { content: [{ type: 'text', text: result.previewUrl }] };
32
+ case 'item':
33
+ return {
34
+ content: [{ type: 'text', text: `itemAttachment: "${result.name}" — embedded Outlook item, not downloadable as a file` }],
35
+ };
36
+ }
37
+ }
38
+ catch (err) {
39
+ logger.error('download_attachment failed', { accountId: params.accountId, mailbox: params.mailbox });
40
+ return errorResponse(err);
41
+ }
42
+ });
43
+ }
@@ -0,0 +1,25 @@
1
+ import { GetMessageSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { getMessage } from '../../graph/email.js';
4
+ import { assertMailboxConfigured } 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
+ import { localizeResponseDates } from '../../utils/datetime.js';
9
+ export function registerGetMessage(server, config, auth) {
10
+ server.tool('get_message', 'Get the full details of a specific email message by ID. Set includeBody to receive the message body, includeAttachments to expand attachment metadata inline.', GetMessageSchema.shape, async (params) => {
11
+ try {
12
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
13
+ logger.info('get_message', { accountId: resolved.accountId, mailbox: resolved.mailbox });
14
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
15
+ const token = await auth.getAccessToken(resolved.accountId);
16
+ const client = createGraphClient(token);
17
+ const result = await getMessage(client, resolved.mailbox, params.messageId, params.includeBody, params.includeAttachments, params.includeInternetMessageHeaders);
18
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
19
+ }
20
+ catch (err) {
21
+ logger.error('get_message failed', { accountId: params.accountId, mailbox: params.mailbox ?? 'default' });
22
+ return errorResponse(err);
23
+ }
24
+ });
25
+ }
@@ -0,0 +1,26 @@
1
+ import { ListFoldersSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listFolders } from '../../graph/email.js';
4
+ import { assertMailboxConfigured } 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 registerListFolders(server, config, auth) {
9
+ server.tool('list_folders', 'List mail folders for a mailbox. Provide parentFolderId to list child folders. Omit accountId/mailbox to use the first configured account and mailbox.', ListFoldersSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('list_folders', { accountId: resolved.accountId, mailbox: resolved.mailbox });
13
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
14
+ const token = await auth.getAccessToken(resolved.accountId);
15
+ const client = createGraphClient(token);
16
+ const result = await listFolders(client, resolved.mailbox, {
17
+ ...(params.parentFolderId !== undefined && { parentFolderId: params.parentFolderId }),
18
+ });
19
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
20
+ }
21
+ catch (err) {
22
+ logger.error('list_folders failed', { accountId: params.accountId, mailbox: params.mailbox });
23
+ return errorResponse(err);
24
+ }
25
+ });
26
+ }
@@ -0,0 +1,30 @@
1
+ import { ListMailboxesSchema } from '../schemas.js';
2
+ import { logger } from '../../utils/logger.js';
3
+ export function registerListMailboxes(server, config) {
4
+ server.tool('list_mailboxes', 'List all configured accounts and their mailboxes, including read-only status. ' +
5
+ 'The isDefault field indicates which account and mailbox will be targeted when ' +
6
+ 'accountId or mailbox are omitted from other tool calls. ' +
7
+ 'Default is determined by position in the config file — first account, first mailbox.', ListMailboxesSchema.shape, async (params) => {
8
+ logger.info('list_mailboxes', { accountId: params.accountId });
9
+ // Default is always the global first account / first mailbox in each account,
10
+ // regardless of any accountId filter applied to the result set.
11
+ const defaultAccountId = config.accounts[0]?.id;
12
+ const accounts = params.accountId
13
+ ? config.accounts.filter((a) => a.id === params.accountId)
14
+ : config.accounts;
15
+ const result = accounts.map((a) => ({
16
+ id: a.id,
17
+ displayName: a.displayName,
18
+ isDefault: a.id === defaultAccountId,
19
+ mailboxes: a.mailboxes.map((m, idx) => ({
20
+ email: m.email,
21
+ displayName: m.displayName,
22
+ readonly: m.readonly,
23
+ isDefault: idx === 0,
24
+ })),
25
+ }));
26
+ return {
27
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
28
+ };
29
+ });
30
+ }
@@ -0,0 +1,26 @@
1
+ import { ListMessageAttachmentsSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listAttachments } from '../../graph/attachments.js';
4
+ import { assertMailboxConfigured } 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 registerListMessageAttachments(server, config, auth) {
9
+ server.tool('list_message_attachments', 'List all attachments on a specific email message. Returns metadata for file, item, and reference attachments. Use download_attachment to retrieve file content. Omit accountId/mailbox to use the first configured account and mailbox.', ListMessageAttachmentsSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('list_message_attachments', { accountId: resolved.accountId, mailbox: resolved.mailbox });
13
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
14
+ const token = await auth.getAccessToken(resolved.accountId);
15
+ const client = createGraphClient(token);
16
+ const attachments = await listAttachments(client, resolved.mailbox, params.messageId);
17
+ return {
18
+ content: [{ type: 'text', text: JSON.stringify({ value: attachments }, null, 2) }],
19
+ };
20
+ }
21
+ catch (err) {
22
+ logger.error('list_message_attachments failed', { accountId: params.accountId, mailbox: params.mailbox });
23
+ return errorResponse(err);
24
+ }
25
+ });
26
+ }
@@ -0,0 +1,50 @@
1
+ import { ListMessagesSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { listMessages } from '../../graph/email.js';
4
+ import { assertMailboxConfigured } from '../../middleware/readonlyGuard.js';
5
+ import { errorResponse, ToolError } from '../../utils/errors.js';
6
+ import { logger } from '../../utils/logger.js';
7
+ import { resolveSelect, SelectValidationError, MESSAGE_SELECT_FIELDS, MESSAGE_SELECT_DEFAULT } from '../../utils/selectFields.js';
8
+ import { resolveMailbox } from '../../utils/resolveMailbox.js';
9
+ import { toUtcIso, localizeResponseDates } from '../../utils/datetime.js';
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) => {
12
+ try {
13
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
14
+ logger.info('list_messages', {
15
+ accountId: resolved.accountId,
16
+ mailbox: resolved.mailbox,
17
+ folderId: params.folderId,
18
+ maxResults: params.maxResults,
19
+ });
20
+ assertMailboxConfigured(config, resolved.accountId, resolved.mailbox);
21
+ let select;
22
+ try {
23
+ select = resolveSelect(params.select, MESSAGE_SELECT_FIELDS, MESSAGE_SELECT_DEFAULT);
24
+ }
25
+ catch (err) {
26
+ if (err instanceof SelectValidationError) {
27
+ return errorResponse(new ToolError(err.message, 'INVALID_SELECT_FIELD'));
28
+ }
29
+ throw err;
30
+ }
31
+ const token = await auth.getAccessToken(resolved.accountId);
32
+ const client = createGraphClient(token);
33
+ const result = await listMessages(client, resolved.mailbox, {
34
+ folderId: params.folderId,
35
+ maxResults: params.maxResults,
36
+ select,
37
+ ...(params.startDate !== undefined && { startDate: toUtcIso(params.startDate) }),
38
+ ...(params.endDate !== undefined && { endDate: toUtcIso(params.endDate) }),
39
+ ...(params.subject !== undefined && { subject: params.subject }),
40
+ ...(params.bodySearch !== undefined && { bodySearch: params.bodySearch }),
41
+ ...(params.sender !== undefined && { sender: params.sender }),
42
+ });
43
+ return { content: [{ type: 'text', text: JSON.stringify(localizeResponseDates(result), null, 2) }] };
44
+ }
45
+ catch (err) {
46
+ logger.error('list_messages failed', { accountId: params.accountId, mailbox: params.mailbox ?? 'default' });
47
+ return errorResponse(err);
48
+ }
49
+ });
50
+ }
@@ -0,0 +1,26 @@
1
+ import { MoveMessageSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { moveMessage } 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 registerMoveMessage(server, config, auth) {
9
+ server.tool('move_message', 'Move an email message to a different folder. Requires the mailbox to be non-readonly. Omit accountId/mailbox to use the first configured account and mailbox.', MoveMessageSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('move_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
+ const result = await moveMessage(client, resolved.mailbox, params.messageId, {
17
+ destinationFolderId: params.destinationFolderId,
18
+ });
19
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
20
+ }
21
+ catch (err) {
22
+ logger.error('move_message failed', { accountId: params.accountId, mailbox: params.mailbox });
23
+ return errorResponse(err);
24
+ }
25
+ });
26
+ }
@@ -0,0 +1,28 @@
1
+ import { ReplyMessageSchema } from '../schemas.js';
2
+ import { createGraphClient } from '../../graph/clientFactory.js';
3
+ import { replyToMessage } 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 registerReplyMessage(server, config, auth) {
9
+ server.tool('reply_message', 'Reply to an email message. Use replyAll to reply to all recipients. Requires the mailbox to be non-readonly. Omit accountId/mailbox to use the first configured account and mailbox.', ReplyMessageSchema.shape, async (params) => {
10
+ try {
11
+ const resolved = resolveMailbox(config, params.accountId, params.mailbox);
12
+ logger.info('reply_message', { accountId: resolved.accountId, mailbox: resolved.mailbox, replyAll: params.replyAll });
13
+ assertWritable(config, resolved.accountId, resolved.mailbox);
14
+ const token = await auth.getAccessToken(resolved.accountId);
15
+ const client = createGraphClient(token);
16
+ await replyToMessage(client, resolved.mailbox, params.messageId, {
17
+ body: params.body,
18
+ bodyType: params.bodyType,
19
+ replyAll: params.replyAll,
20
+ });
21
+ return { content: [{ type: 'text', text: 'Reply sent successfully.' }] };
22
+ }
23
+ catch (err) {
24
+ logger.error('reply_message failed', { accountId: params.accountId, mailbox: params.mailbox });
25
+ return errorResponse(err);
26
+ }
27
+ });
28
+ }