@teamnetwork-nz/m365-mcp-server 1.4.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 +18 -2
- package/dist/graph/calendar.js +43 -1
- package/dist/graph/email.js +60 -19
- package/dist/http-server.js +83 -0
- package/dist/index.js +20 -10
- package/dist/tools/calendar/findMeetingTimes.js +21 -0
- package/dist/tools/calendar/getSchedule.js +22 -0
- package/dist/tools/calendar/listEvents.js +21 -4
- package/dist/tools/email/listConversationMessages.js +21 -0
- package/dist/tools/email/listMessages.js +32 -5
- package/dist/tools/registry.js +6 -0
- package/dist/tools/schemas.js +45 -6
- package/dist/utils/datetime.js +32 -2
- package/dist/utils/errors.js +3 -0
- package/dist/utils/selectFields.js +1 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @teamnetwork-nz/m365-mcp-server
|
|
2
2
|
|
|
3
|
+
## Streamable HTTP
|
|
4
|
+
|
|
5
|
+
Set `M365_TRANSPORT=http` to serve stateless MCP at `/mcp`. It binds to `127.0.0.1` by default; remote binding requires `M365_HTTP_BEARER_TOKEN` and `M365_HTTP_ALLOWED_HOSTS`. Optional controls include `M365_HTTP_PORT`, `M365_HTTP_ALLOWED_ORIGINS`, and `M365_HTTP_MAX_BODY_BYTES`; `/health` is available for health checks.
|
|
6
|
+
|
|
3
7
|
A [Model Context Protocol (MCP)](https://modelcontextprotocol.io) server for Microsoft 365 — Email, Calendar, To Do, and SharePoint document libraries — using **app-only (client credentials) authentication** — no user login flows required.
|
|
4
8
|
|
|
5
9
|
Supports multiple accounts, shared mailboxes, per-mailbox read-only access control, folder navigation, date/content filtering, and grant-based SharePoint access control.
|
|
@@ -181,7 +185,8 @@ Operations always target exactly one mailbox per request, either the default or
|
|
|
181
185
|
|---|---|
|
|
182
186
|
| `list_mailboxes` | List configured accounts and mailboxes with read/write status |
|
|
183
187
|
| `list_folders` | List mail folders (top-level or child folders) |
|
|
184
|
-
| `list_messages` |
|
|
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` |
|
|
185
190
|
| `get_message` | Get full message details. Set `includeBody`, `includeAttachments`, or `includeInternetMessageHeaders` as needed |
|
|
186
191
|
| `send_message` | Send an email (non-readonly mailboxes only) |
|
|
187
192
|
| `reply_message` | Reply or reply-all to a message (non-readonly mailboxes only) |
|
|
@@ -194,11 +199,22 @@ Operations always target exactly one mailbox per request, either the default or
|
|
|
194
199
|
| Tool | Description |
|
|
195
200
|
|---|---|
|
|
196
201
|
| `list_calendars` | List calendars for a mailbox |
|
|
197
|
-
| `list_events` |
|
|
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 |
|
|
198
205
|
| `get_event` | Get full event details |
|
|
199
206
|
| `create_event` | Create a new event (non-readonly mailboxes only) |
|
|
200
207
|
| `update_event` | Update an existing event (non-readonly mailboxes only) |
|
|
201
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
|
+
|
|
202
218
|
### To Do
|
|
203
219
|
|
|
204
220
|
| Tool | Description |
|
package/dist/graph/calendar.js
CHANGED
|
@@ -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
|
-
|
|
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');
|
package/dist/graph/email.js
CHANGED
|
@@ -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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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(
|
|
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 =
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
if (params.
|
|
43
|
-
filters.push(`
|
|
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
|
-
|
|
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.
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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 = [
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
|
+
const loopback = new Set(["127.0.0.1", "::1", "localhost"]);
|
|
5
|
+
const send = (res, status, body) => {
|
|
6
|
+
res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(body));
|
|
7
|
+
};
|
|
8
|
+
const error = (res, status, code, message) => send(res, status, { jsonrpc: "2.0", error: { code, message }, id: null });
|
|
9
|
+
const matches = (value, expected) => {
|
|
10
|
+
if (!value?.startsWith("Bearer "))
|
|
11
|
+
return false;
|
|
12
|
+
const supplied = Buffer.from(value.slice(7));
|
|
13
|
+
const wanted = Buffer.from(expected);
|
|
14
|
+
return supplied.length === wanted.length && timingSafeEqual(supplied, wanted);
|
|
15
|
+
};
|
|
16
|
+
const readBody = (req, limit) => new Promise((resolve, reject) => {
|
|
17
|
+
const chunks = [];
|
|
18
|
+
let size = 0;
|
|
19
|
+
let oversized = false;
|
|
20
|
+
req.on("data", (chunk) => { size += chunk.length; oversized ||= size > limit; if (!oversized)
|
|
21
|
+
chunks.push(chunk); });
|
|
22
|
+
req.on("end", () => {
|
|
23
|
+
if (oversized)
|
|
24
|
+
return reject(Object.assign(new Error("Request body too large"), { statusCode: 413 }));
|
|
25
|
+
try {
|
|
26
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
reject(Object.assign(new Error("Invalid JSON body"), { statusCode: 400 }));
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
req.on("error", reject);
|
|
33
|
+
});
|
|
34
|
+
export function validateHttpOptions(o) {
|
|
35
|
+
if (!Number.isInteger(o.port) || o.port < 1 || o.port > 65535)
|
|
36
|
+
throw new Error(`Invalid HTTP port: ${o.port}`);
|
|
37
|
+
if (o.maxBodyBytes !== undefined && (!Number.isInteger(o.maxBodyBytes) || o.maxBodyBytes < 1))
|
|
38
|
+
throw new Error(`Invalid HTTP body limit: ${o.maxBodyBytes}`);
|
|
39
|
+
if (!loopback.has(o.host) && !o.bearerToken)
|
|
40
|
+
throw new Error("A bearer token is required when binding beyond loopback");
|
|
41
|
+
if (!loopback.has(o.host) && !o.allowedHosts?.length)
|
|
42
|
+
throw new Error("HTTP_ALLOWED_HOSTS is required when binding beyond loopback");
|
|
43
|
+
}
|
|
44
|
+
export function createHttpServer(factory, o) {
|
|
45
|
+
validateHttpOptions(o);
|
|
46
|
+
const hosts = new Set(o.allowedHosts?.map(v => v.toLowerCase()));
|
|
47
|
+
const origins = new Set(o.allowedOrigins?.map(v => v.toLowerCase()));
|
|
48
|
+
return http.createServer(async (req, res) => {
|
|
49
|
+
const path = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
50
|
+
if (path === "/health")
|
|
51
|
+
return send(res, 200, { status: "ok", server: o.serverName });
|
|
52
|
+
if (path !== "/mcp")
|
|
53
|
+
return void res.writeHead(404).end();
|
|
54
|
+
if (hosts.size && !hosts.has((req.headers.host ?? "").toLowerCase()))
|
|
55
|
+
return error(res, 403, -32000, "Host not allowed");
|
|
56
|
+
if (req.headers.origin && !origins.has(req.headers.origin.toLowerCase()))
|
|
57
|
+
return error(res, 403, -32000, "Origin not allowed");
|
|
58
|
+
if (o.bearerToken && !matches(req.headers.authorization, o.bearerToken)) {
|
|
59
|
+
res.setHeader("WWW-Authenticate", "Bearer");
|
|
60
|
+
return error(res, 401, -32001, "Unauthorized");
|
|
61
|
+
}
|
|
62
|
+
if (req.method !== "POST") {
|
|
63
|
+
res.setHeader("Allow", "POST");
|
|
64
|
+
return error(res, 405, -32000, "Method not allowed");
|
|
65
|
+
}
|
|
66
|
+
const server = factory();
|
|
67
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
68
|
+
try {
|
|
69
|
+
const body = await readBody(req, o.maxBodyBytes ?? 1048576);
|
|
70
|
+
await server.connect(transport);
|
|
71
|
+
await transport.handleRequest(req, res, body);
|
|
72
|
+
res.once("close", () => { void transport.close(); void server.close(); });
|
|
73
|
+
}
|
|
74
|
+
catch (cause) {
|
|
75
|
+
void transport.close();
|
|
76
|
+
void server.close();
|
|
77
|
+
if (!res.headersSent) {
|
|
78
|
+
const status = cause.statusCode ?? 500;
|
|
79
|
+
error(res, status, status === 400 ? -32700 : -32603, status < 500 ? cause.message : "Internal server error");
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { TokenCache } from './auth/TokenCache.js';
|
|
|
6
6
|
import { AuthManager } from './auth/AuthManager.js';
|
|
7
7
|
import { registerAllTools } from './tools/registry.js';
|
|
8
8
|
import { logger } from './utils/logger.js';
|
|
9
|
+
import { createHttpServer } from './http-server.js';
|
|
9
10
|
async function main() {
|
|
10
11
|
// 1. Load and validate config — aborts if invalid
|
|
11
12
|
const config = loadConfig();
|
|
@@ -14,11 +15,12 @@ async function main() {
|
|
|
14
15
|
const tokenCache = new TokenCache(config);
|
|
15
16
|
const auth = new AuthManager(tokenCache);
|
|
16
17
|
// 3. Create MCP server and register all tools
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
const createConfiguredServer = () => {
|
|
19
|
+
const server = new McpServer({
|
|
20
|
+
name: '@teamnetwork/m365-mcp-server',
|
|
21
|
+
version: '1.6.0',
|
|
22
|
+
}, {
|
|
23
|
+
instructions: `
|
|
22
24
|
Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph API.
|
|
23
25
|
|
|
24
26
|
## Accounts and mailboxes
|
|
@@ -46,12 +48,20 @@ Microsoft 365 MCP server — email, calendar, and To Do via the Microsoft Graph
|
|
|
46
48
|
- Linked resources (list_linked_resources, create_linked_resource, etc.) are external URL attachments on a task — they are not subtasks. Subtasks appear as checklistItems inside the task body.
|
|
47
49
|
- delete_todo_task is permanent and irreversible. Confirm with the user before calling it.
|
|
48
50
|
`.trim(),
|
|
49
|
-
|
|
50
|
-
|
|
51
|
+
});
|
|
52
|
+
registerAllTools(server, config, auth);
|
|
53
|
+
return server;
|
|
54
|
+
};
|
|
51
55
|
// 4. Connect via stdio transport (Claude Desktop / Claude Code)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
56
|
+
if ((process.env['M365_TRANSPORT'] ?? 'stdio') === 'http') {
|
|
57
|
+
const host = process.env['M365_HTTP_HOST'] ?? '127.0.0.1';
|
|
58
|
+
const port = Number.parseInt(process.env['M365_HTTP_PORT'] ?? '3000', 10);
|
|
59
|
+
createHttpServer(createConfiguredServer, { host, port, serverName: '@teamnetwork/m365-mcp-server', bearerToken: process.env['M365_HTTP_BEARER_TOKEN'], allowedHosts: process.env['M365_HTTP_ALLOWED_HOSTS']?.split(',').map(v => v.trim()).filter(Boolean), allowedOrigins: process.env['M365_HTTP_ALLOWED_ORIGINS']?.split(',').map(v => v.trim()).filter(Boolean), maxBodyBytes: Number.parseInt(process.env['M365_HTTP_MAX_BODY_BYTES'] ?? '1048576', 10) }).listen(port, host, () => logger.info(`M365 MCP server listening on ${host}:${port}/mcp`));
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
await createConfiguredServer().connect(new StdioServerTransport());
|
|
63
|
+
logger.info('M365 MCP server running on stdio');
|
|
64
|
+
}
|
|
55
65
|
}
|
|
56
66
|
main().catch((err) => {
|
|
57
67
|
process.stderr.write(`Fatal: ${err.message ?? String(err)}\n`);
|
|
@@ -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', '
|
|
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
|
-
|
|
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', '
|
|
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
|
-
|
|
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
|
-
...
|
|
38
|
-
|
|
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
|
}
|
package/dist/tools/registry.js
CHANGED
|
@@ -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);
|
package/dist/tools/schemas.js
CHANGED
|
@@ -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
|
|
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('
|
|
19
|
-
bodySearch: z.string().optional().describe('Full-text search
|
|
20
|
-
sender: z.string().
|
|
21
|
-
|
|
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'),
|
package/dist/utils/datetime.js
CHANGED
|
@@ -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
|
package/dist/utils/errors.js
CHANGED
|
@@ -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');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamnetwork-nz/m365-mcp-server",
|
|
3
|
-
"version": "1.
|
|
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",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
],
|
|
14
14
|
"scripts": {
|
|
15
15
|
"build": "tsc",
|
|
16
|
+
"test": "npm run build && node --test tests/*.test.mjs",
|
|
16
17
|
"prepare": "npm run build",
|
|
17
18
|
"start": "node dist/index.js",
|
|
18
19
|
"dev": "tsx watch src/index.ts"
|