@chrischall/microsoft-teams-mcp 0.13.1 → 0.15.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 +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +241 -33
- package/dist/attachments.js +238 -0
- package/dist/auth-fetchproxy.js +42 -7
- package/dist/bridge-scope.js +45 -8
- package/dist/browser-open.js +138 -0
- package/dist/bundle.js +28684 -30653
- package/dist/capture-feedback.js +283 -0
- package/dist/chatsvc.js +132 -7
- package/dist/compose.js +9 -1
- package/dist/file-upload.js +335 -0
- package/dist/index.js +11 -1
- package/dist/model.js +1 -0
- package/dist/presence.js +120 -0
- package/dist/profile.js +182 -0
- package/dist/recap-auth.js +6 -4
- package/dist/recap.js +3 -1
- package/dist/sender-email.js +147 -0
- package/dist/sharepoint-auth.js +196 -29
- package/dist/sharepoint.js +329 -8
- package/dist/substrate-auth.js +8 -7
- package/dist/substrate.js +98 -4
- package/dist/tools/attach.js +167 -0
- package/dist/tools/attachment.js +3 -1
- package/dist/tools/conversation.js +14 -5
- package/dist/tools/edit.js +42 -14
- package/dist/tools/errors.js +10 -11
- package/dist/tools/export.js +30 -3
- package/dist/tools/format.js +29 -6
- package/dist/tools/group-chat.js +349 -33
- package/dist/tools/healthcheck.js +23 -9
- package/dist/tools/mention-check.js +225 -0
- package/dist/tools/people.js +149 -39
- package/dist/tools/profile.js +67 -0
- package/dist/tools/send.js +134 -37
- package/dist/tools/sender-email-arg.js +37 -0
- package/dist/tools/token-status.js +97 -0
- package/dist/tools/unread.js +3 -2
- package/dist/tools/upload-slots.js +51 -0
- package/dist/version.js +1 -1
- package/mint.yaml +19 -0
- package/package.json +4 -1
- package/server.json +30 -2
- package/skills/teams-fpx/references/teams-env.sh +1 -1
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Attachments for `teams_send_message` and `teams_edit_message`: plan them
|
|
3
|
+
* (resolve and vet every file, pick where they go and who gets access) on
|
|
4
|
+
* every call — the preview binds each file's SHA-256, so a file that changed
|
|
5
|
+
* between preview and confirm is refused by the gate — then, only on the
|
|
6
|
+
* confirmed call, upload and share them and hand back the file cards.
|
|
7
|
+
*
|
|
8
|
+
* Never sends without a file: an upload or share failure throws before the
|
|
9
|
+
* message is posted, naming any file already uploaded.
|
|
10
|
+
*/
|
|
11
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
12
|
+
import { blobStoreFromEnv, isHostedEnv } from '@chrischall/mcp-utils/export';
|
|
13
|
+
import { resolveAttachments, MAX_ATTACHMENT_BYTES } from '../attachments.js';
|
|
14
|
+
import { knownSharePointHosts } from '../bridge-scope.js';
|
|
15
|
+
import { channelDestination, filesProperty, oneDriveDestination, } from '../file-upload.js';
|
|
16
|
+
import { oneOnOnePeerMri } from '../model.js';
|
|
17
|
+
const ORGID = /^8:orgid:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
|
18
|
+
function humanSize(n) {
|
|
19
|
+
if (n < 1024)
|
|
20
|
+
return `${n} B`;
|
|
21
|
+
if (n < 1024 * 1024)
|
|
22
|
+
return `${(n / 1024).toFixed(1)} KiB`;
|
|
23
|
+
return `${(n / (1024 * 1024)).toFixed(1)} MiB`;
|
|
24
|
+
}
|
|
25
|
+
function destinationLabel(d, name) {
|
|
26
|
+
return d.kind === 'onedrive' ? `OneDrive (${d.host}) › ${d.folder}/${name}` : `${d.siteUrl} › Shared Documents/${d.folder}/${name}`;
|
|
27
|
+
}
|
|
28
|
+
/** The chat's members other than the user, split into grantable object ids and the rest. */
|
|
29
|
+
async function members(chatsvc, target, me) {
|
|
30
|
+
if (target.kind === 'self' || target.kind === 'channel')
|
|
31
|
+
return { ids: [], others: [] };
|
|
32
|
+
let mris;
|
|
33
|
+
const peer = target.kind === 'oneOnOne' ? oneOnOnePeerMri(target.id, me) : undefined;
|
|
34
|
+
if (peer !== undefined) {
|
|
35
|
+
mris = [peer];
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const thread = await chatsvc.getThread(target.id);
|
|
39
|
+
mris = (thread.members ?? []).map((m) => m.id);
|
|
40
|
+
}
|
|
41
|
+
const ids = [];
|
|
42
|
+
const others = [];
|
|
43
|
+
for (const mri of mris) {
|
|
44
|
+
if (mri.toLowerCase() === me.toLowerCase())
|
|
45
|
+
continue;
|
|
46
|
+
const m = ORGID.exec(mri);
|
|
47
|
+
if (m)
|
|
48
|
+
ids.push(m[1].toLowerCase());
|
|
49
|
+
else
|
|
50
|
+
others.push(mri);
|
|
51
|
+
}
|
|
52
|
+
return { ids: [...new Set(ids)], others };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Resolve and vet the files and decide where they go. Runs on the preview
|
|
56
|
+
* call and again on the confirmed one; uploads nothing.
|
|
57
|
+
*/
|
|
58
|
+
export async function planAttachments(chatsvc, opts, target, items, me) {
|
|
59
|
+
if (opts.files === undefined) {
|
|
60
|
+
throw new McpToolError('This server cannot attach files (no uploader is configured).', { kind: 'unknown' });
|
|
61
|
+
}
|
|
62
|
+
const env = opts.env ?? process.env;
|
|
63
|
+
const files = await resolveAttachments(items, {
|
|
64
|
+
env,
|
|
65
|
+
maxBytes: opts.maxAttachmentBytes ?? MAX_ATTACHMENT_BYTES,
|
|
66
|
+
hosted: isHostedEnv(env),
|
|
67
|
+
store: blobStoreFromEnv(env) ?? null,
|
|
68
|
+
});
|
|
69
|
+
let destination;
|
|
70
|
+
if (target.kind === 'channel') {
|
|
71
|
+
const all = await chatsvc.listConversations();
|
|
72
|
+
const raw = all.find((c) => c.id === target.id) ?? { id: target.id };
|
|
73
|
+
destination = channelDestination(raw, all, target.title);
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
destination = oneDriveDestination(env, knownSharePointHosts(env));
|
|
77
|
+
}
|
|
78
|
+
const { ids, others } = await members(chatsvc, target, me);
|
|
79
|
+
const sharing = target.kind === 'channel'
|
|
80
|
+
? "the team's members (the channel's files folder)"
|
|
81
|
+
: target.kind === 'self'
|
|
82
|
+
? 'no one (your own notes chat)'
|
|
83
|
+
: `${ids.length} chat member${ids.length === 1 ? '' : 's'} (view access, no email)`;
|
|
84
|
+
return {
|
|
85
|
+
files,
|
|
86
|
+
destination,
|
|
87
|
+
shareWith: ids,
|
|
88
|
+
notSharedWith: others,
|
|
89
|
+
preview: {
|
|
90
|
+
attachments: files.map((f) => ({
|
|
91
|
+
name: f.fileName,
|
|
92
|
+
size_bytes: f.sizeBytes,
|
|
93
|
+
size: humanSize(f.sizeBytes),
|
|
94
|
+
type: f.mimeType,
|
|
95
|
+
sha256: f.sha256,
|
|
96
|
+
source: f.source,
|
|
97
|
+
destination: destinationLabel(destination, f.fileName),
|
|
98
|
+
})),
|
|
99
|
+
shared_with: sharing,
|
|
100
|
+
...(others.length > 0
|
|
101
|
+
? { not_shared_with: `${others.join(', ')} — not granted access to the files (not a directory account).` }
|
|
102
|
+
: {}),
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Upload every file and share it — the confirmed call only. Throws (with the
|
|
108
|
+
* files already uploaded named) on the first failure, so the caller never
|
|
109
|
+
* posts a message without its files.
|
|
110
|
+
*/
|
|
111
|
+
export async function deliverAttachments(opts, plan) {
|
|
112
|
+
const uploader = opts.files;
|
|
113
|
+
const done = [];
|
|
114
|
+
try {
|
|
115
|
+
for (const f of plan.files) {
|
|
116
|
+
const up = await uploader.upload(plan.destination, { fileName: f.fileName, mimeType: f.mimeType, bytes: f.bytes });
|
|
117
|
+
done.push(up);
|
|
118
|
+
await uploader.share(up, plan.shareWith);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
const left = done.length > 0
|
|
123
|
+
? ` Already uploaded (not sent, still in ${plan.destination.kind === 'onedrive' ? 'your OneDrive' : 'the channel folder'}): ${done
|
|
124
|
+
.map((u) => `"${u.name}"`)
|
|
125
|
+
.join(', ')}.`
|
|
126
|
+
: '';
|
|
127
|
+
const e = err instanceof McpToolError ? err : new McpToolError(err.message ?? String(err), { kind: 'unknown' });
|
|
128
|
+
throw new McpToolError(`${e.message} The message was NOT sent.${left}`, {
|
|
129
|
+
...(e.kind !== undefined ? { kind: e.kind } : {}),
|
|
130
|
+
...(e.status !== undefined ? { status: e.status } : {}),
|
|
131
|
+
...(e.hint !== undefined ? { hint: e.hint } : {}),
|
|
132
|
+
cause: err,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return done;
|
|
136
|
+
}
|
|
137
|
+
/** The file cards for a message (merged after any it already had). */
|
|
138
|
+
export function mergedFilesProperty(existing, uploaded) {
|
|
139
|
+
let before = [];
|
|
140
|
+
if (typeof existing === 'string') {
|
|
141
|
+
try {
|
|
142
|
+
const p = JSON.parse(existing);
|
|
143
|
+
if (Array.isArray(p))
|
|
144
|
+
before = p;
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
before = [];
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
else if (Array.isArray(existing)) {
|
|
151
|
+
before = existing;
|
|
152
|
+
}
|
|
153
|
+
return JSON.stringify([...before, ...JSON.parse(filesProperty(uploaded))]);
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* After the message is posted: delete blob-store uploads (only when the write
|
|
157
|
+
* is known to have landed — `release`), and say per file what was attached
|
|
158
|
+
* (name, size, link).
|
|
159
|
+
*/
|
|
160
|
+
export async function attachmentResult(plan, uploaded, release = true) {
|
|
161
|
+
const releases = await Promise.all(plan.files.map((f) => (release && f.origin === 'blob' ? f.release().then((r) => ({ key: f.source, ...r })) : undefined)));
|
|
162
|
+
const blob = releases.filter((r) => r !== undefined);
|
|
163
|
+
return {
|
|
164
|
+
attachments: uploaded.map((u) => ({ name: u.name, size_bytes: u.size, ...(u.webUrl ? { url: u.webUrl } : {}) })),
|
|
165
|
+
...(blob.length > 0 ? { blob_uploads: blob } : {}),
|
|
166
|
+
};
|
|
167
|
+
}
|
package/dist/tools/attachment.js
CHANGED
|
@@ -59,7 +59,9 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
|
|
|
59
59
|
'with the reason in conversion_error. ' +
|
|
60
60
|
'The first download may need your Teams tab reloaded to capture a short-lived SharePoint token, which ' +
|
|
61
61
|
'then serves every SharePoint host; a file your account cannot open, or one that could not be fetched, ' +
|
|
62
|
-
'comes back as metadata and its open link instead of failing.
|
|
62
|
+
'comes back as metadata and its open link instead of failing. On a local install, a file on a SharePoint ' +
|
|
63
|
+
'host the browser has not signed in to yet opens its link in a Chrome tab (once per host; the tab is left ' +
|
|
64
|
+
'open) and the download is retried. The caption names the conversation beside ' +
|
|
63
65
|
'its id: title (as teams_list_conversations names it — an untitled group chat by its participants, a 1:1 ' +
|
|
64
66
|
'by the other person) and participants. Does not mark anything read.' +
|
|
65
67
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
@@ -13,6 +13,8 @@ import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage,
|
|
|
13
13
|
import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
|
|
14
14
|
import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
|
|
15
15
|
import { workMeta } from './hints.js';
|
|
16
|
+
import { assertSenderEmail, SENDER_EMAIL_DESCRIPTION, senderEmailArg, senderEmailReport } from './sender-email-arg.js';
|
|
17
|
+
import { withSenderEmails } from '../sender-email.js';
|
|
16
18
|
const MAX_MESSAGES = 500;
|
|
17
19
|
/**
|
|
18
20
|
* Raw messages read before giving up (20 pages of 200). The real bound is the
|
|
@@ -315,18 +317,20 @@ async function readMany(chatsvc, raw, me, conversations, opts) {
|
|
|
315
317
|
errors.sort((a, b) => (order.get(a.conversation) ?? 0) - (order.get(b.conversation) ?? 0));
|
|
316
318
|
return { reads: results, errors };
|
|
317
319
|
}
|
|
318
|
-
export function registerConversationTools(server, { chatsvc }) {
|
|
320
|
+
export function registerConversationTools(server, { chatsvc, substrate }) {
|
|
319
321
|
server.registerTool('teams_list_messages', {
|
|
320
322
|
title: 'Read a Teams chat or channel',
|
|
321
323
|
description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
|
|
322
324
|
'teams_list_conversations / teams_list_channels) or by name, without opening it in ' +
|
|
323
325
|
'Teams. "48:notes" (or the name "notes" / "self") is the user\'s own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, ' +
|
|
324
326
|
'text (never truncated; table cells separated by " | "; lists numbered or bulleted), subject, edited/deleted flags and attachments; ' +
|
|
327
|
+
'senderMri (the sender\'s MRI, 8:orgid:…, to pass to teams_get_profile), ' +
|
|
325
328
|
'a formatted message also carries content_html (its body as sanitised HTML: bold, lists, links, code, quotes, mentions), ' +
|
|
326
329
|
'mentions ([{mri, displayName}], who was @mentioned) and links ([{href, text}]), each absent when there is none; ' +
|
|
327
|
-
'
|
|
330
|
+
'every result has message_count (0 for an empty window, with messages []). A channel returns messages too — ' +
|
|
331
|
+
'flat, roots and replies in time order, each with thread_root_id — AND threads, ' +
|
|
328
332
|
'each root post with its replies. A root older than the window is fetched and marked outside_window: ' +
|
|
329
|
-
'true (it is context, not counted or cursored); up to ' +
|
|
333
|
+
'true (it is context, in threads only: not in messages, counted or cursored); up to ' +
|
|
330
334
|
`${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is ` +
|
|
331
335
|
'{ id, missing: true }. ' +
|
|
332
336
|
'unread_only returns just the messages the user has not read; since stops at a time; ' +
|
|
@@ -362,6 +366,7 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
362
366
|
'with id, title, kind, team, lastActivity and match_reason), hint} and no messages — read again ' +
|
|
363
367
|
'with one candidate\'s id. ' +
|
|
364
368
|
TIME_ZONE_DESCRIPTION +
|
|
369
|
+
SENDER_EMAIL_DESCRIPTION +
|
|
365
370
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
366
371
|
// A write only with mark_read, but a write: it moves the user's read marker (never backwards, so a repeat is a no-op).
|
|
367
372
|
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
@@ -383,11 +388,13 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
383
388
|
tz: tzArg,
|
|
384
389
|
format: formatArg,
|
|
385
390
|
mark_read: markReadArg,
|
|
391
|
+
sender_email: senderEmailArg,
|
|
386
392
|
confirmToken: confirmTokenParam,
|
|
387
393
|
},
|
|
388
|
-
}, async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
394
|
+
}, async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, sender_email, confirmToken }, ctx) => {
|
|
389
395
|
try {
|
|
390
396
|
assertMarkReadFormat(mark_read, format);
|
|
397
|
+
assertSenderEmail(sender_email, format, substrate);
|
|
391
398
|
if (from !== undefined) {
|
|
392
399
|
const clash = since !== undefined ? 'since' : after_message_id !== undefined ? 'after_message_id' : mark_read ? 'mark_read' : undefined;
|
|
393
400
|
if (clash !== undefined) {
|
|
@@ -444,14 +451,16 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
444
451
|
: { marked_read: false }))
|
|
445
452
|
: {}),
|
|
446
453
|
});
|
|
454
|
+
const senders = sender_email && substrate !== undefined ? senderEmailReport(await withSenderEmails(substrate, results)) : {};
|
|
447
455
|
if (Array.isArray(conversation)) {
|
|
448
456
|
return untrustedResult({
|
|
449
457
|
conversations: results,
|
|
450
458
|
...(many.errors.length > 0 ? { errors: many.errors } : {}),
|
|
459
|
+
...senders,
|
|
451
460
|
fetched_at,
|
|
452
461
|
});
|
|
453
462
|
}
|
|
454
|
-
return untrustedResult({ ...results[0], fetched_at });
|
|
463
|
+
return untrustedResult({ ...results[0], ...senders, fetched_at });
|
|
455
464
|
}
|
|
456
465
|
catch (err) {
|
|
457
466
|
// A read can safely hand back the candidates; the write tools keep refusing.
|
package/dist/tools/edit.js
CHANGED
|
@@ -5,9 +5,13 @@ import { htmlToText, isDeleted, SELF_CHAT } from '../model.js';
|
|
|
5
5
|
import { mentionsOf, sanitiseHtml } from '../rich.js';
|
|
6
6
|
import { ownMessage, writeAndReadBack } from './own-message.js';
|
|
7
7
|
import { wrapApiError } from './errors.js';
|
|
8
|
-
import { formatParam, mentionArg, resolveMentions, resolveTarget } from './send.js';
|
|
8
|
+
import { formatParam, mentionArg, once, resolveMentions, resolveTarget, unmatchedNote } from './send.js';
|
|
9
|
+
import { checkMentions, mentionScope } from './mention-check.js';
|
|
10
|
+
import { recentSenders } from './people.js';
|
|
9
11
|
import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
10
12
|
import { workMeta } from './hints.js';
|
|
13
|
+
import { attachmentsParam } from '../attachments.js';
|
|
14
|
+
import { attachmentResult, deliverAttachments, mergedFilesProperty, planAttachments } from './attach.js';
|
|
11
15
|
const TOOL = 'teams_edit_message';
|
|
12
16
|
/** A quote-reply's quote block, as Teams (and `compose.quoteHtml`) put it at the start of the body. */
|
|
13
17
|
const QUOTE_BLOCK = /^\s*(<blockquote\b[^>]*schema\.skype\.com\/Reply[^>]*>[\s\S]*?<\/blockquote\s*>)/i;
|
|
@@ -29,19 +33,22 @@ export function sameBody(a, b) {
|
|
|
29
33
|
const norm = (h) => sanitiseHtml(h).replace(BLOCK_TAG, '$1').trim();
|
|
30
34
|
return norm(a) === norm(b);
|
|
31
35
|
}
|
|
32
|
-
export function registerEditTools(server, { chatsvc }) {
|
|
36
|
+
export function registerEditTools(server, { chatsvc, ...attach }) {
|
|
33
37
|
server.registerTool(TOOL, {
|
|
34
38
|
title: 'Edit a Teams message',
|
|
35
39
|
description: 'Replace the text of one of your own messages in any chat or channel. conversation is an id or name as ' +
|
|
36
40
|
'for teams_list_messages; message_id comes from teams_list_messages and must be a message you sent ' +
|
|
37
41
|
"(someone else's, a deleted one or a system event is refused). text replaces the whole message: plain " +
|
|
38
42
|
'text by default, or Markdown with format "markdown" (as teams_send_message reads it). mentions ' +
|
|
39
|
-
'@-mention people as in teams_send_message
|
|
43
|
+
'@-mention people (or the channel or its team) as in teams_send_message, and the preview checks them the same ' +
|
|
44
|
+
'way: an "@name" no mention covers is listed as unmatched_mentions above the text (not refused), with ' +
|
|
45
|
+
'mentions_summary and, per mention, its type, name and whether the person is in the conversation. A quote-reply keeps its quote. Text that renders exactly as ' +
|
|
40
46
|
'the message already does, mentioning the same people, changes nothing (status "unchanged"). Everyone in the conversation sees the ' +
|
|
41
47
|
'message marked edited. The result says whether reading the message back shows the edit (verified); ' +
|
|
42
48
|
'status "unknown" means Teams did not confirm it and the read-back did not show it — check the message ' +
|
|
43
49
|
`before retrying. conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — ` +
|
|
44
|
-
'use it to try this tool. ' +
|
|
50
|
+
'use it to try this tool. attachments adds files to the message as file cards (kept beside any it already has), ' +
|
|
51
|
+
'uploaded and shared exactly as teams_send_message does; the edit is never made without them. ' +
|
|
45
52
|
CONFIRM_FLOW_SENTENCE +
|
|
46
53
|
' The preview shows the conversation, the current text, the new text and exactly what will replace it. ' +
|
|
47
54
|
CONFIRM_INJECTION_RULE +
|
|
@@ -61,9 +68,10 @@ export function registerEditTools(server, { chatsvc }) {
|
|
|
61
68
|
.describe('The whole new message: plain text (newlines kept, :key: shortcodes become emoji), or Markdown with format "markdown".'),
|
|
62
69
|
format: formatParam,
|
|
63
70
|
mentions: z.array(mentionArg).max(20).optional().describe('People to @-mention in text.'),
|
|
71
|
+
attachments: attachmentsParam,
|
|
64
72
|
confirmToken: confirmTokenParam,
|
|
65
73
|
},
|
|
66
|
-
}, async ({ conversation, message_id, text, format = 'text', mentions, confirmToken }, ctx) => {
|
|
74
|
+
}, async ({ conversation, message_id, text, format = 'text', mentions, attachments, confirmToken }, ctx) => {
|
|
67
75
|
try {
|
|
68
76
|
const me = await chatsvc.meMri();
|
|
69
77
|
const target = await resolveTarget(chatsvc, conversation, me, 'edit a message in');
|
|
@@ -74,15 +82,27 @@ export function registerEditTools(server, { chatsvc }) {
|
|
|
74
82
|
});
|
|
75
83
|
}
|
|
76
84
|
const before = original.content ?? '';
|
|
77
|
-
|
|
85
|
+
// Every file is read, vetted and hashed on BOTH calls; nothing is uploaded here.
|
|
86
|
+
const plan = attachments !== undefined ? await planAttachments(chatsvc, attach, target, attachments, me) : undefined;
|
|
87
|
+
const senders = once(() => recentSenders(chatsvc, target.id));
|
|
88
|
+
const scope = await mentionScope(chatsvc, me, target, mentions ?? []);
|
|
89
|
+
const people = await resolveMentions(chatsvc, target.id, mentions ?? [], { scope, senders });
|
|
78
90
|
const rendered = renderMessageHtml(text, people.map((p) => p.target), format);
|
|
79
91
|
const content = quotePrefix(before) + rendered.html;
|
|
80
92
|
// A mention span names only who it shows, so the people are compared too.
|
|
81
93
|
const mentionedNow = rendered.mentions.map((m) => m.mri.toLowerCase());
|
|
82
94
|
const mentionedBefore = mentionsOf(original.properties?.mentions).map((m) => m.mri.toLowerCase());
|
|
83
|
-
if (sameBody(content, before) && mentionedNow.join('\n') === mentionedBefore.join('\n')) {
|
|
95
|
+
if (plan === undefined && sameBody(content, before) && mentionedNow.join('\n') === mentionedBefore.join('\n')) {
|
|
84
96
|
return untrustedResult({ status: 'unchanged', conversation: target, message_id });
|
|
85
97
|
}
|
|
98
|
+
const checked = await checkMentions(chatsvc, {
|
|
99
|
+
target,
|
|
100
|
+
me,
|
|
101
|
+
text,
|
|
102
|
+
mentions: people.map((p, i) => ({ ...p, name_in_text: mentions[i].name_in_text })),
|
|
103
|
+
scope,
|
|
104
|
+
senders,
|
|
105
|
+
});
|
|
86
106
|
const qtdMsgs = original.properties?.qtdMsgs;
|
|
87
107
|
const body = {
|
|
88
108
|
content,
|
|
@@ -92,6 +112,7 @@ export function registerEditTools(server, { chatsvc }) {
|
|
|
92
112
|
properties: {
|
|
93
113
|
mentions: rendered.mentions.length > 0 ? mentionsProperty(rendered.mentions) : '[]',
|
|
94
114
|
...(typeof qtdMsgs === 'string' && quotePrefix(before) !== '' ? { qtdMsgs } : {}),
|
|
115
|
+
...(plan !== undefined ? { files: mergedFilesProperty(original.properties?.files, []) } : {}),
|
|
95
116
|
},
|
|
96
117
|
};
|
|
97
118
|
const path = `/users/ME/conversations/${encodeURIComponent(target.id)}/messages/${encodeURIComponent(message_id)}`;
|
|
@@ -100,7 +121,9 @@ export function registerEditTools(server, { chatsvc }) {
|
|
|
100
121
|
action: 'chat.edit_message',
|
|
101
122
|
message: 'Review and confirm this edit before it replaces your Teams message:',
|
|
102
123
|
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
103
|
-
summary: `Edit your message ${message_id} in ${target.kind} ${JSON.stringify(target.title)}
|
|
124
|
+
summary: `Edit your message ${message_id} in ${target.kind} ${JSON.stringify(target.title)}` +
|
|
125
|
+
(plan ? `, adding ${plan.files.length} attached file${plan.files.length === 1 ? '' : 's'}` : '') +
|
|
126
|
+
unmatchedNote(checked.unmatched),
|
|
104
127
|
account: me,
|
|
105
128
|
target: `${target.id}/${message_id}`,
|
|
106
129
|
request: { method: 'PUT', path, body },
|
|
@@ -109,20 +132,25 @@ export function registerEditTools(server, { chatsvc }) {
|
|
|
109
132
|
message_id,
|
|
110
133
|
// The user's own text, but a quote-reply's quote is someone else's.
|
|
111
134
|
current_text: untrustedField(htmlToText(before)),
|
|
135
|
+
// Mention warnings sit ABOVE the new text, where they are read first.
|
|
136
|
+
...checked.above,
|
|
112
137
|
text,
|
|
113
138
|
format,
|
|
114
|
-
...(people.length > 0
|
|
115
|
-
|
|
116
|
-
mentions: untrustedField(people.map((p, i) => ({ name_in_text: mentions[i].name_in_text, person: p.person, mri: p.target.mri }))),
|
|
117
|
-
}
|
|
118
|
-
: {}),
|
|
139
|
+
...(people.length > 0 ? { mentions: untrustedField(checked.mentions) } : {}),
|
|
140
|
+
...(plan ? { ...plan.preview, note: 'properties.files gets the new file cards once the files are uploaded.' } : {}),
|
|
119
141
|
},
|
|
120
142
|
confirmToken,
|
|
121
143
|
});
|
|
122
144
|
if (gate)
|
|
123
145
|
return gate;
|
|
146
|
+
// Confirmed: upload and share every file first; any failure throws, so
|
|
147
|
+
// the edit is never made without its files.
|
|
148
|
+
const uploaded = plan ? await deliverAttachments(attach, plan) : [];
|
|
149
|
+
if (uploaded.length > 0)
|
|
150
|
+
body.properties.files = mergedFilesProperty(original.properties?.files, uploaded);
|
|
124
151
|
const { status, ...settled } = await writeAndReadBack(() => chatsvc.editMessage(target.id, message_id, body), () => chatsvc.getMessage(target.id, message_id), (m) => readsAs(m, content), 'edit', 'the new text');
|
|
125
|
-
|
|
152
|
+
const files = plan ? await attachmentResult(plan, uploaded, status === 'done') : {};
|
|
153
|
+
return untrustedResult({ status: status === 'done' ? 'edited' : 'unknown', conversation: target, message_id, ...files, ...settled });
|
|
126
154
|
}
|
|
127
155
|
catch (err) {
|
|
128
156
|
throw wrapApiError(err, 'edit the message');
|
package/dist/tools/errors.js
CHANGED
|
@@ -1,27 +1,26 @@
|
|
|
1
1
|
import { McpToolError } from '@chrischall/mcp-utils';
|
|
2
|
+
import { captureFailure, TokenCaptureError } from '../capture-feedback.js';
|
|
2
3
|
/**
|
|
3
4
|
* Classify a chat-service failure. The client already raises actionable
|
|
4
5
|
* `McpToolError`s (401 after re-capture, 429, 5xx), which pass through as-is;
|
|
5
|
-
* what is left is the token capture, which fails as a
|
|
6
|
-
* `
|
|
6
|
+
* what is left is the token capture, which fails as a `TokenCaptureError` (or,
|
|
7
|
+
* from an older path or a test, a plain `Error` reading "could not capture …").
|
|
8
|
+
* That becomes `captureFailure`'s error: the step that failed, how long it
|
|
9
|
+
* waited, a stable `token_<step>` code, and the one next thing to do — acting
|
|
10
|
+
* WHILE the retry waits, since a capture only sees requests made during it.
|
|
7
11
|
*/
|
|
8
12
|
export function wrapApiError(err, action) {
|
|
9
13
|
if (err instanceof McpToolError)
|
|
10
14
|
return err;
|
|
11
15
|
const message = err instanceof Error ? err.message : String(err);
|
|
12
|
-
|
|
13
|
-
|
|
16
|
+
if (err instanceof TokenCaptureError || /could not capture a .*token/i.test(message)) {
|
|
17
|
+
return captureFailure(err, action);
|
|
18
|
+
}
|
|
19
|
+
// A pairing prompt from anywhere else on the bridge path: approving it is the fix.
|
|
14
20
|
if (/pair code|not granted|not in declared/i.test(message)) {
|
|
15
21
|
return new McpToolError(`The Teams browser bridge is not yet approved: ${message}`, {
|
|
16
22
|
hint: 'Approve the pairing request in the ContextMint Bridge extension popup, then retry.',
|
|
17
23
|
});
|
|
18
24
|
}
|
|
19
|
-
if (/could not capture a Teams token/i.test(message)) {
|
|
20
|
-
return new McpToolError(`Could not get a Teams access token to ${action}.`, {
|
|
21
|
-
hint: 'Open a signed-in teams.cloud.microsoft tab and click into any chat (that is what makes ' +
|
|
22
|
-
'Teams call its chat service, which is where the token is read from), then retry.',
|
|
23
|
-
cause: err,
|
|
24
|
-
});
|
|
25
|
-
}
|
|
26
25
|
return new McpToolError(`Failed to ${action}: ${message}`);
|
|
27
26
|
}
|
package/dist/tools/export.js
CHANGED
|
@@ -53,6 +53,8 @@ import { conversationName, enrichTitles } from './titles.js';
|
|
|
53
53
|
import { resolveTimeZone, tzArg } from './timezone.js';
|
|
54
54
|
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
55
55
|
import { workMeta } from './hints.js';
|
|
56
|
+
import { assertSenderEmail, SENDER_EMAIL_DESCRIPTION, senderEmailArg, senderEmailReport } from './sender-email-arg.js';
|
|
57
|
+
import { withSenderEmails } from '../sender-email.js';
|
|
56
58
|
export const EXPORT_SERVER_NAME = 'microsoft-teams-mcp';
|
|
57
59
|
export const EXPORT_OUTPUT_ENV = 'TEAMS_OUTPUT_DIR';
|
|
58
60
|
export const DEFAULT_MAX_ITEMS = 5000;
|
|
@@ -103,6 +105,7 @@ const storedArgs = z
|
|
|
103
105
|
until: isoTimeArg('until'),
|
|
104
106
|
format: z.enum(EXPORT_FORMATS),
|
|
105
107
|
attachments: z.boolean().optional(),
|
|
108
|
+
sender_email: z.boolean().optional(),
|
|
106
109
|
tz: tzArg,
|
|
107
110
|
})
|
|
108
111
|
.strict();
|
|
@@ -206,8 +209,8 @@ function chatParticipants(titled, messages) {
|
|
|
206
209
|
return out;
|
|
207
210
|
}
|
|
208
211
|
/** Arguments that start an export, which a cursor already carries. */
|
|
209
|
-
const STARTING_ARGS = ['conversations', 'kinds', 'since', 'until', 'format', 'attachments', 'dest', 'tz'];
|
|
210
|
-
async function runExport({ chatsvc, sharepoint }, input, opts) {
|
|
212
|
+
const STARTING_ARGS = ['conversations', 'kinds', 'since', 'until', 'format', 'attachments', 'sender_email', 'dest', 'tz'];
|
|
213
|
+
async function runExport({ chatsvc, sharepoint, substrate }, input, opts) {
|
|
211
214
|
const clock = opts.now ?? Date.now;
|
|
212
215
|
const sleep = opts.sleep ?? realSleep;
|
|
213
216
|
const started = clock();
|
|
@@ -228,6 +231,7 @@ async function runExport({ chatsvc, sharepoint }, input, opts) {
|
|
|
228
231
|
...(input.until !== undefined ? { until: input.until } : {}),
|
|
229
232
|
format: input.format ?? 'jsonl',
|
|
230
233
|
...(input.attachments === true ? { attachments: true } : {}),
|
|
234
|
+
...(input.sender_email === true ? { sender_email: true } : {}),
|
|
231
235
|
...(input.tz !== undefined ? { tz: input.tz } : {}),
|
|
232
236
|
};
|
|
233
237
|
const since = args.since !== undefined ? parseIsoTime(args.since) : undefined;
|
|
@@ -236,6 +240,16 @@ async function runExport({ chatsvc, sharepoint }, input, opts) {
|
|
|
236
240
|
throw new McpToolError('since is after until.', { hint: 'Pass a since at or before until.' });
|
|
237
241
|
}
|
|
238
242
|
const timeZone = resolveTimeZone(args.tz);
|
|
243
|
+
// Markdown renders no sender email, so the lookups (which can hold the call
|
|
244
|
+
// for a token capture) would buy nothing: refuse the pair up front.
|
|
245
|
+
if (args.sender_email === true && args.format === 'markdown') {
|
|
246
|
+
throw new McpToolError('sender_email needs format "jsonl" (the markdown export shows no sender email).', {
|
|
247
|
+
hint: 'Drop sender_email, or export as jsonl.',
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
assertSenderEmail(args.sender_email, 'full', substrate);
|
|
251
|
+
/** What looking up sender emails could not do, across the conversations exported. */
|
|
252
|
+
const senderEmails = {};
|
|
239
253
|
const maxItems = input.max_items ?? DEFAULT_MAX_ITEMS;
|
|
240
254
|
const budgetMs = (input.budget_seconds ?? DEFAULT_BUDGET_SECONDS) * 1000;
|
|
241
255
|
let raw;
|
|
@@ -371,6 +385,14 @@ async function runExport({ chatsvc, sharepoint }, input, opts) {
|
|
|
371
385
|
}
|
|
372
386
|
if (page.length > 0) {
|
|
373
387
|
const normalised = page.map((m) => normaliseMessage(m, me, { timeZone }));
|
|
388
|
+
// After one directory failure the rest of this call goes without, rather than failing again per conversation.
|
|
389
|
+
if (args.sender_email === true && substrate !== undefined && senderEmails.error === undefined) {
|
|
390
|
+
const r = await withSenderEmails(substrate, normalised);
|
|
391
|
+
if (r.error !== undefined)
|
|
392
|
+
senderEmails.error = r.error;
|
|
393
|
+
if (r.unresolved !== undefined)
|
|
394
|
+
senderEmails.unresolved = (senderEmails.unresolved ?? 0) + r.unresolved;
|
|
395
|
+
}
|
|
374
396
|
let messages = normalised;
|
|
375
397
|
if (args.attachments === true) {
|
|
376
398
|
const got = await exportAttachments({ chatsvc, sharepoint }, sink, shortId(id), id, normalised);
|
|
@@ -478,6 +500,7 @@ async function runExport({ chatsvc, sharepoint }, input, opts) {
|
|
|
478
500
|
...(cursor !== undefined ? { cursor } : {}),
|
|
479
501
|
...(errors.length > 0 ? { errors: errors.slice(0, RESULT_ERRORS_CAP) } : {}),
|
|
480
502
|
...(errors.length > RESULT_ERRORS_CAP ? { errors_truncated: errors.length - RESULT_ERRORS_CAP } : {}),
|
|
503
|
+
...senderEmailReport(senderEmails),
|
|
481
504
|
});
|
|
482
505
|
}
|
|
483
506
|
export function registerExportTools(server, deps, opts = {}) {
|
|
@@ -506,7 +529,10 @@ export function registerExportTools(server, deps, opts = {}) {
|
|
|
506
529
|
'With attachments true, inline images and shared files (up to 25 MB) are saved under ' +
|
|
507
530
|
'attachments/<conversation>/<message id>-<name> and each message\'s record lists them by that path ' +
|
|
508
531
|
'relative to the export folder; one that cannot be fetched (a SharePoint file the account cannot ' +
|
|
509
|
-
'open, no token yet, too large) is listed as skipped with the reason, never failing the export.' +
|
|
532
|
+
'open, no token yet, too large) is listed as skipped with the reason, never failing the export. ' +
|
|
533
|
+
'Every JSONL record carries senderMri (the sender\'s MRI).' +
|
|
534
|
+
SENDER_EMAIL_DESCRIPTION +
|
|
535
|
+
' (jsonl only: refused with format "markdown", which shows no email).' +
|
|
510
536
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
511
537
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
512
538
|
_meta: workMeta('other', { aliases: ['export', 'save the chat', 'chat history'] }),
|
|
@@ -531,6 +557,7 @@ export function registerExportTools(server, deps, opts = {}) {
|
|
|
531
557
|
.describe('Also download each message\'s inline images and shared files (up to 25 MB each) into ' +
|
|
532
558
|
'attachments/<conversation>/<message id>-<name>; each record lists them with that relative path, ' +
|
|
533
559
|
'or skipped and why. Default false.'),
|
|
560
|
+
sender_email: senderEmailArg,
|
|
534
561
|
dest: z
|
|
535
562
|
.string()
|
|
536
563
|
.min(1)
|
package/dist/tools/format.js
CHANGED
|
@@ -17,6 +17,11 @@
|
|
|
17
17
|
* summary), or — when it could not be fetched — a `{ id, missing: true }`
|
|
18
18
|
* placeholder (`root_missing`).
|
|
19
19
|
*
|
|
20
|
+
* Every format reports `message_count` (the messages read, never an
|
|
21
|
+
* outside-window root). In full and compact a channel ALSO lists its messages
|
|
22
|
+
* flat, as `messages` (each with `thread_root_id`), beside `threads` — so
|
|
23
|
+
* reading `messages` works the same for a chat and a channel.
|
|
24
|
+
*
|
|
20
25
|
* Every format keeps the conversation's id, and everything else a read reports
|
|
21
26
|
* (unread_count, next_cursor, truncated, …) is the same in all three: the
|
|
22
27
|
* format only changes how the messages are shown, never which were read.
|
|
@@ -31,7 +36,9 @@ export const formatArg = z
|
|
|
31
36
|
'summary: no messages, just per conversation its counts, newest message time and, for a channel, ' +
|
|
32
37
|
'each thread\'s root id, subject, reply count and newest time.');
|
|
33
38
|
/** Shared description text for the `format` argument. */
|
|
34
|
-
export const FORMAT_DESCRIPTION = '
|
|
39
|
+
export const FORMAT_DESCRIPTION = 'In full and compact a channel lists its messages flat (messages, each with thread_root_id) as well as threads; ' +
|
|
40
|
+
'every format has message_count. ' +
|
|
41
|
+
'format "compact" trims each message to id, time, sender and text, and the conversation to id, kind ' +
|
|
35
42
|
'and title; format "summary" returns no messages, only message_count, newest_time and, for a channel, ' +
|
|
36
43
|
'threads of { root_id, subject, reply_count, newest_time } — every format keeps the conversation id. ';
|
|
37
44
|
const NO_ROOTS = new Map();
|
|
@@ -117,10 +124,18 @@ export function formatConversation(summary, format) {
|
|
|
117
124
|
const { id, kind, title, team } = summary;
|
|
118
125
|
return { id, kind, title, ...(team !== undefined ? { team } : {}) };
|
|
119
126
|
}
|
|
127
|
+
/** Which thread a channel message belongs to: its root's id (a root's own id). */
|
|
128
|
+
const withRoot = (m, shown) => ({
|
|
129
|
+
...shown,
|
|
130
|
+
thread_root_id: m.replyTo ?? m.id,
|
|
131
|
+
});
|
|
120
132
|
/**
|
|
121
|
-
* A conversation's oldest-first messages as a result shows them
|
|
122
|
-
*
|
|
123
|
-
*
|
|
133
|
+
* A conversation's oldest-first messages as a result shows them, in full or
|
|
134
|
+
* compact: `message_count` and `messages` for every kind — for a channel the
|
|
135
|
+
* flat list (roots and replies in time order, each with `thread_root_id`) AND
|
|
136
|
+
* its `threads` (with `roots` fetched from outside the window) — or, in
|
|
137
|
+
* summary, just the counts. A root from outside the window is context: it
|
|
138
|
+
* shows in `threads` only, never in `messages` or `message_count`.
|
|
124
139
|
*/
|
|
125
140
|
export function formatBody(kind, messages, format, roots = NO_ROOTS) {
|
|
126
141
|
const channel = kind === 'channel';
|
|
@@ -133,13 +148,21 @@ export function formatBody(kind, messages, format, roots = NO_ROOTS) {
|
|
|
133
148
|
}
|
|
134
149
|
if (format === 'compact') {
|
|
135
150
|
if (!channel)
|
|
136
|
-
return { messages: messages.map(compactMessage) };
|
|
151
|
+
return { message_count: messages.length, messages: messages.map(compactMessage) };
|
|
137
152
|
return {
|
|
153
|
+
message_count: messages.length,
|
|
154
|
+
messages: messages.map((m) => withRoot(m, compactMessage(m))),
|
|
138
155
|
threads: groupThreads(messages, roots).map(({ root, replies }) => ({
|
|
139
156
|
root: compactRoot(root),
|
|
140
157
|
replies: replies.map(compactMessage),
|
|
141
158
|
})),
|
|
142
159
|
};
|
|
143
160
|
}
|
|
144
|
-
|
|
161
|
+
if (!channel)
|
|
162
|
+
return { message_count: messages.length, messages: [...messages] };
|
|
163
|
+
return {
|
|
164
|
+
message_count: messages.length,
|
|
165
|
+
messages: messages.map((m) => withRoot(m, m)),
|
|
166
|
+
threads: groupThreads(messages, roots),
|
|
167
|
+
};
|
|
145
168
|
}
|