@chrischall/microsoft-teams-mcp 0.8.7 → 0.10.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.
@@ -0,0 +1,517 @@
1
+ import { z } from 'zod';
2
+ import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, McpToolError, toolAnnotations, WriteOutcomeUnknownError, writeOutcomeStatus, } from '@chrischall/mcp-utils';
3
+ import { UNTITLED_GROUP_TITLE } from '../model.js';
4
+ import { wrapApiError } from './errors.js';
5
+ import { workMeta } from './hints.js';
6
+ import { knownPeople, resolvePeople } from './people.js';
7
+ import { resolveTarget, SELF_CHAT } from './send.js';
8
+ import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
+ const RENAME = 'teams_rename_chat';
10
+ const ADD = 'teams_add_chat_members';
11
+ const REMOVE = 'teams_remove_chat_members';
12
+ const CREATE = 'teams_create_group_chat';
13
+ /** Most people one call adds or removes. */
14
+ const MAX_PEOPLE = 20;
15
+ const KIND_LABELS = {
16
+ oneOnOne: 'a 1:1 chat',
17
+ meeting: 'a meeting chat',
18
+ channel: 'a channel',
19
+ self: 'your notes self-chat',
20
+ };
21
+ const conversationParam = z
22
+ .string()
23
+ .min(1)
24
+ .describe('The group chat: its id (from teams_list_conversations), or a case-insensitive substring of its title or ' +
25
+ "an untitled chat's participant names.");
26
+ /** How a person may be named, for a `people` parameter; `local` says where a name is matched before the directory. */
27
+ function peopleParamText(local) {
28
+ return ('each an MRI (8:orgid:…), a bare Entra object id, an email address (looked up in your organisation\'s ' +
29
+ 'directory), or a display name ("Greg King" and "King, Greg" are the same) matched among ' +
30
+ `${local}, then — only if no one there matches — in the directory.`);
31
+ }
32
+ const peopleParam = z
33
+ .array(z.string().trim().min(1))
34
+ .min(1)
35
+ .max(MAX_PEOPLE)
36
+ .describe(`Who: ${peopleParamText('the other people of your 1:1 chats and recent senders in this chat')}`);
37
+ /** The description's sentence on naming people; `local` says where a name is matched before the directory. */
38
+ function peopleSentence(local) {
39
+ return ('people are MRIs (8:orgid:…), bare object ids, email addresses, or display names. A name is matched ' +
40
+ `(ignoring case, in either "First Last" or "Last, First" order) among ${local} first; only when no one ` +
41
+ "there matches is the organisation's directory searched, where the one person with exactly that name is " +
42
+ 'taken (or the only suggestion, when the name is whole words of it). An email address is looked up in the ' +
43
+ "directory and must be exactly one person's email or UPN. An ambiguous or unknown person refuses the whole " +
44
+ 'call, listing candidates. The directory is searched with the same token as teams_search_messages: the ' +
45
+ 'first lookup may need the user to run any search in the Teams search box so it can be captured. ');
46
+ }
47
+ const PEOPLE_SENTENCE = peopleSentence("the other person of each of the user's 1:1 chats and the chat's recent senders");
48
+ /** The conversation, refused unless it is a group chat. `doing` words the refusal ("renamed"). */
49
+ async function groupChat(chatsvc, conversation, me, doing) {
50
+ const target = await resolveTarget(chatsvc, conversation, me, `change`);
51
+ if (target.kind === 'group')
52
+ return target;
53
+ const what = KIND_LABELS[target.kind] ?? `a ${target.kind}`;
54
+ throw new McpToolError(`${JSON.stringify(target.title)} is ${what}, not a group chat: only a group chat can be ${doing}.`, {
55
+ hint: target.kind === 'oneOnOne'
56
+ ? 'A 1:1 cannot take more people or a name; start a group chat in Teams instead.'
57
+ : 'Pass a group chat (kind "group" in teams_list_conversations).',
58
+ });
59
+ }
60
+ /** Why Teams did not confirm a write, for a warning. */
61
+ function unconfirmedWhy(e) {
62
+ const status = writeOutcomeStatus(e);
63
+ return e.timedOut ? 'it did not answer in time' : status !== undefined ? `it answered HTTP ${status}` : 'the connection dropped';
64
+ }
65
+ /** The thread's members' MRIs, lower-cased. */
66
+ function memberSet(thread) {
67
+ return new Set((thread.members ?? []).map((m) => m.id.toLowerCase()));
68
+ }
69
+ /** A person as a preview or a result shows them: where they were found and, from the directory, their email. */
70
+ function shown(p) {
71
+ return {
72
+ person: p.person,
73
+ mri: p.mri,
74
+ ...(p.name !== undefined ? { name: p.name } : {}),
75
+ source: p.source,
76
+ ...(p.email !== undefined ? { email: p.email } : {}),
77
+ };
78
+ }
79
+ /**
80
+ * People resolved and de-duplicated by MRI (the first naming of each kept).
81
+ * Names are matched among the user's 1:1s and, given `conversationId`, that
82
+ * chat's recent senders; with none (a chat not yet made), the 1:1s only.
83
+ */
84
+ async function resolveFor(chatsvc, directory, me, conversationId, people) {
85
+ const known = await knownPeople(chatsvc, me, conversationId);
86
+ const seen = new Set();
87
+ return (await resolvePeople(people, known, directory)).filter((p) => {
88
+ const key = p.mri.toLowerCase();
89
+ if (seen.has(key))
90
+ return false;
91
+ seen.add(key);
92
+ return true;
93
+ });
94
+ }
95
+ /**
96
+ * Run one write per person, read the thread back once, and report each:
97
+ * `done` (shown, or Teams confirmed it — `verified` saying whether the
98
+ * read-back showed it, null when the read-back failed), `unknown` (Teams did
99
+ * not confirm and the read-back does not show it) or `failed` (refused).
100
+ */
101
+ async function applyMemberChanges(chatsvc, threadId, people, write, done) {
102
+ const outcomes = [];
103
+ for (const p of people) {
104
+ try {
105
+ await write(p.mri);
106
+ outcomes.push({ p });
107
+ }
108
+ catch (e) {
109
+ if (e instanceof WriteOutcomeUnknownError)
110
+ outcomes.push({ p, unconfirmed: e });
111
+ else
112
+ outcomes.push({ p, error: e instanceof Error ? e.message : String(e) });
113
+ }
114
+ }
115
+ let members;
116
+ try {
117
+ members = memberSet(await chatsvc.getThread(threadId));
118
+ }
119
+ catch {
120
+ members = undefined;
121
+ }
122
+ const changed = (mri) => {
123
+ const present = members?.has(mri.toLowerCase());
124
+ return present === undefined ? null : done === 'added' ? present : !present;
125
+ };
126
+ const notes = [];
127
+ const results = outcomes.map(({ p, unconfirmed, error }) => {
128
+ if (error !== undefined)
129
+ return { ...shown(p), status: 'failed', error };
130
+ const verified = changed(p.mri);
131
+ if (unconfirmed !== undefined && verified !== true) {
132
+ notes.push(`Teams did not confirm the change for ${p.mri} (${unconfirmedWhy(unconfirmed)}), and reading the chat back ` +
133
+ `${verified === null ? 'failed' : `did not show it ${done}`}.`);
134
+ return { ...shown(p), status: 'unknown', verified: verified ?? false };
135
+ }
136
+ if (unconfirmed !== undefined) {
137
+ notes.push(`Teams did not confirm the change for ${p.mri}, but reading the chat back shows it ${done}.`);
138
+ }
139
+ else if (verified === false) {
140
+ notes.push(`Teams accepted the change for ${p.mri}, but reading the chat back did not show it ${done}.`);
141
+ }
142
+ return { ...shown(p), status: done, verified };
143
+ });
144
+ if (members === undefined)
145
+ notes.push('Teams accepted the changes, but reading the chat back failed.');
146
+ if (results.some((r) => r.status === 'failed'))
147
+ notes.push("Some changes failed: see each person's error.");
148
+ if (notes.length === 0)
149
+ return { results };
150
+ return {
151
+ results,
152
+ warning: `${notes.join(' ')} Check the chat before retrying — running this tool again is safe: anyone already ` +
153
+ `${done === 'added' ? 'in the chat is reported as already_member' : 'gone is reported as not_member'} and not written again.`,
154
+ };
155
+ }
156
+ export function registerGroupChatTools(server, { chatsvc, substrate }) {
157
+ server.registerTool(RENAME, {
158
+ title: 'Rename a Teams group chat',
159
+ description: "Rename a group chat (set its topic) as the signed-in user. conversation is the chat's id or name as for " +
160
+ `teams_list_messages; only group chats can be renamed — 1:1s, meeting chats, channels and the self-chat ` +
161
+ `(${SELF_CHAT}) are refused. Teams posts a notice in the chat that the user renamed it, so everyone in it ` +
162
+ 'sees the change. Renaming to the current name changes nothing and asks for no confirmation. The result ' +
163
+ 'says whether reading the chat back showed the new name (verified); status "unknown" means Teams did not ' +
164
+ 'confirm the change and the read-back did not show it — check the chat before retrying. ' +
165
+ CONFIRM_FLOW_SENTENCE +
166
+ ' The preview shows the chat, its current name and the new one. ' +
167
+ CONFIRM_INJECTION_RULE +
168
+ UNTRUSTED_DESCRIPTION_SUFFIX,
169
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
170
+ _meta: workMeta('send', { aliases: ['rename chat', 'rename', 'chat name', 'topic', 'set topic'] }),
171
+ inputSchema: {
172
+ conversation: conversationParam,
173
+ name: z.string().trim().min(1).describe('The new name for the chat (surrounding spaces are trimmed).'),
174
+ confirmToken: confirmTokenParam,
175
+ },
176
+ }, async ({ conversation, name, confirmToken }, ctx) => {
177
+ try {
178
+ const me = await chatsvc.meMri();
179
+ const target = await groupChat(chatsvc, conversation, me, 'renamed');
180
+ const current = (await chatsvc.getThread(target.id)).properties?.topic ?? '';
181
+ if (current === name) {
182
+ return untrustedResult({ status: 'unchanged', conversation: target, name });
183
+ }
184
+ const path = `/threads/${encodeURIComponent(target.id)}/properties?name=topic`;
185
+ const gate = await confirmWrite(ctx, {
186
+ tool: RENAME,
187
+ action: 'chat.rename',
188
+ message: 'Review and confirm this group chat rename before it is made:',
189
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
190
+ summary: `Rename group chat ${JSON.stringify(target.title)} to ${JSON.stringify(name)}`,
191
+ // The signed-in user, so an approval minted under one account never acts as another.
192
+ account: me,
193
+ target: target.id,
194
+ request: { method: 'PUT', path, body: { topic: name } },
195
+ // The title and the current name are set by other people, so each is fenced.
196
+ preview: {
197
+ conversation: untrustedField(target),
198
+ current_name: untrustedField(current),
199
+ new_name: name,
200
+ note: 'Teams posts a notice in the chat that you renamed it.',
201
+ },
202
+ confirmToken,
203
+ });
204
+ if (gate)
205
+ return gate;
206
+ let unconfirmed;
207
+ try {
208
+ await chatsvc.setTopic(target.id, name);
209
+ }
210
+ catch (e) {
211
+ if (!(e instanceof WriteOutcomeUnknownError))
212
+ throw e;
213
+ unconfirmed = e;
214
+ }
215
+ let verified = false;
216
+ try {
217
+ verified = (await chatsvc.getThread(target.id)).properties?.topic === name;
218
+ }
219
+ catch {
220
+ verified = null;
221
+ }
222
+ const base = { conversation: target, previous_name: current, name };
223
+ if (unconfirmed !== undefined && verified !== true) {
224
+ return untrustedResult({
225
+ status: 'unknown',
226
+ ...base,
227
+ verified: verified ?? false,
228
+ warning: `Teams did not confirm this rename (${unconfirmedWhy(unconfirmed)}), and reading the chat back ` +
229
+ `${verified === null ? 'failed' : 'did not show the new name'} — check the chat (teams_list_conversations) ` +
230
+ 'before retrying; renaming again to the same name is harmless.',
231
+ });
232
+ }
233
+ let warning;
234
+ if (unconfirmed !== undefined) {
235
+ warning = 'Teams did not confirm this rename, but reading the chat back shows the new name.';
236
+ }
237
+ else if (verified === null) {
238
+ warning = 'Teams accepted the rename, but reading the chat back failed — check the chat (teams_list_conversations).';
239
+ }
240
+ else if (!verified) {
241
+ warning = 'Teams accepted the rename, but reading the chat back did not show the new name — check the chat (teams_list_conversations).';
242
+ }
243
+ return untrustedResult({ status: 'renamed', ...base, verified, ...(warning !== undefined ? { warning } : {}) });
244
+ }
245
+ catch (err) {
246
+ throw wrapApiError(err, 'rename the chat');
247
+ }
248
+ });
249
+ server.registerTool(ADD, {
250
+ title: 'Add people to a Teams group chat',
251
+ description: 'Add people to a group chat as the signed-in user, as ordinary members. conversation is the chat\'s id or ' +
252
+ 'name as for teams_list_messages; only group chats take people — 1:1s, meeting chats, channels and the ' +
253
+ `self-chat are refused. ${PEOPLE_SENTENCE}People already in the chat are reported as already_member and ` +
254
+ 'not written; if everyone is, nothing is asked or changed. Teams posts a notice in the chat for each person ' +
255
+ 'added, and they can read the chat\'s history as Teams allows. The result lists each person: added, ' +
256
+ 'already_member, unknown (Teams did not confirm and reading the chat back does not show them — check ' +
257
+ 'before retrying) or failed (with the error). ' +
258
+ CONFIRM_FLOW_SENTENCE +
259
+ ' The preview shows the chat and exactly who would be added — each with their source (id, chat or ' +
260
+ 'directory) and, from the directory, their email — so the user can check it is the right person. ' +
261
+ CONFIRM_INJECTION_RULE +
262
+ UNTRUSTED_DESCRIPTION_SUFFIX,
263
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
264
+ _meta: workMeta('send', { aliases: ['add people', 'add to chat', 'invite', 'add members', 'members'] }),
265
+ inputSchema: {
266
+ conversation: conversationParam,
267
+ people: peopleParam,
268
+ confirmToken: confirmTokenParam,
269
+ },
270
+ }, async ({ conversation, people, confirmToken }, ctx) => {
271
+ try {
272
+ const me = await chatsvc.meMri();
273
+ const target = await groupChat(chatsvc, conversation, me, 'given more people');
274
+ const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
275
+ const members = memberSet(await chatsvc.getThread(target.id));
276
+ const already = resolved.filter((p) => members.has(p.mri.toLowerCase()));
277
+ const toAdd = resolved.filter((p) => !members.has(p.mri.toLowerCase()));
278
+ const alreadyResults = already.map((p) => ({ ...shown(p), status: 'already_member' }));
279
+ if (toAdd.length === 0) {
280
+ return untrustedResult({ status: 'unchanged', conversation: target, results: alreadyResults });
281
+ }
282
+ const gate = await confirmWrite(ctx, {
283
+ tool: ADD,
284
+ action: 'chat.add_members',
285
+ message: 'Review and confirm who is added to this group chat:',
286
+ summary: `Add ${toAdd.length} ${toAdd.length === 1 ? 'person' : 'people'} to group chat ${JSON.stringify(target.title)}`,
287
+ account: me,
288
+ target: target.id,
289
+ request: {
290
+ method: 'PUT',
291
+ path: `/threads/${encodeURIComponent(target.id)}/members`,
292
+ body: { members: toAdd.map((p) => ({ id: p.mri, role: 'User' })) },
293
+ },
294
+ // The title and the resolved names are set by other people, so each is fenced.
295
+ preview: {
296
+ conversation: untrustedField(target),
297
+ add: untrustedField(toAdd.map(shown)),
298
+ ...(already.length > 0 ? { already_members: untrustedField(already.map(shown)) } : {}),
299
+ note: 'Sent as one PUT /threads/{id}/members/{mri} with {"role":"User"} per person. Teams posts a notice in ' +
300
+ 'the chat for each person added.',
301
+ },
302
+ confirmToken,
303
+ });
304
+ if (gate)
305
+ return gate;
306
+ const { results, warning } = await applyMemberChanges(chatsvc, target.id, toAdd, (mri) => chatsvc.addMember(target.id, mri, 'User'), 'added');
307
+ return untrustedResult({
308
+ status: 'done',
309
+ conversation: target,
310
+ results: orderAs(resolved, [...results, ...alreadyResults]),
311
+ ...(warning !== undefined ? { warning } : {}),
312
+ });
313
+ }
314
+ catch (err) {
315
+ throw wrapApiError(err, 'add people to the chat');
316
+ }
317
+ });
318
+ server.registerTool(REMOVE, {
319
+ title: 'Remove people from a Teams group chat',
320
+ description: 'Remove people from a group chat as the signed-in user. conversation is the chat\'s id or name as for ' +
321
+ 'teams_list_messages; only group chats are changed — 1:1s, meeting chats, channels and the self-chat are ' +
322
+ `refused, and so is removing the signed-in user (leave the chat in Teams instead). ${PEOPLE_SENTENCE}` +
323
+ 'People not in the chat are reported as not_member and not written; if no one is, nothing is asked or ' +
324
+ 'changed. Teams posts a notice in the chat for each person removed, and they lose access to it. The ' +
325
+ 'result lists each person: removed, not_member, unknown (Teams did not confirm and reading the chat back ' +
326
+ 'still shows them — check before retrying) or failed (with the error). ' +
327
+ CONFIRM_FLOW_SENTENCE +
328
+ ' The preview shows the chat and exactly who would be removed — each with their source (id, chat or ' +
329
+ 'directory) and, from the directory, their email. ' +
330
+ CONFIRM_INJECTION_RULE +
331
+ UNTRUSTED_DESCRIPTION_SUFFIX,
332
+ annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: true, openWorld: true }),
333
+ _meta: workMeta('send', { aliases: ['remove people', 'remove from chat', 'kick', 'remove members', 'members'] }),
334
+ inputSchema: {
335
+ conversation: conversationParam,
336
+ people: peopleParam,
337
+ confirmToken: confirmTokenParam,
338
+ },
339
+ }, async ({ conversation, people, confirmToken }, ctx) => {
340
+ try {
341
+ const me = await chatsvc.meMri();
342
+ const target = await groupChat(chatsvc, conversation, me, 'changed');
343
+ const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
344
+ const self = resolved.find((p) => p.mri.toLowerCase() === me.toLowerCase());
345
+ if (self !== undefined) {
346
+ throw new McpToolError(`Refusing to remove you (the signed-in user, "${self.person}") from the chat.`, {
347
+ hint: 'To leave a group chat, use Leave in Teams. Remove the others by passing them without yourself.',
348
+ });
349
+ }
350
+ const members = memberSet(await chatsvc.getThread(target.id));
351
+ const toRemove = resolved.filter((p) => members.has(p.mri.toLowerCase()));
352
+ const absent = resolved
353
+ .filter((p) => !members.has(p.mri.toLowerCase()))
354
+ .map((p) => ({ ...shown(p), status: 'not_member' }));
355
+ if (toRemove.length === 0) {
356
+ return untrustedResult({ status: 'unchanged', conversation: target, results: absent });
357
+ }
358
+ const gate = await confirmWrite(ctx, {
359
+ tool: REMOVE,
360
+ action: 'chat.remove_members',
361
+ message: 'Review and confirm who is removed from this group chat:',
362
+ summary: `Remove ${toRemove.length} ${toRemove.length === 1 ? 'person' : 'people'} from group chat ` +
363
+ JSON.stringify(target.title),
364
+ account: me,
365
+ target: target.id,
366
+ request: {
367
+ method: 'DELETE',
368
+ path: `/threads/${encodeURIComponent(target.id)}/members`,
369
+ body: { members: toRemove.map((p) => p.mri) },
370
+ },
371
+ preview: {
372
+ conversation: untrustedField(target),
373
+ remove: untrustedField(toRemove.map(shown)),
374
+ ...(absent.length > 0 ? { not_members: untrustedField(absent.map(shown)) } : {}),
375
+ note: 'Sent as one DELETE /threads/{id}/members/{mri} per person. Teams posts a notice in the chat for each ' +
376
+ 'person removed.',
377
+ },
378
+ confirmToken,
379
+ });
380
+ if (gate)
381
+ return gate;
382
+ const { results, warning } = await applyMemberChanges(chatsvc, target.id, toRemove, (mri) => chatsvc.removeMember(target.id, mri), 'removed');
383
+ return untrustedResult({
384
+ status: 'done',
385
+ conversation: target,
386
+ results: orderAs(resolved, [...results, ...absent]),
387
+ ...(warning !== undefined ? { warning } : {}),
388
+ });
389
+ }
390
+ catch (err) {
391
+ throw wrapApiError(err, 'remove people from the chat');
392
+ }
393
+ });
394
+ server.registerTool(CREATE, {
395
+ title: 'Create a Teams group chat',
396
+ description: 'Start a new group chat as the signed-in user with 2–20 other people, optionally named (topic). The user ' +
397
+ 'is always included (listing them is ignored), as are duplicates; fewer than two other people is refused — ' +
398
+ 'one other person is a 1:1, which this tool does not create. ' +
399
+ peopleSentence("the other person of each of the user's 1:1 chats") +
400
+ 'Everyone added sees the chat at once in their chat list, and it cannot be deleted afterwards — only ' +
401
+ 'left. No message is sent: post the first one with teams_send_message, passing the new conversation id. ' +
402
+ '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 "unknown" means Teams did not confirm the create — a chat may exist anyway, so check ' +
405
+ 'teams_list_conversations and do NOT retry blindly (that would make a second chat). ' +
406
+ CONFIRM_FLOW_SENTENCE +
407
+ ' The preview shows the topic and exactly who would be in the chat — each with their source (id, chat or ' +
408
+ 'directory) and, from the directory, their email — so the user can check it is the right people. ' +
409
+ CONFIRM_INJECTION_RULE +
410
+ UNTRUSTED_DESCRIPTION_SUFFIX,
411
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: false, openWorld: true }),
412
+ _meta: workMeta('send', {
413
+ aliases: ['create chat', 'new group chat', 'start a chat', 'new chat', 'group chat', 'start group chat'],
414
+ }),
415
+ inputSchema: {
416
+ people: z
417
+ .array(z.string().trim().min(1))
418
+ .min(2)
419
+ .max(MAX_PEOPLE)
420
+ .describe(`Who to start the chat with (2–20 others; you are added automatically): ` +
421
+ peopleParamText('the other people of your 1:1 chats')),
422
+ topic: z
423
+ .string()
424
+ .optional()
425
+ .describe('A name for the chat (surrounding spaces are trimmed). Omit or leave empty for an untitled chat.'),
426
+ confirmToken: confirmTokenParam,
427
+ },
428
+ }, async ({ people, topic: rawTopic, confirmToken }, ctx) => {
429
+ try {
430
+ const me = await chatsvc.meMri();
431
+ const topic = rawTopic?.trim() || undefined;
432
+ const others = (await resolveFor(chatsvc, substrate, me, undefined, people)).filter((p) => p.mri.toLowerCase() !== me.toLowerCase());
433
+ if (others.length < 2) {
434
+ 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
+ hint: 'Add at least one more person, or to talk to one person use your 1:1 chat with them (teams_send_message, ' +
436
+ 'conversation set to their name).',
437
+ });
438
+ }
439
+ const members = others.map(shown);
440
+ const allMris = [me, ...others.map((p) => p.mri)];
441
+ const count = `you and ${others.length} other people`;
442
+ const gate = await confirmWrite(ctx, {
443
+ tool: CREATE,
444
+ action: 'chat.create',
445
+ message: 'Review and confirm this new group chat before it is created — it cannot be deleted afterwards:',
446
+ // 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}`,
448
+ account: me,
449
+ target: 'new group chat',
450
+ request: { method: 'POST', path: '/threads', body: { members: allMris, ...(topic !== undefined ? { topic } : {}) } },
451
+ // The resolved names are set by other people, so they are fenced.
452
+ preview: {
453
+ topic: topic ?? '(untitled)',
454
+ members: untrustedField(members),
455
+ 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. No message is sent.',
457
+ },
458
+ confirmToken,
459
+ });
460
+ if (gate)
461
+ return gate;
462
+ let id;
463
+ try {
464
+ ({ id } = await chatsvc.createGroupChat(others.map((p) => p.mri), topic));
465
+ }
466
+ catch (e) {
467
+ if (!(e instanceof WriteOutcomeUnknownError))
468
+ throw e;
469
+ return untrustedResult({
470
+ status: 'unknown',
471
+ ...(topic !== undefined ? { topic } : {}),
472
+ members,
473
+ warning: `Teams did not confirm creating the chat (${unconfirmedWhy(e)}), so it may or may not exist. Check ` +
474
+ 'teams_list_conversations for a new group chat with these people (no messages yet) before doing ' +
475
+ 'anything else — do NOT retry blindly: if it was created, retrying makes a second chat, and chats ' +
476
+ 'cannot be deleted.',
477
+ });
478
+ }
479
+ let warning;
480
+ let verified;
481
+ try {
482
+ const thread = await chatsvc.getThread(id);
483
+ const present = memberSet(thread);
484
+ const missing = allMris.filter((m) => !present.has(m.toLowerCase()));
485
+ const shownTopic = thread.properties?.topic || undefined;
486
+ const notes = [];
487
+ if (missing.length > 0)
488
+ notes.push(`did not show ${missing.join(', ')} as a member`);
489
+ if (shownTopic !== topic)
490
+ notes.push(`showed the topic as ${JSON.stringify(shownTopic ?? '')}`);
491
+ verified = notes.length === 0;
492
+ if (!verified) {
493
+ warning = `Teams created the chat, but reading it back ${notes.join(' and ')} — check it in Teams (do not create it again).`;
494
+ }
495
+ }
496
+ catch {
497
+ verified = null;
498
+ warning = 'Teams created the chat, but reading the chat back failed — check it in teams_list_conversations (do not create it again).';
499
+ }
500
+ return untrustedResult({
501
+ status: 'created',
502
+ conversation: { id, title: topic ?? UNTITLED_GROUP_TITLE, kind: 'group' },
503
+ ...(topic !== undefined ? { topic } : {}),
504
+ members,
505
+ verified,
506
+ ...(warning !== undefined ? { warning } : {}),
507
+ });
508
+ }
509
+ catch (err) {
510
+ throw wrapApiError(err, 'create the group chat');
511
+ }
512
+ });
513
+ }
514
+ /** `results` in the order the people were asked for. */
515
+ function orderAs(people, results) {
516
+ return people.map((p) => results.find((r) => r.mri === p.mri));
517
+ }
@@ -3,13 +3,13 @@ import { credentialHealthcheckDescription, runCredentialHealthcheck } from '@chr
3
3
  const HOST_LABEL = 'teams.cloud.microsoft';
4
4
  const TITLE = 'Verify the Teams chat-service token and API end-to-end';
5
5
  /**
6
- * Static note on the SharePoint path: a separate token, captured on demand per
7
- * host and short-lived, that `teams_get_attachment` uses for shared-file
6
+ * Static note on the SharePoint path: a separate token, captured on demand and
7
+ * short-lived, that `teams_get_attachment` uses for shared-file
8
8
  * download. Not probed here — a healthy result never depends on it existing.
9
9
  */
10
10
  const SHAREPOINT_NOTE = 'Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on ' +
11
- 'demand per SharePoint host and short-lived (~53 min). None is held until you open a file, and ' +
12
- 'this healthcheck neither mints nor requires one.';
11
+ 'demand and short-lived; one token serves every SharePoint host. None is held until you download ' +
12
+ 'a file, and this healthcheck neither mints nor requires one.';
13
13
  /** Static note on the search path. Not probed — a healthy result never depends on it. */
14
14
  const SUBSTRATE_NOTE = 'Search (teams_search_messages) uses a separate Microsoft Substrate token for substrate.office.com, ' +
15
15
  'captured on demand when you run a search in a Teams tab (the bridge pairing must trust ' +