@chrischall/office-outlook-mcp 0.4.0 → 0.5.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/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +3 -3
- package/README.md +74 -19
- package/dist/bundle.js +1384 -211
- package/dist/client.js +29 -9
- package/dist/timezone.js +32 -3
- package/dist/tools/_invite.js +24 -0
- package/dist/tools/_paging.js +9 -2
- package/dist/tools/calendar.js +58 -37
- package/dist/tools/directory.js +36 -31
- package/dist/tools/healthcheck.js +4 -3
- package/dist/tools/mail.js +310 -25
- package/dist/tools/writes.js +579 -28
- package/dist/version.js +1 -1
- package/dist/view.js +44 -7
- package/mint.yaml +3 -2
- package/package.json +2 -2
- package/server.json +15 -3
- package/skills/outlook-fpx/references/outlook-env.sh +2 -2
package/dist/tools/mail.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { minifiedResult, resolveView, viewParam, McpToolError } from '@chrischall/mcp-utils';
|
|
3
|
-
import { compactFolder, compactMessage, fullMessage, projectCollection, } from '../view.js';
|
|
2
|
+
import { imageResult, mapWithConcurrency, minifiedResult, resolveView, viewParam, McpToolError, } from '@chrischall/mcp-utils';
|
|
3
|
+
import { addr, addrs, cappedRecipients, compactFolder, compactMessage, fullMessage, projectCollection, VIEWS, } from '../view.js';
|
|
4
|
+
import { EVENT_EXPAND, INVITE_GONE, MEETING_MESSAGE_TYPE, resolvedEvent } from './_invite.js';
|
|
4
5
|
import { fetchPage, nextLinkParam, plainCollection } from './_paging.js';
|
|
5
6
|
import { mailboxUntrusted, UNTRUSTED_DESCRIPTION_SUFFIX } from './_untrusted.js';
|
|
6
|
-
export const VIEWS = ['compact', 'full', 'raw'];
|
|
7
7
|
/**
|
|
8
8
|
* Well-known folder names the API accepts wherever a folder id is taken.
|
|
9
9
|
* All eight verified present on a live mailbox 2026-09-20.
|
|
@@ -20,40 +20,159 @@ const WELL_KNOWN = [
|
|
|
20
20
|
];
|
|
21
21
|
/** Fields worth listing. Anything not here costs bytes on every row. */
|
|
22
22
|
const LIST_SELECT = 'Id,Subject,From,ToRecipients,ReceivedDateTime,IsRead,HasAttachments,BodyPreview';
|
|
23
|
-
function qs(params) {
|
|
24
|
-
const parts = [];
|
|
25
|
-
for (const [k, v] of Object.entries(params)) {
|
|
26
|
-
if (v === undefined || v === '')
|
|
27
|
-
continue;
|
|
28
|
-
parts.push(`${k}=${encodeURIComponent(String(v))}`);
|
|
29
|
-
}
|
|
30
|
-
return parts.length ? `?${parts.join('&')}` : '';
|
|
31
|
-
}
|
|
32
23
|
/** `inbox` etc. pass through; anything else is treated as an opaque folder id. */
|
|
33
24
|
function folderSegment(folder) {
|
|
34
25
|
return encodeURIComponent(folder);
|
|
35
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Fields for the triage listing. `MeetingMessageType` exists only on the
|
|
29
|
+
* derived EventMessage type, so it is selected with the type cast — the same
|
|
30
|
+
* form the `$expand` below uses. A plain Message row simply omits it.
|
|
31
|
+
*/
|
|
32
|
+
const UNREAD_SELECT = [
|
|
33
|
+
'Id',
|
|
34
|
+
'Subject',
|
|
35
|
+
'From',
|
|
36
|
+
'ToRecipients',
|
|
37
|
+
'CcRecipients',
|
|
38
|
+
'ReceivedDateTime',
|
|
39
|
+
'Importance',
|
|
40
|
+
'HasAttachments',
|
|
41
|
+
'Categories',
|
|
42
|
+
'Flag',
|
|
43
|
+
'ConversationId',
|
|
44
|
+
MEETING_MESSAGE_TYPE,
|
|
45
|
+
].join(',');
|
|
46
|
+
/** Bodies (and invite events) fetched in parallel, bounded so a 50-row batch cannot burst. */
|
|
47
|
+
const BODY_CONCURRENCY = 4;
|
|
48
|
+
/**
|
|
49
|
+
* Sort a row into what an agent does with it. `MeetingMessageType` decides;
|
|
50
|
+
* an EventMessage that arrives without it (a shape we have not seen, but the
|
|
51
|
+
* type name is all that is left) falls back to its `@odata.type`, so an
|
|
52
|
+
* invite never silently reads as plain mail.
|
|
53
|
+
*/
|
|
54
|
+
function triageKind(m) {
|
|
55
|
+
switch (m.MeetingMessageType) {
|
|
56
|
+
case 'MeetingRequest':
|
|
57
|
+
return 'meetingRequest';
|
|
58
|
+
case 'MeetingCancelled':
|
|
59
|
+
return 'meetingCancelled';
|
|
60
|
+
case 'MeetingAccepted':
|
|
61
|
+
case 'MeetingTenativelyAccepted': // sic — Outlook's spelling
|
|
62
|
+
case 'MeetingTentativelyAccepted':
|
|
63
|
+
case 'MeetingDeclined':
|
|
64
|
+
return 'meetingResponse';
|
|
65
|
+
}
|
|
66
|
+
const type = m['@odata.type'] ?? '';
|
|
67
|
+
if (!type.includes('EventMessage'))
|
|
68
|
+
return 'mail';
|
|
69
|
+
if (/Request$/.test(type))
|
|
70
|
+
return 'meetingRequest';
|
|
71
|
+
if (/Cancel/.test(type))
|
|
72
|
+
return 'meetingCancelled';
|
|
73
|
+
return 'meetingResponse';
|
|
74
|
+
}
|
|
75
|
+
function triageEvent(e) {
|
|
76
|
+
return stripUndefined({
|
|
77
|
+
id: e.Id,
|
|
78
|
+
subject: e.Subject,
|
|
79
|
+
start: e.Start?.DateTime,
|
|
80
|
+
end: e.End?.DateTime,
|
|
81
|
+
timeZone: e.Start?.TimeZone,
|
|
82
|
+
location: e.Location?.DisplayName || undefined,
|
|
83
|
+
organizer: addr(e.Organizer),
|
|
84
|
+
responseStatus: e.ResponseStatus?.Response,
|
|
85
|
+
isCancelled: e.IsCancelled,
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** Set on a request/cancellation whose event did not come back with it. */
|
|
89
|
+
const INVITE_UNRESOLVED_HINT = `This invite's ${INVITE_GONE}.`;
|
|
90
|
+
/**
|
|
91
|
+
* `text` cut to at most `max` UTF-16 units, never between the halves of a
|
|
92
|
+
* surrogate pair (which would leave a lone, unprintable half at the end).
|
|
93
|
+
*/
|
|
94
|
+
function truncateChars(text, max) {
|
|
95
|
+
const end = /[\uD800-\uDBFF]/.test(text.charAt(max - 1)) ? max - 1 : max;
|
|
96
|
+
return text.slice(0, end);
|
|
97
|
+
}
|
|
98
|
+
function stripUndefined(o) {
|
|
99
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
|
|
100
|
+
}
|
|
101
|
+
/** Metadata probe for one attachment: never the bytes. */
|
|
102
|
+
const ATTACHMENT_META_SELECT = 'Id,Name,ContentType,Size,IsInline';
|
|
103
|
+
/** Above this an attachment is never inlined, whatever its type (base64 inflates it ~4/3 again). */
|
|
104
|
+
const MAX_INLINE_BYTES = 5 * 1024 * 1024;
|
|
105
|
+
/** Decoded text is cut here; a longer file is marked `textTruncated`. */
|
|
106
|
+
const MAX_TEXT_BYTES = 200 * 1024;
|
|
107
|
+
/**
|
|
108
|
+
* Types worth decoding to text. Senders often label a calendar or CSV file
|
|
109
|
+
* `application/octet-stream`, so the file extension is consulted as well.
|
|
110
|
+
*/
|
|
111
|
+
const TEXT_TYPE = /^text\/|^application\/(json|xml|csv|ics|calendar)\b|\+(json|xml)$/i;
|
|
112
|
+
const TEXT_EXT = /\.(txt|csv|tsv|json|xml|ics|md|log|html?)$/i;
|
|
113
|
+
function attachmentKind(a) {
|
|
114
|
+
const type = a['@odata.type'] ?? '';
|
|
115
|
+
if (/ItemAttachment$/.test(type))
|
|
116
|
+
return 'item';
|
|
117
|
+
if (/ReferenceAttachment$/.test(type))
|
|
118
|
+
return 'reference';
|
|
119
|
+
return 'file';
|
|
120
|
+
}
|
|
121
|
+
/** `image/*` renders as MCP image content; SVG is markup, so it reads as text instead. */
|
|
122
|
+
function isImage(contentType) {
|
|
123
|
+
return /^image\//i.test(contentType) && !/svg/i.test(contentType);
|
|
124
|
+
}
|
|
125
|
+
function isText(contentType, name) {
|
|
126
|
+
return TEXT_TYPE.test(contentType) || /svg/i.test(contentType) || TEXT_EXT.test(name);
|
|
127
|
+
}
|
|
128
|
+
/** Decoded size of a base64 string, without decoding it (an upper bound if it has stray characters). */
|
|
129
|
+
function base64DecodedLength(b64) {
|
|
130
|
+
const padding = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;
|
|
131
|
+
return Math.floor((b64.length * 3) / 4) - padding;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The largest cut at or below `max` that does not split a UTF-8 character:
|
|
135
|
+
* back off while the byte at the cut is a continuation byte (10xxxxxx).
|
|
136
|
+
*/
|
|
137
|
+
function utf8Boundary(buf, max) {
|
|
138
|
+
if (buf.length <= max)
|
|
139
|
+
return buf.length;
|
|
140
|
+
let end = max;
|
|
141
|
+
while (end > 0 && (buf[end] & 0xc0) === 0x80)
|
|
142
|
+
end--;
|
|
143
|
+
return end;
|
|
144
|
+
}
|
|
145
|
+
/** `ReceivedDateTime ge` literal: OData wants it unquoted, and seconds are precision enough. */
|
|
146
|
+
function sinceLiteral(hours) {
|
|
147
|
+
return new Date(Date.now() - hours * 3_600_000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
148
|
+
}
|
|
36
149
|
export function registerMailTools(server, client) {
|
|
37
150
|
server.registerTool('outlook_list_folders', {
|
|
38
151
|
description: 'List mail folders with unread and total counts. Use this to discover folder ids before listing messages; the well-known names (' +
|
|
39
152
|
WELL_KNOWN.join(', ') +
|
|
40
|
-
') can be used directly without a lookup.',
|
|
41
|
-
annotations: { readOnlyHint: true },
|
|
153
|
+
') can be used directly without a lookup. Lists ONE level: top-level folders by default, or the child folders of `parent`. A folder with `Children` > 0 has subfolders — list them with `parent` set to its Id.',
|
|
154
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
42
155
|
inputSchema: z.object({
|
|
43
156
|
view: viewParam(VIEWS),
|
|
157
|
+
parent: z
|
|
158
|
+
.string()
|
|
159
|
+
.min(1)
|
|
160
|
+
.optional()
|
|
161
|
+
.describe('List the child folders of this folder (id or well-known name). Omit for the top level.'),
|
|
44
162
|
limit: z.number().int().min(1).max(200).optional().describe('Max folders (default 50)'),
|
|
45
163
|
nextLink: nextLinkParam,
|
|
46
164
|
}),
|
|
47
|
-
}, async ({ view, limit, nextLink }) => {
|
|
48
|
-
const
|
|
165
|
+
}, async ({ view, parent, limit, nextLink }) => {
|
|
166
|
+
const base = parent !== undefined ? `/me/mailfolders/${folderSegment(parent)}/childfolders` : '/me/mailfolders';
|
|
167
|
+
const data = await fetchPage(client, nextLink, base, { query: { $top: limit ?? 50 } });
|
|
49
168
|
if (resolveView(view, VIEWS) === 'raw')
|
|
50
169
|
return minifiedResult(data);
|
|
51
170
|
return minifiedResult(projectCollection(data, compactFolder, 'mail folder'));
|
|
52
171
|
});
|
|
53
172
|
server.registerTool('outlook_list_messages', {
|
|
54
|
-
description: "List messages in a folder, newest first. Defaults to the inbox. Use `unreadOnly` for a triage view. Bodies are NOT included — call outlook_get_message for one. Note `search` and `unreadOnly` cannot be combined on a first-page request (the API rejects $search with $filter); pass `search` alone to search the whole mailbox. When following a `nextLink`, both are ignored, so echoing them back is harmless." +
|
|
173
|
+
description: "List messages in a folder, newest first. Defaults to the inbox. Use `unreadOnly` for a triage view. Bodies are NOT included — call outlook_get_message for one. Note `search` and `unreadOnly` cannot be combined on a first-page request (the API rejects $search with $filter); pass `search` alone to search the whole mailbox. When following a `nextLink`, both are ignored, so echoing them back is harmless. Each message's To list (and Cc, in the full view) holds at most 20 addresses; a longer list adds ToCount/ToTruncated (CcCount/CcTruncated) with the full count — pass view:\"raw\" for every address." +
|
|
55
174
|
' ' + UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
56
|
-
annotations: { readOnlyHint: true },
|
|
175
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
57
176
|
inputSchema: z.object({
|
|
58
177
|
view: viewParam(VIEWS),
|
|
59
178
|
folder: z
|
|
@@ -93,16 +212,16 @@ export function registerMailTools(server, client) {
|
|
|
93
212
|
if (unreadOnly === true)
|
|
94
213
|
params.$filter = 'IsRead eq false';
|
|
95
214
|
}
|
|
96
|
-
const data = await fetchPage(client, nextLink,
|
|
215
|
+
const data = await fetchPage(client, nextLink, base, { query: params });
|
|
97
216
|
const v = resolveView(view, VIEWS);
|
|
98
217
|
if (v === 'raw')
|
|
99
218
|
return mailboxUntrusted(data);
|
|
100
219
|
return mailboxUntrusted(projectCollection(data, v === 'full' ? fullMessage : compactMessage, 'message'));
|
|
101
220
|
});
|
|
102
221
|
server.registerTool('outlook_get_message', {
|
|
103
|
-
description: 'Get one message including its body. The body is requested as plain text rather than HTML (measured ~9x smaller and far easier to read); pass view:"raw" to get Outlook\'s untouched record.' +
|
|
222
|
+
description: 'Get one message including its body. The body is requested as plain text rather than HTML (measured ~9x smaller and far easier to read); pass view:"raw" to get Outlook\'s untouched record. To and Cc list at most 20 addresses; a longer list adds ToCount/ToTruncated (CcCount/CcTruncated) with the full count — view:"raw" returns every address.' +
|
|
104
223
|
' ' + UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
105
|
-
annotations: { readOnlyHint: true },
|
|
224
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
106
225
|
inputSchema: z.object({
|
|
107
226
|
view: viewParam(VIEWS),
|
|
108
227
|
id: z.string().min(1).describe('Message Id from outlook_list_messages'),
|
|
@@ -120,17 +239,183 @@ export function registerMailTools(server, client) {
|
|
|
120
239
|
return mailboxUntrusted(data);
|
|
121
240
|
return mailboxUntrusted(v === 'full' ? fullMessage(data) : compactMessage(data));
|
|
122
241
|
});
|
|
242
|
+
server.registerTool('outlook_get_unread', {
|
|
243
|
+
description: 'Triage batch: the unread messages in a folder (default inbox), newest first, each WITH its plain-text body (truncated to `maxBodyChars`) in one call — no follow-up outlook_get_message needed. Every item has a `kind`: "mail", "meetingRequest", "meetingCancelled" or "meetingResponse" (a reply to an invite you sent). Requests and cancellations also carry `event` (id, time, organizer, your current `responseStatus`) so the invite can be answered by its event id (when the meeting is no longer on your calendar — already declined, cancelled or deleted — the item has a `hint` instead and there is nothing to respond to). `to`/`cc` list at most 20 addresses; a longer list adds `toCount`/`ccCount` and `toTruncated`/`ccTruncated`. This does NOT mark anything read. Processing loop: read the batch → act on each item (reply, respond to the invite, file, flag — or leave it) → call outlook_mark_read on the ids you handled, so the next call returns only what is still new. Follow `nextLink` for more.' +
|
|
244
|
+
' ' + UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
245
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
246
|
+
inputSchema: z.object({
|
|
247
|
+
folder: z.string().min(1).optional().describe('Folder id or well-known name (default "inbox")'),
|
|
248
|
+
limit: z.number().int().min(1).max(50).optional().describe('Max messages (default 25, max 50)'),
|
|
249
|
+
sinceHours: z
|
|
250
|
+
.number()
|
|
251
|
+
.positive()
|
|
252
|
+
.max(24 * 365)
|
|
253
|
+
.optional()
|
|
254
|
+
.describe('Only mail received in the last N hours'),
|
|
255
|
+
includeBody: z
|
|
256
|
+
.boolean()
|
|
257
|
+
.optional()
|
|
258
|
+
.describe('Fetch each plain-text body (default true). Invite events are resolved either way.'),
|
|
259
|
+
maxBodyChars: z
|
|
260
|
+
.number()
|
|
261
|
+
.int()
|
|
262
|
+
.min(100)
|
|
263
|
+
.max(100_000)
|
|
264
|
+
.optional()
|
|
265
|
+
.describe('Truncate each body to this many characters (default 4000); `bodyTruncated` marks a cut'),
|
|
266
|
+
nextLink: nextLinkParam,
|
|
267
|
+
}),
|
|
268
|
+
}, async ({ folder, limit, sinceHours, includeBody, maxBodyChars, nextLink }) => {
|
|
269
|
+
// Outlook rejects a $filter that does not lead with the $orderby
|
|
270
|
+
// property ("InefficientFilter"), so the date bound goes first.
|
|
271
|
+
const filter = [
|
|
272
|
+
sinceHours !== undefined ? `ReceivedDateTime ge ${sinceLiteral(sinceHours)}` : undefined,
|
|
273
|
+
'IsRead eq false',
|
|
274
|
+
]
|
|
275
|
+
.filter((c) => c !== undefined)
|
|
276
|
+
.join(' and ');
|
|
277
|
+
const data = await fetchPage(client, nextLink, `/me/mailfolders/${folderSegment(folder ?? 'inbox')}/messages`, {
|
|
278
|
+
query: {
|
|
279
|
+
$top: limit ?? 25,
|
|
280
|
+
$select: UNREAD_SELECT,
|
|
281
|
+
$filter: filter,
|
|
282
|
+
$orderby: 'ReceivedDateTime desc',
|
|
283
|
+
},
|
|
284
|
+
});
|
|
285
|
+
const rows = Array.isArray(data?.value) ? data.value : [];
|
|
286
|
+
const wantBody = includeBody !== false;
|
|
287
|
+
const cap = maxBodyChars ?? 4000;
|
|
288
|
+
const items = await mapWithConcurrency(rows, BODY_CONCURRENCY, async (m) => {
|
|
289
|
+
const kind = triageKind(m);
|
|
290
|
+
const item = stripUndefined({
|
|
291
|
+
id: m.Id,
|
|
292
|
+
kind,
|
|
293
|
+
receivedAt: m.ReceivedDateTime,
|
|
294
|
+
from: addr(m.From ?? m.Sender),
|
|
295
|
+
...cappedRecipients('to', addrs(m.ToRecipients)),
|
|
296
|
+
...cappedRecipients('cc', addrs(m.CcRecipients)),
|
|
297
|
+
subject: m.Subject,
|
|
298
|
+
importance: m.Importance,
|
|
299
|
+
hasAttachments: m.HasAttachments || undefined,
|
|
300
|
+
categories: m.Categories?.length ? m.Categories : undefined,
|
|
301
|
+
flag: m.Flag?.FlagStatus,
|
|
302
|
+
conversationId: m.ConversationId,
|
|
303
|
+
});
|
|
304
|
+
// A response to an invite you sent has no event of yours to act on.
|
|
305
|
+
const wantEvent = kind === 'meetingRequest' || kind === 'meetingCancelled';
|
|
306
|
+
if ((!wantBody && !wantEvent) || m.Id === undefined)
|
|
307
|
+
return item;
|
|
308
|
+
try {
|
|
309
|
+
const one = await client.get(`/me/messages/${encodeURIComponent(m.Id)}`, {
|
|
310
|
+
text: wantBody,
|
|
311
|
+
query: {
|
|
312
|
+
$select: wantBody ? 'Id,Body' : 'Id',
|
|
313
|
+
$expand: wantEvent ? EVENT_EXPAND : undefined,
|
|
314
|
+
},
|
|
315
|
+
});
|
|
316
|
+
if (wantBody) {
|
|
317
|
+
const text = (one.Body?.Content ?? '').trim();
|
|
318
|
+
item.body = text.length > cap ? truncateChars(text, cap) : text;
|
|
319
|
+
if (text.length > cap)
|
|
320
|
+
item.bodyTruncated = true;
|
|
321
|
+
}
|
|
322
|
+
if (wantEvent) {
|
|
323
|
+
const event = resolvedEvent(one.Event);
|
|
324
|
+
if (event)
|
|
325
|
+
item.event = triageEvent(event);
|
|
326
|
+
else
|
|
327
|
+
item.hint = INVITE_UNRESOLVED_HINT;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
catch (e) {
|
|
331
|
+
// One unreadable message must not cost the agent the whole batch.
|
|
332
|
+
item.error = e instanceof Error ? e.message : String(e);
|
|
333
|
+
}
|
|
334
|
+
return item;
|
|
335
|
+
});
|
|
336
|
+
const out = { count: items.length, items };
|
|
337
|
+
const next = data?.['@odata.nextLink'];
|
|
338
|
+
if (next)
|
|
339
|
+
out.nextLink = next;
|
|
340
|
+
return mailboxUntrusted(out);
|
|
341
|
+
});
|
|
123
342
|
server.registerTool('outlook_list_attachments', {
|
|
124
343
|
description: "List a message's attachments (name, size, content type). Metadata only — this deliberately does not download bytes.",
|
|
125
|
-
annotations: { readOnlyHint: true },
|
|
344
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
126
345
|
inputSchema: z.object({
|
|
127
346
|
id: z.string().min(1).describe('Message Id'),
|
|
128
347
|
nextLink: nextLinkParam,
|
|
129
348
|
}),
|
|
130
349
|
}, async ({ id, nextLink }) => {
|
|
131
|
-
const data = await fetchPage(client, nextLink, `/me/messages/${encodeURIComponent(id)}/attachments
|
|
132
|
-
$select: 'Id,Name,Size,ContentType',
|
|
133
|
-
})}`);
|
|
350
|
+
const data = await fetchPage(client, nextLink, `/me/messages/${encodeURIComponent(id)}/attachments`, { query: { $select: 'Id,Name,Size,ContentType' } });
|
|
134
351
|
return minifiedResult(plainCollection(data));
|
|
135
352
|
});
|
|
353
|
+
server.registerTool('outlook_get_attachment', {
|
|
354
|
+
description: "Get one attachment's content (ids from outlook_list_attachments). An image comes back as image content the model can see; a text-like file (text/*, JSON, CSV, XML, .ics) is decoded to `text`, capped at 200 KB (`textTruncated` marks a cut). Any other binary (PDF, Office, archives) and anything over 5 MB is returned as metadata only — its bytes are not inlined. An attached Outlook item (a forwarded email or event) or a cloud-file link has no bytes to return; the result says which." +
|
|
355
|
+
' ' + UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
356
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
357
|
+
inputSchema: z.object({
|
|
358
|
+
messageId: z.string().min(1).describe('Message Id'),
|
|
359
|
+
attachmentId: z.string().min(1).describe('Attachment Id from outlook_list_attachments'),
|
|
360
|
+
}),
|
|
361
|
+
}, async ({ messageId, attachmentId }) => {
|
|
362
|
+
const path = `/me/messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`;
|
|
363
|
+
// Metadata first, so a 25 MB PDF is never downloaded only to be dropped.
|
|
364
|
+
const meta = await client.get(path, { query: { $select: ATTACHMENT_META_SELECT } });
|
|
365
|
+
const kind = attachmentKind(meta);
|
|
366
|
+
const contentType = meta.ContentType ?? '';
|
|
367
|
+
const name = meta.Name ?? '';
|
|
368
|
+
const out = stripUndefined({
|
|
369
|
+
messageId,
|
|
370
|
+
attachmentId,
|
|
371
|
+
name: meta.Name,
|
|
372
|
+
contentType: meta.ContentType ?? undefined,
|
|
373
|
+
size: meta.Size,
|
|
374
|
+
isInline: meta.IsInline || undefined,
|
|
375
|
+
kind,
|
|
376
|
+
inlined: false,
|
|
377
|
+
});
|
|
378
|
+
if (kind === 'item') {
|
|
379
|
+
out.hint =
|
|
380
|
+
'This is an attached Outlook item (an email, event or contact), not a file, so it has no bytes to return. Ask the sender for it, or open the parent message in Outlook.';
|
|
381
|
+
return mailboxUntrusted(out);
|
|
382
|
+
}
|
|
383
|
+
if (kind === 'reference') {
|
|
384
|
+
out.hint =
|
|
385
|
+
'This is a link to a cloud file (OneDrive/SharePoint), not a file stored in the message, so there are no bytes to return.';
|
|
386
|
+
return mailboxUntrusted(out);
|
|
387
|
+
}
|
|
388
|
+
const image = isImage(contentType);
|
|
389
|
+
if (!image && !isText(contentType, name)) {
|
|
390
|
+
out.hint = 'Binary content is not inlined: only images and text-like files are returned. Open it in Outlook to read it.';
|
|
391
|
+
return mailboxUntrusted(out);
|
|
392
|
+
}
|
|
393
|
+
if ((meta.Size ?? 0) > MAX_INLINE_BYTES) {
|
|
394
|
+
out.hint = 'Content is not inlined above 5 MB. Open it in Outlook to read it.';
|
|
395
|
+
return mailboxUntrusted(out);
|
|
396
|
+
}
|
|
397
|
+
const full = await client.get(path);
|
|
398
|
+
const bytes = full.ContentBytes;
|
|
399
|
+
if (typeof bytes !== 'string' || bytes.length === 0) {
|
|
400
|
+
out.hint = 'Outlook returned no content for this attachment.';
|
|
401
|
+
return mailboxUntrusted(out);
|
|
402
|
+
}
|
|
403
|
+
// Size is Outlook's figure for the whole record and can understate the
|
|
404
|
+
// file; the base64 length bounds the real size, so judge it before decoding.
|
|
405
|
+
if (base64DecodedLength(bytes) > MAX_INLINE_BYTES) {
|
|
406
|
+
out.hint = 'Content is not inlined above 5 MB. Open it in Outlook to read it.';
|
|
407
|
+
return mailboxUntrusted(out);
|
|
408
|
+
}
|
|
409
|
+
const buf = Buffer.from(bytes, 'base64');
|
|
410
|
+
out.inlined = true;
|
|
411
|
+
if (image) {
|
|
412
|
+
// The name is the sender's text, so the metadata keeps its envelope; the image follows it.
|
|
413
|
+
const env = mailboxUntrusted(out);
|
|
414
|
+
return { ...env, content: [...env.content, ...imageResult(bytes, contentType).content] };
|
|
415
|
+
}
|
|
416
|
+
out.text = buf.subarray(0, utf8Boundary(buf, MAX_TEXT_BYTES)).toString('utf8');
|
|
417
|
+
if (buf.length > MAX_TEXT_BYTES)
|
|
418
|
+
out.textTruncated = true;
|
|
419
|
+
return mailboxUntrusted(out);
|
|
420
|
+
});
|
|
136
421
|
}
|