@chrischall/microsoft-teams-mcp 0.8.7 → 0.9.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,385 @@
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 { wrapApiError } from './errors.js';
4
+ import { workMeta } from './hints.js';
5
+ import { knownPeople, resolvePeople } from './people.js';
6
+ import { resolveTarget, SELF_CHAT } from './send.js';
7
+ import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
8
+ const RENAME = 'teams_rename_chat';
9
+ const ADD = 'teams_add_chat_members';
10
+ const REMOVE = 'teams_remove_chat_members';
11
+ /** Most people one call adds or removes. */
12
+ const MAX_PEOPLE = 20;
13
+ const KIND_LABELS = {
14
+ oneOnOne: 'a 1:1 chat',
15
+ meeting: 'a meeting chat',
16
+ channel: 'a channel',
17
+ self: 'your notes self-chat',
18
+ };
19
+ const conversationParam = z
20
+ .string()
21
+ .min(1)
22
+ .describe('The group chat: its id (from teams_list_conversations), or a case-insensitive substring of its title or ' +
23
+ "an untitled chat's participant names.");
24
+ const peopleParam = z
25
+ .array(z.string().trim().min(1))
26
+ .min(1)
27
+ .max(MAX_PEOPLE)
28
+ .describe('Who: 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 the other people ' +
30
+ 'of your 1:1 chats and recent senders in this chat, then — only if no one there matches — in the directory.');
31
+ const PEOPLE_SENTENCE = 'people are MRIs (8:orgid:…), bare object ids, email addresses, or display names. A name is matched ' +
32
+ '(ignoring case, in either "First Last" or "Last, First" order) among the other person of each of the ' +
33
+ "user's 1:1 chats and the chat's recent senders first; only when no one there matches is the organisation's " +
34
+ 'directory searched, where the one person with exactly that name is taken (or the only suggestion, when the ' +
35
+ 'name is whole words of it). An email address is looked up in the directory and must be exactly one ' +
36
+ "person's email or UPN. An ambiguous or unknown person refuses the whole call, listing candidates. The " +
37
+ 'directory is searched with the same token as teams_search_messages: the first lookup may need the user to ' +
38
+ 'run any search in the Teams search box so it can be captured. ';
39
+ /** The conversation, refused unless it is a group chat. `doing` words the refusal ("renamed"). */
40
+ async function groupChat(chatsvc, conversation, me, doing) {
41
+ const target = await resolveTarget(chatsvc, conversation, me, `change`);
42
+ if (target.kind === 'group')
43
+ return target;
44
+ const what = KIND_LABELS[target.kind] ?? `a ${target.kind}`;
45
+ throw new McpToolError(`${JSON.stringify(target.title)} is ${what}, not a group chat: only a group chat can be ${doing}.`, {
46
+ hint: target.kind === 'oneOnOne'
47
+ ? 'A 1:1 cannot take more people or a name; start a group chat in Teams instead.'
48
+ : 'Pass a group chat (kind "group" in teams_list_conversations).',
49
+ });
50
+ }
51
+ /** Why Teams did not confirm a write, for a warning. */
52
+ function unconfirmedWhy(e) {
53
+ const status = writeOutcomeStatus(e);
54
+ return e.timedOut ? 'it did not answer in time' : status !== undefined ? `it answered HTTP ${status}` : 'the connection dropped';
55
+ }
56
+ /** The thread's members' MRIs, lower-cased. */
57
+ function memberSet(thread) {
58
+ return new Set((thread.members ?? []).map((m) => m.id.toLowerCase()));
59
+ }
60
+ /** A person as a preview or a result shows them: where they were found and, from the directory, their email. */
61
+ function shown(p) {
62
+ return {
63
+ person: p.person,
64
+ mri: p.mri,
65
+ ...(p.name !== undefined ? { name: p.name } : {}),
66
+ source: p.source,
67
+ ...(p.email !== undefined ? { email: p.email } : {}),
68
+ };
69
+ }
70
+ /** People resolved and de-duplicated by MRI (the first naming of each kept). */
71
+ async function resolveFor(chatsvc, directory, me, conversationId, people) {
72
+ const known = await knownPeople(chatsvc, me, conversationId);
73
+ const seen = new Set();
74
+ return (await resolvePeople(people, known, directory)).filter((p) => {
75
+ const key = p.mri.toLowerCase();
76
+ if (seen.has(key))
77
+ return false;
78
+ seen.add(key);
79
+ return true;
80
+ });
81
+ }
82
+ /**
83
+ * Run one write per person, read the thread back once, and report each:
84
+ * `done` (shown, or Teams confirmed it — `verified` saying whether the
85
+ * read-back showed it, null when the read-back failed), `unknown` (Teams did
86
+ * not confirm and the read-back does not show it) or `failed` (refused).
87
+ */
88
+ async function applyMemberChanges(chatsvc, threadId, people, write, done) {
89
+ const outcomes = [];
90
+ for (const p of people) {
91
+ try {
92
+ await write(p.mri);
93
+ outcomes.push({ p });
94
+ }
95
+ catch (e) {
96
+ if (e instanceof WriteOutcomeUnknownError)
97
+ outcomes.push({ p, unconfirmed: e });
98
+ else
99
+ outcomes.push({ p, error: e instanceof Error ? e.message : String(e) });
100
+ }
101
+ }
102
+ let members;
103
+ try {
104
+ members = memberSet(await chatsvc.getThread(threadId));
105
+ }
106
+ catch {
107
+ members = undefined;
108
+ }
109
+ const changed = (mri) => {
110
+ const present = members?.has(mri.toLowerCase());
111
+ return present === undefined ? null : done === 'added' ? present : !present;
112
+ };
113
+ const notes = [];
114
+ const results = outcomes.map(({ p, unconfirmed, error }) => {
115
+ if (error !== undefined)
116
+ return { ...shown(p), status: 'failed', error };
117
+ const verified = changed(p.mri);
118
+ if (unconfirmed !== undefined && verified !== true) {
119
+ notes.push(`Teams did not confirm the change for ${p.mri} (${unconfirmedWhy(unconfirmed)}), and reading the chat back ` +
120
+ `${verified === null ? 'failed' : `did not show it ${done}`}.`);
121
+ return { ...shown(p), status: 'unknown', verified: verified ?? false };
122
+ }
123
+ if (unconfirmed !== undefined) {
124
+ notes.push(`Teams did not confirm the change for ${p.mri}, but reading the chat back shows it ${done}.`);
125
+ }
126
+ else if (verified === false) {
127
+ notes.push(`Teams accepted the change for ${p.mri}, but reading the chat back did not show it ${done}.`);
128
+ }
129
+ return { ...shown(p), status: done, verified };
130
+ });
131
+ if (members === undefined)
132
+ notes.push('Teams accepted the changes, but reading the chat back failed.');
133
+ if (results.some((r) => r.status === 'failed'))
134
+ notes.push("Some changes failed: see each person's error.");
135
+ if (notes.length === 0)
136
+ return { results };
137
+ return {
138
+ results,
139
+ warning: `${notes.join(' ')} Check the chat before retrying — running this tool again is safe: anyone already ` +
140
+ `${done === 'added' ? 'in the chat is reported as already_member' : 'gone is reported as not_member'} and not written again.`,
141
+ };
142
+ }
143
+ export function registerGroupChatTools(server, { chatsvc, substrate }) {
144
+ server.registerTool(RENAME, {
145
+ title: 'Rename a Teams group chat',
146
+ description: "Rename a group chat (set its topic) as the signed-in user. conversation is the chat's id or name as for " +
147
+ `teams_list_messages; only group chats can be renamed — 1:1s, meeting chats, channels and the self-chat ` +
148
+ `(${SELF_CHAT}) are refused. Teams posts a notice in the chat that the user renamed it, so everyone in it ` +
149
+ 'sees the change. Renaming to the current name changes nothing and asks for no confirmation. The result ' +
150
+ 'says whether reading the chat back showed the new name (verified); status "unknown" means Teams did not ' +
151
+ 'confirm the change and the read-back did not show it — check the chat before retrying. ' +
152
+ CONFIRM_FLOW_SENTENCE +
153
+ ' The preview shows the chat, its current name and the new one. ' +
154
+ CONFIRM_INJECTION_RULE +
155
+ UNTRUSTED_DESCRIPTION_SUFFIX,
156
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
157
+ _meta: workMeta('send', { aliases: ['rename chat', 'rename', 'chat name', 'topic', 'set topic'] }),
158
+ inputSchema: {
159
+ conversation: conversationParam,
160
+ name: z.string().trim().min(1).describe('The new name for the chat (surrounding spaces are trimmed).'),
161
+ confirmToken: confirmTokenParam,
162
+ },
163
+ }, async ({ conversation, name, confirmToken }, ctx) => {
164
+ try {
165
+ const me = await chatsvc.meMri();
166
+ const target = await groupChat(chatsvc, conversation, me, 'renamed');
167
+ const current = (await chatsvc.getThread(target.id)).properties?.topic ?? '';
168
+ if (current === name) {
169
+ return untrustedResult({ status: 'unchanged', conversation: target, name });
170
+ }
171
+ const path = `/threads/${encodeURIComponent(target.id)}/properties?name=topic`;
172
+ const gate = await confirmWrite(ctx, {
173
+ tool: RENAME,
174
+ action: 'chat.rename',
175
+ message: 'Review and confirm this group chat rename before it is made:',
176
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
177
+ summary: `Rename group chat ${JSON.stringify(target.title)} to ${JSON.stringify(name)}`,
178
+ // The signed-in user, so an approval minted under one account never acts as another.
179
+ account: me,
180
+ target: target.id,
181
+ request: { method: 'PUT', path, body: { topic: name } },
182
+ // The title and the current name are set by other people, so each is fenced.
183
+ preview: {
184
+ conversation: untrustedField(target),
185
+ current_name: untrustedField(current),
186
+ new_name: name,
187
+ note: 'Teams posts a notice in the chat that you renamed it.',
188
+ },
189
+ confirmToken,
190
+ });
191
+ if (gate)
192
+ return gate;
193
+ let unconfirmed;
194
+ try {
195
+ await chatsvc.setTopic(target.id, name);
196
+ }
197
+ catch (e) {
198
+ if (!(e instanceof WriteOutcomeUnknownError))
199
+ throw e;
200
+ unconfirmed = e;
201
+ }
202
+ let verified = false;
203
+ try {
204
+ verified = (await chatsvc.getThread(target.id)).properties?.topic === name;
205
+ }
206
+ catch {
207
+ verified = null;
208
+ }
209
+ const base = { conversation: target, previous_name: current, name };
210
+ if (unconfirmed !== undefined && verified !== true) {
211
+ return untrustedResult({
212
+ status: 'unknown',
213
+ ...base,
214
+ verified: verified ?? false,
215
+ warning: `Teams did not confirm this rename (${unconfirmedWhy(unconfirmed)}), and reading the chat back ` +
216
+ `${verified === null ? 'failed' : 'did not show the new name'} — check the chat (teams_list_conversations) ` +
217
+ 'before retrying; renaming again to the same name is harmless.',
218
+ });
219
+ }
220
+ let warning;
221
+ if (unconfirmed !== undefined) {
222
+ warning = 'Teams did not confirm this rename, but reading the chat back shows the new name.';
223
+ }
224
+ else if (verified === null) {
225
+ warning = 'Teams accepted the rename, but reading the chat back failed — check the chat (teams_list_conversations).';
226
+ }
227
+ else if (!verified) {
228
+ warning = 'Teams accepted the rename, but reading the chat back did not show the new name — check the chat (teams_list_conversations).';
229
+ }
230
+ return untrustedResult({ status: 'renamed', ...base, verified, ...(warning !== undefined ? { warning } : {}) });
231
+ }
232
+ catch (err) {
233
+ throw wrapApiError(err, 'rename the chat');
234
+ }
235
+ });
236
+ server.registerTool(ADD, {
237
+ title: 'Add people to a Teams group chat',
238
+ description: 'Add people to a group chat as the signed-in user, as ordinary members. conversation is the chat\'s id or ' +
239
+ 'name as for teams_list_messages; only group chats take people — 1:1s, meeting chats, channels and the ' +
240
+ `self-chat are refused. ${PEOPLE_SENTENCE}People already in the chat are reported as already_member and ` +
241
+ 'not written; if everyone is, nothing is asked or changed. Teams posts a notice in the chat for each person ' +
242
+ 'added, and they can read the chat\'s history as Teams allows. The result lists each person: added, ' +
243
+ 'already_member, unknown (Teams did not confirm and reading the chat back does not show them — check ' +
244
+ 'before retrying) or failed (with the error). ' +
245
+ CONFIRM_FLOW_SENTENCE +
246
+ ' The preview shows the chat and exactly who would be added — each with their source (id, chat or ' +
247
+ 'directory) and, from the directory, their email — so the user can check it is the right person. ' +
248
+ CONFIRM_INJECTION_RULE +
249
+ UNTRUSTED_DESCRIPTION_SUFFIX,
250
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
251
+ _meta: workMeta('send', { aliases: ['add people', 'add to chat', 'invite', 'add members', 'members'] }),
252
+ inputSchema: {
253
+ conversation: conversationParam,
254
+ people: peopleParam,
255
+ confirmToken: confirmTokenParam,
256
+ },
257
+ }, async ({ conversation, people, confirmToken }, ctx) => {
258
+ try {
259
+ const me = await chatsvc.meMri();
260
+ const target = await groupChat(chatsvc, conversation, me, 'given more people');
261
+ const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
262
+ const members = memberSet(await chatsvc.getThread(target.id));
263
+ const already = resolved.filter((p) => members.has(p.mri.toLowerCase()));
264
+ const toAdd = resolved.filter((p) => !members.has(p.mri.toLowerCase()));
265
+ const alreadyResults = already.map((p) => ({ ...shown(p), status: 'already_member' }));
266
+ if (toAdd.length === 0) {
267
+ return untrustedResult({ status: 'unchanged', conversation: target, results: alreadyResults });
268
+ }
269
+ const gate = await confirmWrite(ctx, {
270
+ tool: ADD,
271
+ action: 'chat.add_members',
272
+ message: 'Review and confirm who is added to this group chat:',
273
+ summary: `Add ${toAdd.length} ${toAdd.length === 1 ? 'person' : 'people'} to group chat ${JSON.stringify(target.title)}`,
274
+ account: me,
275
+ target: target.id,
276
+ request: {
277
+ method: 'PUT',
278
+ path: `/threads/${encodeURIComponent(target.id)}/members`,
279
+ body: { members: toAdd.map((p) => ({ id: p.mri, role: 'User' })) },
280
+ },
281
+ // The title and the resolved names are set by other people, so each is fenced.
282
+ preview: {
283
+ conversation: untrustedField(target),
284
+ add: untrustedField(toAdd.map(shown)),
285
+ ...(already.length > 0 ? { already_members: untrustedField(already.map(shown)) } : {}),
286
+ note: 'Sent as one PUT /threads/{id}/members/{mri} with {"role":"User"} per person. Teams posts a notice in ' +
287
+ 'the chat for each person added.',
288
+ },
289
+ confirmToken,
290
+ });
291
+ if (gate)
292
+ return gate;
293
+ const { results, warning } = await applyMemberChanges(chatsvc, target.id, toAdd, (mri) => chatsvc.addMember(target.id, mri, 'User'), 'added');
294
+ return untrustedResult({
295
+ status: 'done',
296
+ conversation: target,
297
+ results: orderAs(resolved, [...results, ...alreadyResults]),
298
+ ...(warning !== undefined ? { warning } : {}),
299
+ });
300
+ }
301
+ catch (err) {
302
+ throw wrapApiError(err, 'add people to the chat');
303
+ }
304
+ });
305
+ server.registerTool(REMOVE, {
306
+ title: 'Remove people from a Teams group chat',
307
+ description: 'Remove people from a group chat as the signed-in user. conversation is the chat\'s id or name as for ' +
308
+ 'teams_list_messages; only group chats are changed — 1:1s, meeting chats, channels and the self-chat are ' +
309
+ `refused, and so is removing the signed-in user (leave the chat in Teams instead). ${PEOPLE_SENTENCE}` +
310
+ 'People not in the chat are reported as not_member and not written; if no one is, nothing is asked or ' +
311
+ 'changed. Teams posts a notice in the chat for each person removed, and they lose access to it. The ' +
312
+ 'result lists each person: removed, not_member, unknown (Teams did not confirm and reading the chat back ' +
313
+ 'still shows them — check before retrying) or failed (with the error). ' +
314
+ CONFIRM_FLOW_SENTENCE +
315
+ ' The preview shows the chat and exactly who would be removed — each with their source (id, chat or ' +
316
+ 'directory) and, from the directory, their email. ' +
317
+ CONFIRM_INJECTION_RULE +
318
+ UNTRUSTED_DESCRIPTION_SUFFIX,
319
+ annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: true, openWorld: true }),
320
+ _meta: workMeta('send', { aliases: ['remove people', 'remove from chat', 'kick', 'remove members', 'members'] }),
321
+ inputSchema: {
322
+ conversation: conversationParam,
323
+ people: peopleParam,
324
+ confirmToken: confirmTokenParam,
325
+ },
326
+ }, async ({ conversation, people, confirmToken }, ctx) => {
327
+ try {
328
+ const me = await chatsvc.meMri();
329
+ const target = await groupChat(chatsvc, conversation, me, 'changed');
330
+ const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
331
+ const self = resolved.find((p) => p.mri.toLowerCase() === me.toLowerCase());
332
+ if (self !== undefined) {
333
+ throw new McpToolError(`Refusing to remove you (the signed-in user, "${self.person}") from the chat.`, {
334
+ hint: 'To leave a group chat, use Leave in Teams. Remove the others by passing them without yourself.',
335
+ });
336
+ }
337
+ const members = memberSet(await chatsvc.getThread(target.id));
338
+ const toRemove = resolved.filter((p) => members.has(p.mri.toLowerCase()));
339
+ const absent = resolved
340
+ .filter((p) => !members.has(p.mri.toLowerCase()))
341
+ .map((p) => ({ ...shown(p), status: 'not_member' }));
342
+ if (toRemove.length === 0) {
343
+ return untrustedResult({ status: 'unchanged', conversation: target, results: absent });
344
+ }
345
+ const gate = await confirmWrite(ctx, {
346
+ tool: REMOVE,
347
+ action: 'chat.remove_members',
348
+ message: 'Review and confirm who is removed from this group chat:',
349
+ summary: `Remove ${toRemove.length} ${toRemove.length === 1 ? 'person' : 'people'} from group chat ` +
350
+ JSON.stringify(target.title),
351
+ account: me,
352
+ target: target.id,
353
+ request: {
354
+ method: 'DELETE',
355
+ path: `/threads/${encodeURIComponent(target.id)}/members`,
356
+ body: { members: toRemove.map((p) => p.mri) },
357
+ },
358
+ preview: {
359
+ conversation: untrustedField(target),
360
+ remove: untrustedField(toRemove.map(shown)),
361
+ ...(absent.length > 0 ? { not_members: untrustedField(absent.map(shown)) } : {}),
362
+ note: 'Sent as one DELETE /threads/{id}/members/{mri} per person. Teams posts a notice in the chat for each ' +
363
+ 'person removed.',
364
+ },
365
+ confirmToken,
366
+ });
367
+ if (gate)
368
+ return gate;
369
+ const { results, warning } = await applyMemberChanges(chatsvc, target.id, toRemove, (mri) => chatsvc.removeMember(target.id, mri), 'removed');
370
+ return untrustedResult({
371
+ status: 'done',
372
+ conversation: target,
373
+ results: orderAs(resolved, [...results, ...absent]),
374
+ ...(warning !== undefined ? { warning } : {}),
375
+ });
376
+ }
377
+ catch (err) {
378
+ throw wrapApiError(err, 'remove people from the chat');
379
+ }
380
+ });
381
+ }
382
+ /** `results` in the order the people were asked for. */
383
+ function orderAs(people, results) {
384
+ return people.map((p) => results.find((r) => r.mri === p.mri));
385
+ }
@@ -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 ' +
@@ -0,0 +1,236 @@
1
+ /**
2
+ * People by name, for the tools that act on someone: a group chat's members
3
+ * (`teams_add_chat_members`, `teams_remove_chat_members`) and a message's
4
+ * @mentions (`teams_send_message`).
5
+ *
6
+ * A person is, in this order:
7
+ * - an MRI (`8:orgid:<oid>`) or a bare oid — taken as is (source `id`);
8
+ * - an email address (has an `@`) — looked up in the directory (Substrate's
9
+ * people suggestions, `substrate.ts`), and taken only when exactly one
10
+ * person there has that email or UPN, ignoring case;
11
+ * - a display name — matched first among the people this MCP can already
12
+ * see (source `chat`): the other person of each 1:1 chat (named as
13
+ * `tools/titles.ts` names that 1:1) and the recent senders of the chat
14
+ * being changed; exact (as {@link normaliseName} compares), else
15
+ * substring; several is refused. ONLY when that finds no one is the
16
+ * directory asked (source `directory`), and a suggestion is taken only
17
+ * when it is (a) the one suggestion whose normalised name equals the
18
+ * query's, or (b) the ONLY suggestion and the normalised query is a run of
19
+ * whole words of its normalised name ("solomon" or "gary" for "Solomon,
20
+ * Gary", never "sol"). Anything else is refused, listing the suggestions.
21
+ *
22
+ * A name is never guessed: ambiguous or unknown is an error. The chat
23
+ * service's own user-search endpoints answer 401 with the chat-service token
24
+ * (live, 2026-11-09), so the directory is reached through Substrate with the
25
+ * token search already captures.
26
+ */
27
+ import { McpToolError } from '@chrischall/mcp-utils';
28
+ import { isUserMessage, oneOnOnePeerMri, senderMri, summariseAll } from '../model.js';
29
+ import { enrichTitles } from './titles.js';
30
+ import { THIRD_PARTY_NAMES_NOTE } from './untrusted.js';
31
+ /** An MRI such as `8:orgid:<oid>` (a person) or `28:<id>` (a bot). */
32
+ export const MRI = /^\d+:\S+$/;
33
+ /** A bare Entra object id. */
34
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
35
+ /** Recent messages scanned for senders. */
36
+ const RECENT_MESSAGES = 200;
37
+ /** Candidates an error lists. */
38
+ const MAX_CANDIDATES = 10;
39
+ /** The MRI an input names directly — an MRI as is, a bare GUID as `8:orgid:<guid>` — else `undefined` (a name). */
40
+ export function personMri(input) {
41
+ const s = input.trim();
42
+ if (MRI.test(s))
43
+ return s;
44
+ if (GUID.test(s))
45
+ return `8:orgid:${s.toLowerCase()}`;
46
+ return undefined;
47
+ }
48
+ /**
49
+ * A name for comparing: lower-cased, spacing collapsed, and a "Last, First"
50
+ * display name (common in Teams) turned round to "first last".
51
+ */
52
+ export function normaliseName(name) {
53
+ const s = name.trim().toLowerCase().replace(/\s+/g, ' ');
54
+ const m = /^([^,]+),\s*([^,]+)$/.exec(s);
55
+ return m ? `${m[2].trim()} ${m[1].trim()}` : s;
56
+ }
57
+ /** Who has written in the conversation lately, by MRI → display name. */
58
+ export async function recentSenders(chatsvc, conversationId) {
59
+ const out = new Map();
60
+ for (const m of await chatsvc.getMessages(conversationId, { max: RECENT_MESSAGES })) {
61
+ const mri = senderMri(m.from);
62
+ const name = m.imdisplayname?.trim();
63
+ if (isUserMessage(m) && mri !== undefined && name && !out.has(mri))
64
+ out.set(mri, name);
65
+ }
66
+ return out;
67
+ }
68
+ /**
69
+ * Everyone this MCP can put a name to for `conversationId`: the other person
70
+ * of every 1:1 the user has (as that 1:1 is titled), then the chat's recent
71
+ * senders. One entry per MRI (ignoring case), the 1:1 name winning. Never
72
+ * throws — a failed read just knows fewer people.
73
+ */
74
+ export async function knownPeople(chatsvc, me, conversationId) {
75
+ const byMri = new Map();
76
+ const add = (mri, name) => {
77
+ const key = mri.toLowerCase();
78
+ if (name.trim() && !byMri.has(key))
79
+ byMri.set(key, { mri, name: name.trim() });
80
+ };
81
+ try {
82
+ const raw = await chatsvc.listConversations();
83
+ const oneOnOnes = summariseAll(raw, me).filter((s) => s.kind === 'oneOnOne');
84
+ for (const s of await enrichTitles(chatsvc, raw, me, oneOnOnes)) {
85
+ const peer = oneOnOnePeerMri(s.id, me);
86
+ const name = s.participants?.[0];
87
+ if (peer !== undefined && name !== undefined)
88
+ add(peer, name);
89
+ }
90
+ }
91
+ catch {
92
+ // No 1:1 names; the chat's own senders may still do.
93
+ }
94
+ try {
95
+ for (const [mri, name] of await recentSenders(chatsvc, conversationId))
96
+ add(mri, name);
97
+ }
98
+ catch {
99
+ // Fewer names, not a failure.
100
+ }
101
+ return [...byMri.values()];
102
+ }
103
+ /** The known name of `mri`, if any. */
104
+ export function knownName(mri, known) {
105
+ const key = mri.toLowerCase();
106
+ return known.find((k) => k.mri.toLowerCase() === key)?.name;
107
+ }
108
+ /** An email address, as opposed to a name. */
109
+ function isEmail(input) {
110
+ return /^[^@\s]+@[^@\s]+$/.test(input.trim());
111
+ }
112
+ /** Candidates, JSON-quoted (they are other people's display names), with email when known and MRI. */
113
+ function candidateList(people) {
114
+ return people
115
+ .slice(0, MAX_CANDIDATES)
116
+ .map((k) => {
117
+ const email = k.email ?? k.upn;
118
+ return `${JSON.stringify(k.name)}${email !== undefined ? ` <${email}>` : ''} (${k.mri})`;
119
+ })
120
+ .join('; ');
121
+ }
122
+ /** The local match for a name: one person, none (`undefined`), or a refusal when several match. */
123
+ function matchKnown(person, known) {
124
+ const q = normaliseName(person);
125
+ const raw = person.trim().toLowerCase();
126
+ const exact = known.filter((k) => normaliseName(k.name) === q);
127
+ const found = exact.length > 0
128
+ ? exact
129
+ : known.filter((k) => normaliseName(k.name).includes(q) || k.name.toLowerCase().includes(raw));
130
+ if (found.length === 1)
131
+ return found[0];
132
+ if (found.length > 1) {
133
+ throw new McpToolError(`"${person}" matches ${found.length} people: ${candidateList(found)}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'Pass the MRI (8:orgid:…) of the one you mean.' });
134
+ }
135
+ return undefined;
136
+ }
137
+ const PASS_ID = "Pass the person's email address or MRI (8:orgid:…) instead.";
138
+ /** A directory failure as the refusal for `person`, keeping the failure's message, kind and remedy. */
139
+ function directoryFailed(person, err, email) {
140
+ const message = err instanceof Error ? err.message : String(err);
141
+ const own = err instanceof McpToolError ? err.hint : undefined;
142
+ const remedy = own ??
143
+ 'Run any search in the Teams search box of a signed-in Teams tab while retrying (that is what lets this ' +
144
+ 'server capture the token it searches the directory with).';
145
+ const lead = email ? `Could not look up "${person}" because` : `No one in your chats is called "${person}", and`;
146
+ return new McpToolError(`${lead} the directory could not be searched: ${message}`, {
147
+ hint: `${remedy} Or pass the person's MRI (8:orgid:…) instead.`,
148
+ ...(err instanceof McpToolError && err.kind !== undefined ? { kind: err.kind } : {}),
149
+ cause: err,
150
+ });
151
+ }
152
+ function fromDirectory(person, p) {
153
+ const email = p.email ?? p.upn;
154
+ return { person, mri: p.mri, name: p.name, source: 'directory', ...(email !== undefined ? { email } : {}) };
155
+ }
156
+ /** The one directory person an email names: their email or UPN equal to it, ignoring case. */
157
+ function pickByEmail(person, found) {
158
+ const want = person.trim().toLowerCase();
159
+ const hits = found.filter((p) => p.email?.toLowerCase() === want || p.upn?.toLowerCase() === want);
160
+ if (hits.length === 1)
161
+ return fromDirectory(person, hits[0]);
162
+ if (hits.length > 1) {
163
+ throw new McpToolError(`"${person}" is the address of ${hits.length} people in the directory: ${candidateList(hits)}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'Pass the MRI (8:orgid:…) of the one you mean.' });
164
+ }
165
+ throw new McpToolError(`No one in your organisation's directory has the address "${person}".`, {
166
+ hint: "Check the address, or pass the person's name or MRI (8:orgid:…) instead. Only people in your " +
167
+ 'organisation (not distribution lists or personal contacts) are found there.',
168
+ });
169
+ }
170
+ /**
171
+ * The one directory person a name means — see the module comment for the
172
+ * rule: a unique exact normalised match, or the only suggestion when the
173
+ * query is a run of whole words of its name. Otherwise refused.
174
+ */
175
+ function pickByName(person, found) {
176
+ const q = normaliseName(person);
177
+ const exact = found.filter((p) => normaliseName(p.name) === q);
178
+ if (exact.length === 1)
179
+ return fromDirectory(person, exact[0]);
180
+ if (exact.length > 1) {
181
+ throw new McpToolError(`"${person}" matches ${exact.length} people in the directory: ${candidateList(exact)}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'Pass the email address or MRI (8:orgid:…) of the one you mean.' });
182
+ }
183
+ if (found.length === 1 && ` ${normaliseName(found[0].name)} `.includes(` ${q} `))
184
+ return fromDirectory(person, found[0]);
185
+ if (found.length > 0) {
186
+ throw new McpToolError(`No one in your chats is called "${person}", and no one in the directory is called exactly that; it ` +
187
+ `suggested: ${candidateList(found)}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'If one of them is who you mean, pass their email address or MRI (8:orgid:…).' });
188
+ }
189
+ throw new McpToolError(`No one in your chats or your organisation's directory is called "${person}".`, {
190
+ hint: `${PASS_ID} A name is matched among the other person of each of your 1:1 chats and this chat's recent ` +
191
+ "senders, then searched in your organisation's directory.",
192
+ });
193
+ }
194
+ /**
195
+ * Each requested person's MRI (and name, source and — from the directory —
196
+ * email), by the rules in the module comment. Every person resolves or the
197
+ * call throws, naming the candidates or the failure. Local matching runs for
198
+ * every input first, so a local ambiguity refuses before the directory is
199
+ * asked; then the directory is asked once per distinct input that needs it
200
+ * (`force`, so a retry after running a Teams search really re-captures).
201
+ */
202
+ export async function resolvePeople(inputs, known, directory) {
203
+ const local = inputs.map((person) => {
204
+ const direct = personMri(person);
205
+ if (direct !== undefined) {
206
+ const name = knownName(direct, known);
207
+ return { person, mri: direct, ...(name !== undefined ? { name } : {}), source: 'id' };
208
+ }
209
+ if (isEmail(person))
210
+ return { person, email: true };
211
+ const k = matchKnown(person, known);
212
+ return k !== undefined ? { person, mri: k.mri, name: k.name, source: 'chat' } : { person, email: false };
213
+ });
214
+ const asked = new Map();
215
+ const out = [];
216
+ for (const r of local) {
217
+ if ('mri' in r) {
218
+ out.push(r);
219
+ continue;
220
+ }
221
+ const text = r.person.trim();
222
+ const key = r.email ? `@${text.toLowerCase()}` : normaliseName(text);
223
+ let found = asked.get(key);
224
+ if (found === undefined) {
225
+ try {
226
+ found = await directory.suggestPeople(text, { force: true });
227
+ }
228
+ catch (err) {
229
+ throw directoryFailed(r.person, err, r.email);
230
+ }
231
+ asked.set(key, found);
232
+ }
233
+ out.push(r.email ? pickByEmail(r.person, found) : pickByName(r.person, found));
234
+ }
235
+ return out;
236
+ }