@chrischall/microsoft-teams-mcp 0.14.0 → 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 +7 -6
- package/dist/browser-open.js +138 -0
- package/dist/bundle.js +6840 -3949
- 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 +42 -21
- package/dist/sharepoint.js +150 -3
- 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
package/dist/tools/group-chat.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, McpToolError, toolAnnotations, WriteOutcomeUnknownError, writeOutcomeStatus, } from '@chrischall/mcp-utils';
|
|
3
3
|
import { UNTITLED_GROUP_TITLE } from '../model.js';
|
|
4
|
+
import { buildSendBody, mentionRanges, mentionsProperty, newClientMessageId, renderMessageHtml, } from '../compose.js';
|
|
4
5
|
import { wrapApiError } from './errors.js';
|
|
5
6
|
import { workMeta } from './hints.js';
|
|
6
|
-
import { knownPeople, resolvePeople } from './people.js';
|
|
7
|
-
import { resolveTarget, SELF_CHAT } from './send.js';
|
|
7
|
+
import { knownPeople, MRI, normaliseName, resolvePeople, } from './people.js';
|
|
8
|
+
import { formatParam, mentionArg, resolveTarget, SELF_CHAT, unmatchedNote } from './send.js';
|
|
9
|
+
import { unmatchedMentions } from './mention-check.js';
|
|
10
|
+
import { THIRD_PARTY_NAMES_NOTE } from './untrusted.js';
|
|
8
11
|
import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
9
12
|
const RENAME = 'teams_rename_chat';
|
|
10
13
|
const ADD = 'teams_add_chat_members';
|
|
@@ -34,15 +37,29 @@ const peopleParam = z
|
|
|
34
37
|
.min(1)
|
|
35
38
|
.max(MAX_PEOPLE)
|
|
36
39
|
.describe(`Who: ${peopleParamText('the other people of your 1:1 chats and recent senders in this chat')}`);
|
|
40
|
+
/**
|
|
41
|
+
* The resolver hook (`people.ts`): ids the caller already looked up elsewhere,
|
|
42
|
+
* so a person not in the user's chats needs no directory search — and so no
|
|
43
|
+
* Substrate token captured from the browser.
|
|
44
|
+
*/
|
|
45
|
+
const idsParam = z
|
|
46
|
+
.record(z.string(), z.string().trim().min(1))
|
|
47
|
+
.optional()
|
|
48
|
+
.describe('Optional ids you already looked up elsewhere (e.g. the Outlook MCP\'s people list), keyed by the exact people ' +
|
|
49
|
+
'entry → an MRI (8:orgid:…) or bare Entra object id. Used for a name not found in your chats, and for an ' +
|
|
50
|
+
'email, BEFORE the directory is searched; one that names someone other than the chat match is refused.');
|
|
37
51
|
/** The description's sentence on naming people; `local` says where a name is matched before the directory. */
|
|
38
52
|
function peopleSentence(local) {
|
|
39
|
-
return ('people are MRIs (8:orgid:…), bare object ids, email addresses, or display names
|
|
40
|
-
`(ignoring case,
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
"
|
|
44
|
-
'
|
|
45
|
-
'
|
|
53
|
+
return ('people are MRIs (8:orgid:…), bare Entra object ids, email addresses, or display names, resolved in this ' +
|
|
54
|
+
`order: an id as given; a name matched (ignoring case, "First Last" or "Last, First") among ${local}; ` +
|
|
55
|
+
'the ids argument (ids you looked up elsewhere, e.g. the Outlook MCP\'s people list — also for an email); ' +
|
|
56
|
+
"and only then the organisation's directory, where the one person with exactly that name is taken (or the " +
|
|
57
|
+
"only suggestion, when the name is whole words of it) and an email must be exactly one person's email or " +
|
|
58
|
+
'UPN. Nothing is guessed: an ambiguous or unknown person refuses the whole call, listing candidates, naming ' +
|
|
59
|
+
'which people DID resolve, with a stable error code (person_ambiguous, person_not_found, ' +
|
|
60
|
+
'directory_unavailable, …). The directory needs the Substrate search token, captured only while the call ' +
|
|
61
|
+
'waits: if it is not held (teams_token_status), the user must run a search in the Teams search box within ' +
|
|
62
|
+
'the window after the call starts — so prefer passing an Entra id or using ids. ');
|
|
46
63
|
}
|
|
47
64
|
const PEOPLE_SENTENCE = peopleSentence("the other person of each of the user's 1:1 chats and the chat's recent senders");
|
|
48
65
|
/** The conversation, refused unless it is a group chat. `doing` words the refusal ("renamed"). */
|
|
@@ -81,10 +98,10 @@ function shown(p) {
|
|
|
81
98
|
* Names are matched among the user's 1:1s and, given `conversationId`, that
|
|
82
99
|
* chat's recent senders; with none (a chat not yet made), the 1:1s only.
|
|
83
100
|
*/
|
|
84
|
-
async function resolveFor(chatsvc, directory, me, conversationId, people) {
|
|
101
|
+
async function resolveFor(chatsvc, directory, me, conversationId, people, ids = {}) {
|
|
85
102
|
const known = await knownPeople(chatsvc, me, conversationId);
|
|
86
103
|
const seen = new Set();
|
|
87
|
-
return (await resolvePeople(people, known, directory)).filter((p) => {
|
|
104
|
+
return (await resolvePeople(people, known, directory, ids)).filter((p) => {
|
|
88
105
|
const key = p.mri.toLowerCase();
|
|
89
106
|
if (seen.has(key))
|
|
90
107
|
return false;
|
|
@@ -153,6 +170,172 @@ async function applyMemberChanges(chatsvc, threadId, people, write, done) {
|
|
|
153
170
|
`${done === 'added' ? 'in the chat is reported as already_member' : 'gone is reported as not_member'} and not written again.`,
|
|
154
171
|
};
|
|
155
172
|
}
|
|
173
|
+
/** Recent messages read back to find the first message by its clientmessageid. */
|
|
174
|
+
const READBACK_MESSAGES = 50;
|
|
175
|
+
/** How long a chat created without its first message is remembered for a send-only retry (24 h). */
|
|
176
|
+
const PENDING_TTL_MS = 24 * 60 * 60 * 1000;
|
|
177
|
+
/**
|
|
178
|
+
* Chats `teams_create_group_chat` created whose first message did not go
|
|
179
|
+
* through, keyed by who is in them and the topic (`pendingKey`). A repeat of
|
|
180
|
+
* the same call then only SENDS, to this conversation id — it never creates a
|
|
181
|
+
* second chat (chats cannot be deleted). Process memory only; cleared once the
|
|
182
|
+
* message is sent, or after a day.
|
|
183
|
+
*/
|
|
184
|
+
const pendingFirstMessages = new Map();
|
|
185
|
+
/** Forget every pending first message (tests). */
|
|
186
|
+
export function resetPendingFirstMessages() {
|
|
187
|
+
pendingFirstMessages.clear();
|
|
188
|
+
}
|
|
189
|
+
function pendingKey(me, mris, topic) {
|
|
190
|
+
return JSON.stringify([me.toLowerCase(), [...mris].map((m) => m.toLowerCase()).sort(), topic ?? '']);
|
|
191
|
+
}
|
|
192
|
+
function pendingFor(key) {
|
|
193
|
+
const p = pendingFirstMessages.get(key);
|
|
194
|
+
if (p !== undefined && Date.now() - p.at > PENDING_TTL_MS) {
|
|
195
|
+
pendingFirstMessages.delete(key);
|
|
196
|
+
return undefined;
|
|
197
|
+
}
|
|
198
|
+
return p;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Each mention resolved against the NEW chat's members (never recent senders —
|
|
202
|
+
* there are none yet): an MRI that is a member, else a member whose name (or
|
|
203
|
+
* the people entry that named them) equals `person` (normalised, "Last, First"
|
|
204
|
+
* either way), else contains it. None or several is refused with a stable code.
|
|
205
|
+
*/
|
|
206
|
+
function resolveMemberMentions(mentions, members) {
|
|
207
|
+
const list = (ms) => ms.map((m) => `${JSON.stringify(m.name ?? m.person)} (${m.mri})`).join('; ');
|
|
208
|
+
return mentions.map(({ name_in_text, person }) => {
|
|
209
|
+
const p = person.trim();
|
|
210
|
+
let found;
|
|
211
|
+
if (MRI.test(p)) {
|
|
212
|
+
found = members.filter((m) => m.mri.toLowerCase() === p.toLowerCase());
|
|
213
|
+
}
|
|
214
|
+
else {
|
|
215
|
+
const q = normaliseName(p);
|
|
216
|
+
const names = (m) => [m.name, m.person].filter((n) => n !== undefined).map(normaliseName);
|
|
217
|
+
const exact = members.filter((m) => names(m).includes(q));
|
|
218
|
+
found = exact.length > 0 ? exact : members.filter((m) => names(m).some((n) => n.includes(q)));
|
|
219
|
+
}
|
|
220
|
+
if (found.length === 1) {
|
|
221
|
+
const m = found[0];
|
|
222
|
+
return { name_in_text, person, ...(m.name !== undefined ? { name: m.name } : {}), mri: m.mri };
|
|
223
|
+
}
|
|
224
|
+
if (found.length > 1) {
|
|
225
|
+
throw new McpToolError(`The mention of "${person}" matches ${found.length} members of the new chat: ${list(found)}. ${THIRD_PARTY_NAMES_NOTE} ` +
|
|
226
|
+
'(error code: mention_ambiguous)', { hint: 'Pass the MRI of the member to mention as person.' });
|
|
227
|
+
}
|
|
228
|
+
throw new McpToolError(`The mention of "${person}" matches no member of the new chat. Members: ${list(members)}. ${THIRD_PARTY_NAMES_NOTE} ` +
|
|
229
|
+
'(error code: mention_no_member)', { hint: 'Mention only people in people: pass their display name or MRI as person, or add them to people.' });
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
/** Render the first message as it will be posted, with its mentions resolved against the members. */
|
|
233
|
+
function firstMessage(text, format, mentions, members) {
|
|
234
|
+
const shown = resolveMemberMentions(mentions, members);
|
|
235
|
+
const targets = shown.map((m) => ({ text: m.name_in_text, mri: m.mri }));
|
|
236
|
+
const rendered = renderMessageHtml(text, targets, format);
|
|
237
|
+
// The new chat's members are the only names a multi-word "@name" can mean here.
|
|
238
|
+
const known = members.flatMap((m) => [m.name, m.person].filter((n) => n !== undefined && !MRI.test(n)));
|
|
239
|
+
return {
|
|
240
|
+
text,
|
|
241
|
+
format,
|
|
242
|
+
content: rendered.html,
|
|
243
|
+
mentions: rendered.mentions.length > 0 ? mentionsProperty(rendered.mentions) : '[]',
|
|
244
|
+
shown,
|
|
245
|
+
unmatched: unmatchedMentions(text, mentionRanges(text, targets), known),
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The mention fields that go ABOVE the first message's text in the preview,
|
|
250
|
+
* as teams_send_message shows them: a warning (never a refusal) for an
|
|
251
|
+
* "@name" no mention covers, and a one-line summary of who is mentioned.
|
|
252
|
+
*/
|
|
253
|
+
function mentionAbove(msg) {
|
|
254
|
+
const n = msg.unmatched.length;
|
|
255
|
+
return {
|
|
256
|
+
...(n > 0
|
|
257
|
+
? {
|
|
258
|
+
unmatched_mentions: msg.unmatched,
|
|
259
|
+
mention_warning: `${msg.unmatched.join(', ')} ${n === 1 ? 'is' : 'are'} written as plain text: no mention names ` +
|
|
260
|
+
`${n === 1 ? 'it' : 'them'}, so nobody is notified. To mention, add to mentions (name_in_text, and ` +
|
|
261
|
+
'person: a member of the new chat); otherwise it is sent as written.',
|
|
262
|
+
}
|
|
263
|
+
: {}),
|
|
264
|
+
...(msg.shown.length > 0
|
|
265
|
+
? { mentions_summary: 'Mentions: ' + msg.shown.map((m) => JSON.stringify(m.name ?? m.person)).join(', ') }
|
|
266
|
+
: {}),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Post the first message to `conversationId` — the id Teams returned for the
|
|
271
|
+
* new chat, never a name lookup — and look for it again by its clientmessageid.
|
|
272
|
+
*/
|
|
273
|
+
async function postFirstMessage(chatsvc, conversationId, me, msg) {
|
|
274
|
+
const meName = await chatsvc.meDisplayName().catch(() => '');
|
|
275
|
+
const clientmessageid = newClientMessageId();
|
|
276
|
+
const body = buildSendBody({
|
|
277
|
+
conversationId,
|
|
278
|
+
meMri: me,
|
|
279
|
+
meName,
|
|
280
|
+
content: msg.content,
|
|
281
|
+
clientmessageid,
|
|
282
|
+
now: new Date(),
|
|
283
|
+
...(msg.mentions !== '[]' ? { mentions: msg.mentions } : {}),
|
|
284
|
+
});
|
|
285
|
+
let sentId;
|
|
286
|
+
try {
|
|
287
|
+
sentId = (await chatsvc.sendMessage(conversationId, body)).id;
|
|
288
|
+
}
|
|
289
|
+
catch (e) {
|
|
290
|
+
if (e instanceof WriteOutcomeUnknownError)
|
|
291
|
+
return { status: 'unknown', reason: unconfirmedWhy(e) };
|
|
292
|
+
return { status: 'failed', error: e instanceof Error ? e.message : String(e) };
|
|
293
|
+
}
|
|
294
|
+
let found;
|
|
295
|
+
let readBackFailed = false;
|
|
296
|
+
try {
|
|
297
|
+
found = (await chatsvc.getMessages(conversationId, { max: READBACK_MESSAGES })).find((m) => m.clientmessageid === clientmessageid)?.id;
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
readBackFailed = true;
|
|
301
|
+
}
|
|
302
|
+
const message_id = sentId ?? found;
|
|
303
|
+
const verified = found !== undefined;
|
|
304
|
+
return {
|
|
305
|
+
status: 'sent',
|
|
306
|
+
...(message_id !== undefined ? { message_id } : {}),
|
|
307
|
+
verified,
|
|
308
|
+
...(verified
|
|
309
|
+
? {}
|
|
310
|
+
: {
|
|
311
|
+
warning: readBackFailed
|
|
312
|
+
? 'Teams accepted the message, but reading the chat back failed — check it before posting again.'
|
|
313
|
+
: 'Teams accepted the message, but it was not found on reading the chat back — check it before posting again.',
|
|
314
|
+
}),
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
/** What a "partial" result warns: the chat exists; how to send the message without making another. */
|
|
318
|
+
function partialWarning(outcome) {
|
|
319
|
+
const why = outcome.status === 'unknown'
|
|
320
|
+
? `Teams did not confirm the first message (${outcome.reason}), so it may already be in the chat — check it with ` +
|
|
321
|
+
'teams_list_messages (conversation: the id above) before sending it again.'
|
|
322
|
+
: `The first message failed: ${outcome.error}.`;
|
|
323
|
+
return (`The group chat WAS created (conversation id above), but ${why} To send the message, run retry ` +
|
|
324
|
+
'(teams_send_message to that conversation id). Do NOT call teams_create_group_chat again to retry — the chat ' +
|
|
325
|
+
'already exists (a repeat of the same call would only send to it).');
|
|
326
|
+
}
|
|
327
|
+
/** A send-only retry, ready to run: teams_send_message to the created chat, mentions by MRI. */
|
|
328
|
+
function retryCall(conversationId, msg) {
|
|
329
|
+
return {
|
|
330
|
+
tool: 'teams_send_message',
|
|
331
|
+
arguments: {
|
|
332
|
+
conversation: conversationId,
|
|
333
|
+
text: msg.text,
|
|
334
|
+
format: msg.format,
|
|
335
|
+
...(msg.shown.length > 0 ? { mentions: msg.shown.map((m) => ({ name_in_text: m.name_in_text, person: m.mri })) } : {}),
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
156
339
|
export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
157
340
|
server.registerTool(RENAME, {
|
|
158
341
|
title: 'Rename a Teams group chat',
|
|
@@ -256,7 +439,7 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
256
439
|
'already_member, unknown (Teams did not confirm and reading the chat back does not show them — check ' +
|
|
257
440
|
'before retrying) or failed (with the error). ' +
|
|
258
441
|
CONFIRM_FLOW_SENTENCE +
|
|
259
|
-
' The preview shows the chat and exactly who would be added — each with their source (id, chat or ' +
|
|
442
|
+
' The preview shows the chat and exactly who would be added — each with their source (id, chat, caller or ' +
|
|
260
443
|
'directory) and, from the directory, their email — so the user can check it is the right person. ' +
|
|
261
444
|
CONFIRM_INJECTION_RULE +
|
|
262
445
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
@@ -265,13 +448,14 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
265
448
|
inputSchema: {
|
|
266
449
|
conversation: conversationParam,
|
|
267
450
|
people: peopleParam,
|
|
451
|
+
ids: idsParam,
|
|
268
452
|
confirmToken: confirmTokenParam,
|
|
269
453
|
},
|
|
270
|
-
}, async ({ conversation, people, confirmToken }, ctx) => {
|
|
454
|
+
}, async ({ conversation, people, ids, confirmToken }, ctx) => {
|
|
271
455
|
try {
|
|
272
456
|
const me = await chatsvc.meMri();
|
|
273
457
|
const target = await groupChat(chatsvc, conversation, me, 'given more people');
|
|
274
|
-
const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
|
|
458
|
+
const resolved = await resolveFor(chatsvc, substrate, me, target.id, people, ids);
|
|
275
459
|
const members = memberSet(await chatsvc.getThread(target.id));
|
|
276
460
|
const already = resolved.filter((p) => members.has(p.mri.toLowerCase()));
|
|
277
461
|
const toAdd = resolved.filter((p) => !members.has(p.mri.toLowerCase()));
|
|
@@ -325,7 +509,7 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
325
509
|
'result lists each person: removed, not_member, unknown (Teams did not confirm and reading the chat back ' +
|
|
326
510
|
'still shows them — check before retrying) or failed (with the error). ' +
|
|
327
511
|
CONFIRM_FLOW_SENTENCE +
|
|
328
|
-
' The preview shows the chat and exactly who would be removed — each with their source (id, chat or ' +
|
|
512
|
+
' The preview shows the chat and exactly who would be removed — each with their source (id, chat, caller or ' +
|
|
329
513
|
'directory) and, from the directory, their email. ' +
|
|
330
514
|
CONFIRM_INJECTION_RULE +
|
|
331
515
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
@@ -334,13 +518,14 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
334
518
|
inputSchema: {
|
|
335
519
|
conversation: conversationParam,
|
|
336
520
|
people: peopleParam,
|
|
521
|
+
ids: idsParam,
|
|
337
522
|
confirmToken: confirmTokenParam,
|
|
338
523
|
},
|
|
339
|
-
}, async ({ conversation, people, confirmToken }, ctx) => {
|
|
524
|
+
}, async ({ conversation, people, ids, confirmToken }, ctx) => {
|
|
340
525
|
try {
|
|
341
526
|
const me = await chatsvc.meMri();
|
|
342
527
|
const target = await groupChat(chatsvc, conversation, me, 'changed');
|
|
343
|
-
const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
|
|
528
|
+
const resolved = await resolveFor(chatsvc, substrate, me, target.id, people, ids);
|
|
344
529
|
const self = resolved.find((p) => p.mri.toLowerCase() === me.toLowerCase());
|
|
345
530
|
if (self !== undefined) {
|
|
346
531
|
throw new McpToolError(`Refusing to remove you (the signed-in user, "${self.person}") from the chat.`, {
|
|
@@ -398,17 +583,30 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
398
583
|
'one other person is a 1:1, which this tool does not create. ' +
|
|
399
584
|
peopleSentence("the other person of each of the user's 1:1 chats") +
|
|
400
585
|
'Everyone added sees the chat at once in their chat list, and it cannot be deleted afterwards — only ' +
|
|
401
|
-
'left.
|
|
586
|
+
'left. Optionally post the first message in the same action: message (with format text|markdown and ' +
|
|
587
|
+
'mentions, as for teams_send_message, except that each mention\'s person must be one of the new chat\'s ' +
|
|
588
|
+
'members — by display name or MRI; one matching none or several is refused). The chat is created first ' +
|
|
589
|
+
'and the message is then posted to the conversation id Teams returned (never looked up by name). ' +
|
|
590
|
+
'Without message nothing is sent; teams_send_message can post later with the new conversation id. ' +
|
|
402
591
|
'Not idempotent: every confirmed call makes a NEW chat. The result has the new conversation (id, title, ' +
|
|
403
|
-
'kind "group"), the members and whether reading the chat back showed them all and the topic (verified)
|
|
404
|
-
'status "
|
|
405
|
-
'
|
|
592
|
+
'kind "group"), the members and whether reading the chat back showed them all and the topic (verified), ' +
|
|
593
|
+
'and with a message, message: {status "sent", message_id, verified}. Status "partial" means the chat WAS ' +
|
|
594
|
+
'created but the message failed (or Teams did not confirm it): it carries the conversation id, the error ' +
|
|
595
|
+
'and a ready retry (teams_send_message to that id) — never call this tool again to retry, though if you ' +
|
|
596
|
+
'do, the same people and topic only send to the chat already made. Status "unknown" means Teams did not ' +
|
|
597
|
+
'confirm the create — a chat may exist anyway, so check teams_list_conversations and do NOT retry blindly ' +
|
|
598
|
+
'(that would make a second chat); no message is sent then. ' +
|
|
406
599
|
CONFIRM_FLOW_SENTENCE +
|
|
407
|
-
'
|
|
408
|
-
'
|
|
600
|
+
' One confirmation covers both steps and is bound to the members, the topic and the exact message. The ' +
|
|
601
|
+
'preview shows the topic, exactly who would be in the chat — each with their source (id, chat, caller or ' +
|
|
602
|
+
'directory) and, from the directory, their email — and the exact message (text, format, rendered HTML and ' +
|
|
603
|
+
'each mention with the member it resolved to), so the user can check it all. Above the message it adds ' +
|
|
604
|
+
'mentions_summary and, for any "@name" in the text that no mention covers (it would go out as plain text ' +
|
|
605
|
+
'and notify nobody), unmatched_mentions with a mention_warning — a warning, not a refusal. ' +
|
|
409
606
|
CONFIRM_INJECTION_RULE +
|
|
410
607
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
411
|
-
|
|
608
|
+
// Destructive like teams_send_message: a first message, once posted, cannot be recalled.
|
|
609
|
+
annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: false, openWorld: true }),
|
|
412
610
|
_meta: workMeta('send', {
|
|
413
611
|
aliases: ['create chat', 'new group chat', 'start a chat', 'new chat', 'group chat', 'start group chat'],
|
|
414
612
|
}),
|
|
@@ -423,13 +621,32 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
423
621
|
.string()
|
|
424
622
|
.optional()
|
|
425
623
|
.describe('A name for the chat (surrounding spaces are trimmed). Omit or leave empty for an untitled chat.'),
|
|
624
|
+
ids: idsParam,
|
|
625
|
+
message: z
|
|
626
|
+
.string()
|
|
627
|
+
.min(1)
|
|
628
|
+
.optional()
|
|
629
|
+
.describe('Optional first message, posted to the new chat right after it is created (same confirmation): plain text, ' +
|
|
630
|
+
'or Markdown with format "markdown". Omit to create the chat only.'),
|
|
631
|
+
format: formatParam,
|
|
632
|
+
mentions: z
|
|
633
|
+
.array(mentionArg)
|
|
634
|
+
.max(20)
|
|
635
|
+
.optional()
|
|
636
|
+
.describe('People to @-mention in message: name_in_text must appear in message; person is a member of the new chat ' +
|
|
637
|
+
'(their display name, the people entry that named them, or their MRI).'),
|
|
426
638
|
confirmToken: confirmTokenParam,
|
|
427
639
|
},
|
|
428
|
-
}, async ({ people, topic: rawTopic, confirmToken }, ctx) => {
|
|
640
|
+
}, async ({ people, topic: rawTopic, ids, message, format, mentions, confirmToken }, ctx) => {
|
|
429
641
|
try {
|
|
642
|
+
if (message === undefined && ((mentions?.length ?? 0) > 0 || format !== undefined)) {
|
|
643
|
+
throw new McpToolError('mentions and format apply to message, and no message was given.', {
|
|
644
|
+
hint: 'Pass message, or leave out mentions and format.',
|
|
645
|
+
});
|
|
646
|
+
}
|
|
430
647
|
const me = await chatsvc.meMri();
|
|
431
648
|
const topic = rawTopic?.trim() || undefined;
|
|
432
|
-
const others = (await resolveFor(chatsvc, substrate, me, undefined, people)).filter((p) => p.mri.toLowerCase() !== me.toLowerCase());
|
|
649
|
+
const others = (await resolveFor(chatsvc, substrate, me, undefined, people, ids)).filter((p) => p.mri.toLowerCase() !== me.toLowerCase());
|
|
433
650
|
if (others.length < 2) {
|
|
434
651
|
throw new McpToolError(`A group chat needs at least two other people besides you; ${others.length === 1 ? `only ${JSON.stringify(others[0].person)} is` : 'no one else is'} left once you and duplicates are dropped. One other person is a 1:1 chat, which this tool does not create.`, {
|
|
435
652
|
hint: 'Add at least one more person, or to talk to one person use your 1:1 chat with them (teams_send_message, ' +
|
|
@@ -438,22 +655,91 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
438
655
|
}
|
|
439
656
|
const members = others.map(shown);
|
|
440
657
|
const allMris = [me, ...others.map((p) => p.mri)];
|
|
658
|
+
const msg = message !== undefined ? firstMessage(message, format ?? 'text', mentions ?? [], others) : undefined;
|
|
659
|
+
const msgPreview = msg === undefined
|
|
660
|
+
? undefined
|
|
661
|
+
: {
|
|
662
|
+
...mentionAbove(msg),
|
|
663
|
+
text: msg.text,
|
|
664
|
+
format: msg.format,
|
|
665
|
+
rendered_html: msg.content,
|
|
666
|
+
...(msg.shown.length > 0 ? { mentions: untrustedField(msg.shown) } : {}),
|
|
667
|
+
};
|
|
668
|
+
const key = pendingKey(me, allMris, topic);
|
|
669
|
+
// This chat was made by an earlier call whose first message did not go
|
|
670
|
+
// through: only send, to that id. Never a second chat.
|
|
671
|
+
const pending = msg !== undefined ? pendingFor(key) : undefined;
|
|
672
|
+
if (pending !== undefined && msg !== undefined) {
|
|
673
|
+
const path = `/users/ME/conversations/${encodeURIComponent(pending.id)}/messages`;
|
|
674
|
+
const gate = await confirmWrite(ctx, {
|
|
675
|
+
tool: CREATE,
|
|
676
|
+
action: 'chat.send_message',
|
|
677
|
+
message: 'This group chat was already created by an earlier call; review and confirm its first message:',
|
|
678
|
+
summary: `Send the first message to group chat ${JSON.stringify(pending.title)} (${pending.id}), already created earlier — the chat is NOT created again`,
|
|
679
|
+
account: me,
|
|
680
|
+
target: pending.id,
|
|
681
|
+
request: { method: 'POST', path, body: { content: msg.content, mentions: msg.mentions } },
|
|
682
|
+
preview: {
|
|
683
|
+
conversation: { id: pending.id, title: pending.title, kind: 'group' },
|
|
684
|
+
members: untrustedField(members),
|
|
685
|
+
first_message: msgPreview,
|
|
686
|
+
note: 'The chat with these people and this topic was already created by an earlier call whose first message ' +
|
|
687
|
+
`${pending.outcome === 'unknown' ? 'Teams did not confirm — it may already be in the chat, so check teams_list_messages first' : 'failed'}. ` +
|
|
688
|
+
'Confirming only posts the message there; no new chat is made.',
|
|
689
|
+
},
|
|
690
|
+
confirmToken,
|
|
691
|
+
});
|
|
692
|
+
if (gate)
|
|
693
|
+
return gate;
|
|
694
|
+
const outcome = await postFirstMessage(chatsvc, pending.id, me, msg);
|
|
695
|
+
const conversation = { id: pending.id, title: pending.title, kind: 'group' };
|
|
696
|
+
if (outcome.status === 'sent') {
|
|
697
|
+
pendingFirstMessages.delete(key);
|
|
698
|
+
return untrustedResult({ status: 'sent', conversation, created_earlier: true, message: outcome });
|
|
699
|
+
}
|
|
700
|
+
pendingFirstMessages.set(key, { ...pending, outcome: outcome.status });
|
|
701
|
+
return untrustedResult({
|
|
702
|
+
status: 'partial',
|
|
703
|
+
conversation,
|
|
704
|
+
created_earlier: true,
|
|
705
|
+
message: outcome,
|
|
706
|
+
retry: retryCall(pending.id, msg),
|
|
707
|
+
warning: partialWarning(outcome),
|
|
708
|
+
});
|
|
709
|
+
}
|
|
441
710
|
const count = `you and ${others.length} other people`;
|
|
442
711
|
const gate = await confirmWrite(ctx, {
|
|
443
712
|
tool: CREATE,
|
|
444
713
|
action: 'chat.create',
|
|
445
|
-
message:
|
|
714
|
+
message: msg === undefined
|
|
715
|
+
? 'Review and confirm this new group chat before it is created — it cannot be deleted afterwards:'
|
|
716
|
+
: 'Review and confirm this new group chat and its first message — the chat cannot be deleted afterwards:',
|
|
446
717
|
// The topic is the caller's own text: JSON-quoted all the same, so it reads as one value.
|
|
447
|
-
summary: `Create ${topic !== undefined ? `group chat ${JSON.stringify(topic)}` : 'an untitled group chat'} with ${count}
|
|
718
|
+
summary: `Create ${topic !== undefined ? `group chat ${JSON.stringify(topic)}` : 'an untitled group chat'} with ${count}` +
|
|
719
|
+
(msg !== undefined ? ', then post its first message' + unmatchedNote(msg.unmatched.length) : ''),
|
|
448
720
|
account: me,
|
|
449
721
|
target: 'new group chat',
|
|
450
|
-
|
|
722
|
+
// Bound to the members, the topic and — with a message — its exact rendered content and mentions.
|
|
723
|
+
request: {
|
|
724
|
+
method: 'POST',
|
|
725
|
+
path: '/threads',
|
|
726
|
+
body: {
|
|
727
|
+
members: allMris,
|
|
728
|
+
...(topic !== undefined ? { topic } : {}),
|
|
729
|
+
...(msg !== undefined ? { first_message: { content: msg.content, mentions: msg.mentions } } : {}),
|
|
730
|
+
},
|
|
731
|
+
},
|
|
451
732
|
// The resolved names are set by other people, so they are fenced.
|
|
452
733
|
preview: {
|
|
453
734
|
topic: topic ?? '(untitled)',
|
|
454
735
|
members: untrustedField(members),
|
|
736
|
+
...(msgPreview !== undefined ? { first_message: msgPreview } : {}),
|
|
455
737
|
note: 'Creates a NEW group chat with everyone as a member (Teams makes each one an Admin). Everyone added ' +
|
|
456
|
-
'sees it at once; it cannot be deleted afterwards, only left.
|
|
738
|
+
'sees it at once; it cannot be deleted afterwards, only left. ' +
|
|
739
|
+
(msg === undefined
|
|
740
|
+
? 'No message is sent.'
|
|
741
|
+
: 'Then posts first_message to the conversation id Teams returns for it (one POST ' +
|
|
742
|
+
'/users/ME/conversations/{id}/messages); clientmessageid and timestamps are filled in then.'),
|
|
457
743
|
},
|
|
458
744
|
confirmToken,
|
|
459
745
|
});
|
|
@@ -470,6 +756,7 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
470
756
|
status: 'unknown',
|
|
471
757
|
...(topic !== undefined ? { topic } : {}),
|
|
472
758
|
members,
|
|
759
|
+
...(msg !== undefined ? { message: { status: 'not_sent' } } : {}),
|
|
473
760
|
warning: `Teams did not confirm creating the chat (${unconfirmedWhy(e)}), so it may or may not exist. Check ` +
|
|
474
761
|
'teams_list_conversations for a new group chat with these people (no messages yet) before doing ' +
|
|
475
762
|
'anything else — do NOT retry blindly: if it was created, retrying makes a second chat, and chats ' +
|
|
@@ -497,13 +784,42 @@ export function registerGroupChatTools(server, { chatsvc, substrate }) {
|
|
|
497
784
|
verified = null;
|
|
498
785
|
warning = 'Teams created the chat, but reading the chat back failed — check it in teams_list_conversations (do not create it again).';
|
|
499
786
|
}
|
|
787
|
+
const conversation = { id, title: topic ?? UNTITLED_GROUP_TITLE, kind: 'group' };
|
|
788
|
+
if (msg === undefined) {
|
|
789
|
+
return untrustedResult({
|
|
790
|
+
status: 'created',
|
|
791
|
+
conversation,
|
|
792
|
+
...(topic !== undefined ? { topic } : {}),
|
|
793
|
+
members,
|
|
794
|
+
verified,
|
|
795
|
+
...(warning !== undefined ? { warning } : {}),
|
|
796
|
+
});
|
|
797
|
+
}
|
|
798
|
+
// Created: post the first message to the id Teams returned.
|
|
799
|
+
const outcome = await postFirstMessage(chatsvc, id, me, msg);
|
|
800
|
+
if (outcome.status === 'sent') {
|
|
801
|
+
return untrustedResult({
|
|
802
|
+
status: 'created',
|
|
803
|
+
conversation,
|
|
804
|
+
...(topic !== undefined ? { topic } : {}),
|
|
805
|
+
members,
|
|
806
|
+
verified,
|
|
807
|
+
message: outcome,
|
|
808
|
+
...(warning !== undefined ? { warning } : {}),
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
// The chat exists; the message did not (or may not have) go through. Remember
|
|
812
|
+
// the chat, so a repeat of this call only sends — never creates a second one.
|
|
813
|
+
pendingFirstMessages.set(key, { id, title: conversation.title, at: Date.now(), outcome: outcome.status });
|
|
500
814
|
return untrustedResult({
|
|
501
|
-
status: '
|
|
502
|
-
conversation
|
|
815
|
+
status: 'partial',
|
|
816
|
+
conversation,
|
|
503
817
|
...(topic !== undefined ? { topic } : {}),
|
|
504
818
|
members,
|
|
505
819
|
verified,
|
|
506
|
-
|
|
820
|
+
message: outcome,
|
|
821
|
+
retry: retryCall(id, msg),
|
|
822
|
+
warning: [warning, partialWarning(outcome)].filter((w) => w !== undefined).join(' '),
|
|
507
823
|
});
|
|
508
824
|
}
|
|
509
825
|
catch (err) {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
2
|
import { credentialHealthcheckDescription, runCredentialHealthcheck } from '@chrischall/mcp-utils/healthcheck';
|
|
3
|
+
import { captureErrorCode, captureFailure, classifyCaptureFailure, TokenCaptureError } from '../capture-feedback.js';
|
|
3
4
|
const HOST_LABEL = 'teams.cloud.microsoft';
|
|
4
5
|
const TITLE = 'Verify the Teams chat-service token and API end-to-end';
|
|
5
6
|
/**
|
|
@@ -12,9 +13,9 @@ const SHAREPOINT_NOTE = 'Shared-file download (teams_get_attachment) uses a sepa
|
|
|
12
13
|
'a file, and this healthcheck neither mints nor requires one.';
|
|
13
14
|
/** Static note on the search path. Not probed — a healthy result never depends on it. */
|
|
14
15
|
const SUBSTRATE_NOTE = 'Search (teams_search_messages) uses a separate Microsoft Substrate token for substrate.office.com, ' +
|
|
15
|
-
'captured on demand when you run a search in a Teams tab (the bridge pairing must trust ' +
|
|
16
|
+
'captured on demand when you run a search in a Teams tab while a call waits (the bridge pairing must trust ' +
|
|
16
17
|
'substrate.office.com). Without one, search falls back to a scan of recent conversations; this ' +
|
|
17
|
-
'healthcheck neither mints nor requires one.';
|
|
18
|
+
'healthcheck neither mints nor requires one — teams_token_status reports whether it is held.';
|
|
18
19
|
export function registerHealthcheckTool(server, { chatsvc }) {
|
|
19
20
|
server.registerTool('teams_healthcheck', {
|
|
20
21
|
title: TITLE,
|
|
@@ -22,7 +23,9 @@ export function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
22
23
|
'token behind every tool; the probe is one conversations listing. Also reports the ' +
|
|
23
24
|
'token\'s source (browser capture through the ContextMint Bridge, or TEAMS_ACCESS_TOKEN), ' +
|
|
24
25
|
'its expiry, and how many conversations the listing returned — never the token itself. ' +
|
|
25
|
-
'Call this when a real tool fails and you want to know which hop broke.'
|
|
26
|
+
'Call this when a real tool fails and you want to know which hop broke. A failed token capture is ' +
|
|
27
|
+
'reported with a stable code (error.detail.code, e.g. token_no_request_seen) and the one next step; to ' +
|
|
28
|
+
'see which tokens are held without capturing, or to prime one with a longer wait, use teams_token_status.',
|
|
26
29
|
annotations: toolAnnotations({ title: TITLE, readOnly: true, idempotent: true, openWorld: true }),
|
|
27
30
|
inputSchema: {},
|
|
28
31
|
}, async () => {
|
|
@@ -44,9 +47,23 @@ export function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
44
47
|
conversations = (await chatsvc.listConversations()).length;
|
|
45
48
|
return `${conversations} conversation(s) listed`;
|
|
46
49
|
},
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
+
// A capture failure names its step, how long it waited and a stable code
|
|
51
|
+
// (`capture-feedback.ts`); the hint says to act WHILE the retry waits.
|
|
52
|
+
classifyThrown: (err) => {
|
|
53
|
+
if (!(err instanceof TokenCaptureError) && !/could not capture a Teams token/i.test(err instanceof Error ? err.message : String(err))) {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const described = captureFailure(err, 'verify the chat service', 'chat_service');
|
|
57
|
+
return {
|
|
58
|
+
kind: 'token_capture',
|
|
59
|
+
hint: described.hint,
|
|
60
|
+
detail: {
|
|
61
|
+
code: captureErrorCode(classifyCaptureFailure(err)),
|
|
62
|
+
message: described.message,
|
|
63
|
+
...(err instanceof TokenCaptureError ? { waited_seconds: Math.round(err.waitedMs / 1000) } : {}),
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
},
|
|
50
67
|
});
|
|
51
68
|
// Read after the resolve, which is what loads (or captures) the token.
|
|
52
69
|
const expiresAt = chatsvc.tokenExpiresAt();
|
|
@@ -88,6 +105,3 @@ export function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
88
105
|
};
|
|
89
106
|
});
|
|
90
107
|
}
|
|
91
|
-
const TOKEN_CAPTURE_HINT = 'No Teams access token could be captured. Open a signed-in teams.cloud.microsoft tab and click ' +
|
|
92
|
-
'into any chat (that is what makes Teams call its chat service, where the token is read from), ' +
|
|
93
|
-
'then retry.';
|