@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.
Files changed (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +241 -33
  4. package/dist/attachments.js +238 -0
  5. package/dist/auth-fetchproxy.js +7 -6
  6. package/dist/browser-open.js +138 -0
  7. package/dist/bundle.js +6840 -3949
  8. package/dist/capture-feedback.js +283 -0
  9. package/dist/chatsvc.js +132 -7
  10. package/dist/compose.js +9 -1
  11. package/dist/file-upload.js +335 -0
  12. package/dist/index.js +11 -1
  13. package/dist/model.js +1 -0
  14. package/dist/presence.js +120 -0
  15. package/dist/profile.js +182 -0
  16. package/dist/recap-auth.js +6 -4
  17. package/dist/recap.js +3 -1
  18. package/dist/sender-email.js +147 -0
  19. package/dist/sharepoint-auth.js +42 -21
  20. package/dist/sharepoint.js +150 -3
  21. package/dist/substrate-auth.js +8 -7
  22. package/dist/substrate.js +98 -4
  23. package/dist/tools/attach.js +167 -0
  24. package/dist/tools/attachment.js +3 -1
  25. package/dist/tools/conversation.js +14 -5
  26. package/dist/tools/edit.js +42 -14
  27. package/dist/tools/errors.js +10 -11
  28. package/dist/tools/export.js +30 -3
  29. package/dist/tools/format.js +29 -6
  30. package/dist/tools/group-chat.js +349 -33
  31. package/dist/tools/healthcheck.js +23 -9
  32. package/dist/tools/mention-check.js +225 -0
  33. package/dist/tools/people.js +149 -39
  34. package/dist/tools/profile.js +67 -0
  35. package/dist/tools/send.js +134 -37
  36. package/dist/tools/sender-email-arg.js +37 -0
  37. package/dist/tools/token-status.js +97 -0
  38. package/dist/tools/unread.js +3 -2
  39. package/dist/tools/upload-slots.js +51 -0
  40. package/dist/version.js +1 -1
  41. package/mint.yaml +19 -0
  42. package/package.json +4 -1
  43. package/server.json +30 -2
  44. package/skills/teams-fpx/references/teams-env.sh +1 -1
@@ -0,0 +1,225 @@
1
+ import { mentionRanges } from '../compose.js';
2
+ import { oneOnOnePeerMri, summariseAll } from '../model.js';
3
+ import { normaliseName } from './people.js';
4
+ /** A channel's (or team's) thread id: `19:…@thread.tacv2`, or the older `…@thread.skype`. */
5
+ export const CHANNEL_ID = /^19:\S+@thread\.(?:tacv2|skype)$/i;
6
+ /**
7
+ * The channel scope for `mentions`: read only when a mention could name a
8
+ * channel — the conversation is a channel, or a mention's person is a
9
+ * channel/team id. One listing read; a failed read just knows less.
10
+ */
11
+ export async function mentionScope(chatsvc, me, target, mentions) {
12
+ const inChannel = target.kind === 'channel';
13
+ if (mentions.length === 0 || (!inChannel && !mentions.some((m) => CHANNEL_ID.test(m.person.trim()))))
14
+ return undefined;
15
+ const channel = inChannel ? { id: target.id, title: target.title } : undefined;
16
+ try {
17
+ const raw = await chatsvc.listConversations();
18
+ const summaries = summariseAll(raw, me);
19
+ const threads = new Map(summaries.filter((s) => CHANNEL_ID.test(s.id)).map((s) => [s.id.toLowerCase(), s.title]));
20
+ const spaceId = inChannel ? raw.find((c) => c.id === target.id)?.threadProperties?.spaceId : undefined;
21
+ const teamName = inChannel ? summaries.find((s) => s.id === target.id)?.team : undefined;
22
+ const team = spaceId !== undefined && teamName !== undefined ? { id: spaceId, name: teamName } : undefined;
23
+ return { ...(channel ? { channel } : {}), ...(team ? { team } : {}), threads };
24
+ }
25
+ catch {
26
+ return { ...(channel ? { channel } : {}), threads: new Map() };
27
+ }
28
+ }
29
+ /** The channel or team of the conversation that `name` names exactly (ignoring case and spacing). */
30
+ export function scopeByName(scope, name) {
31
+ if (scope === undefined)
32
+ return undefined;
33
+ const q = normaliseName(name);
34
+ if (scope.channel !== undefined && normaliseName(scope.channel.title) === q) {
35
+ return { id: scope.channel.id, type: 'channel', name: scope.channel.title };
36
+ }
37
+ if (scope.team !== undefined && normaliseName(scope.team.name) === q)
38
+ return { id: scope.team.id, type: 'team', name: scope.team.name };
39
+ return undefined;
40
+ }
41
+ /** What a channel/team id names: the conversation's team, else a channel (its title when listed). */
42
+ export function scopeById(scope, id) {
43
+ const key = id.toLowerCase();
44
+ if (scope?.channel !== undefined && scope.channel.id.toLowerCase() === key)
45
+ return { type: 'channel', name: scope.channel.title };
46
+ if (scope?.team !== undefined && scope.team.id.toLowerCase() === key)
47
+ return { type: 'team', name: scope.team.name };
48
+ const title = scope?.threads.get(key);
49
+ return { type: 'channel', ...(title !== undefined ? { name: title } : {}) };
50
+ }
51
+ const WORD = /[\p{L}\p{N}_]/u;
52
+ /** A character that, before an "@", makes it part of an address (`a@b.com`) rather than a mention. */
53
+ const ADDRESS_CHAR = /[\p{L}\p{N}_.+\-%]/u;
54
+ const LETTER = /\p{L}/u;
55
+ const ONE_WORD = /^[\p{L}\p{N}_]+(?:[.-][\p{L}\p{N}_]+)*/u;
56
+ /** Spans whose "@"s never count: fenced code, inline code, URLs. */
57
+ const SKIPPED = /```[\s\S]*?(?:```|$)|`[^`\n]*`|\b(?:https?:\/\/|www\.)\S+/giu;
58
+ /**
59
+ * Every "@name" in `text` that no mention covers (`taken`, from
60
+ * `mentionRanges`), as written, once each — see the heuristic above.
61
+ * `known` are display names a multi-word "@name" is matched against.
62
+ */
63
+ export function unmatchedMentions(text, taken, known) {
64
+ const skipped = [...text.matchAll(SKIPPED)].map((m) => [m.index, m.index + m[0].length]);
65
+ const inside = (spans, i) => spans.some(([s, e]) => i >= s && i < e);
66
+ const names = [...new Set(known.map((k) => k.trim()).filter((k) => k !== ''))].sort((a, b) => b.length - a.length);
67
+ const out = [];
68
+ const seen = new Set();
69
+ for (let i = text.indexOf('@'); i >= 0; i = text.indexOf('@', i + 1)) {
70
+ if (i > 0 && ADDRESS_CHAR.test(text[i - 1]))
71
+ continue;
72
+ if (!LETTER.test(text[i + 1] ?? ''))
73
+ continue;
74
+ if (inside(skipped, i) || inside(taken, i) || inside(taken, i + 1))
75
+ continue;
76
+ const rest = text.slice(i + 1);
77
+ const lower = rest.toLowerCase();
78
+ const longest = names.find((n) => lower.startsWith(n.toLowerCase()) && !WORD.test(rest[n.length] ?? ''));
79
+ const name = longest !== undefined ? rest.slice(0, longest.length) : ONE_WORD.exec(rest)?.[0];
80
+ if (name === undefined)
81
+ continue;
82
+ const key = name.toLowerCase();
83
+ if (seen.has(key))
84
+ continue;
85
+ seen.add(key);
86
+ out.push(`@${name}`);
87
+ }
88
+ return out;
89
+ }
90
+ /** A conversation kind in words, for a note. */
91
+ function kindWords(kind) {
92
+ switch (kind) {
93
+ case 'group':
94
+ return 'group chat';
95
+ case 'meeting':
96
+ return 'meeting chat';
97
+ case 'oneOnOne':
98
+ return '1:1 chat';
99
+ case 'self':
100
+ return 'self-chat';
101
+ default:
102
+ return kind;
103
+ }
104
+ }
105
+ /**
106
+ * The conversation's member MRIs (lower-cased), from data that names them:
107
+ * a 1:1's id, the self-chat, else the chat's member list (one read). A
108
+ * channel's members are its team's, which this MCP cannot list: `undefined`,
109
+ * as is a failed read.
110
+ */
111
+ async function membersOf(chatsvc, target, me) {
112
+ if (target.kind === 'channel')
113
+ return undefined;
114
+ if (target.kind === 'self')
115
+ return new Set([me.toLowerCase()]);
116
+ const peer = target.kind === 'oneOnOne' ? oneOnOnePeerMri(target.id, me) : undefined;
117
+ if (peer !== undefined)
118
+ return new Set([me.toLowerCase(), peer.toLowerCase()]);
119
+ try {
120
+ const thread = await chatsvc.getThread(target.id);
121
+ if (thread.members === undefined || thread.members.length === 0)
122
+ return undefined;
123
+ return new Set(thread.members.map((m) => m.id.toLowerCase()));
124
+ }
125
+ catch {
126
+ return undefined;
127
+ }
128
+ }
129
+ /**
130
+ * Check what `text` will mention: each mention's type, name and membership,
131
+ * the "@name"s no mention covers, and the notes to show. `senders` loads the
132
+ * conversation's recent senders (MRI → name) at most once; it is only called
133
+ * when a name is needed. Never throws for a failed read — it knows less.
134
+ */
135
+ export async function checkMentions(chatsvc, { target, me, text, mentions, scope, senders, }) {
136
+ const safeSenders = async () => {
137
+ try {
138
+ const all = await senders();
139
+ return new Map([...all].map(([mri, name]) => [mri.toLowerCase(), name]));
140
+ }
141
+ catch {
142
+ return new Map();
143
+ }
144
+ };
145
+ let known;
146
+ const sendersOnce = async () => (known ??= await safeSenders());
147
+ const people = mentions.filter((m) => m.type === 'person');
148
+ const members = people.length > 0 ? await membersOf(chatsvc, target, me) : undefined;
149
+ const needNames = people.some((m) => m.name === undefined) || (people.length > 0 && target.kind === 'channel');
150
+ const named = needNames ? await sendersOnce() : new Map();
151
+ const views = mentions.map((m) => {
152
+ const mri = m.target.mri;
153
+ const name = m.name ?? (m.type === 'person' ? named.get(mri.toLowerCase()) : undefined);
154
+ let in_conversation;
155
+ if (m.type === 'person') {
156
+ if (members !== undefined)
157
+ in_conversation = members.has(mri.toLowerCase());
158
+ // In a channel, someone who posted lately is in it; anyone else may be.
159
+ else
160
+ in_conversation = target.kind === 'channel' && named.has(mri.toLowerCase()) ? true : 'unknown';
161
+ }
162
+ return {
163
+ name_in_text: m.name_in_text,
164
+ person: m.person,
165
+ mri,
166
+ mention_type: m.type,
167
+ ...(name !== undefined ? { name } : {}),
168
+ ...(in_conversation !== undefined ? { in_conversation } : {}),
169
+ };
170
+ });
171
+ const notes = [];
172
+ for (const v of views) {
173
+ const shown = JSON.stringify(v.name ?? v.name_in_text);
174
+ if (v.mention_type === 'person' && v.in_conversation === false) {
175
+ notes.push(`${shown} (${v.mri}) is not a member of this ${kindWords(target.kind)}: the mention is still sent, but they are ` +
176
+ 'not in the conversation to see it. Check that this is the right person.');
177
+ }
178
+ if (v.mention_type !== 'person') {
179
+ const here = scope?.channel?.id.toLowerCase() === v.mri.toLowerCase() || scope?.team?.id.toLowerCase() === v.mri.toLowerCase();
180
+ if (!here) {
181
+ notes.push(`The mention of ${shown} (${v.mri}) names a different channel than the one being posted to ` +
182
+ `(${target.kind === 'channel' ? JSON.stringify(target.title) : `this is a ${kindWords(target.kind)}`}).`);
183
+ }
184
+ }
185
+ }
186
+ // Unmatched "@names": a cheap pass first; known names are read only when one turns up.
187
+ const taken = mentionRanges(text, mentions.map((m) => m.target));
188
+ let unmatched = unmatchedMentions(text, taken, []);
189
+ if (unmatched.length > 0) {
190
+ const names = [
191
+ ...(await sendersOnce()).values(),
192
+ ...views.flatMap((v) => (v.name !== undefined ? [v.name] : [])),
193
+ ...(scope?.channel !== undefined ? [scope.channel.title] : []),
194
+ ...(scope?.team !== undefined ? [scope.team.name] : []),
195
+ ...(target.kind === 'channel' && scope === undefined ? [target.title] : []),
196
+ ];
197
+ unmatched = unmatchedMentions(text, taken, names);
198
+ }
199
+ const summary = views.length === 0
200
+ ? undefined
201
+ : 'Mentions: ' +
202
+ views
203
+ .map((v) => {
204
+ const tag = v.mention_type !== 'person' ? ` (${v.mention_type})` : v.in_conversation === false ? ' (not in this conversation)' : '';
205
+ return `${JSON.stringify(v.name ?? v.name_in_text)}${tag}`;
206
+ })
207
+ .join(', ');
208
+ return {
209
+ mentions: views,
210
+ unmatched: unmatched.length,
211
+ above: {
212
+ ...(unmatched.length > 0
213
+ ? {
214
+ unmatched_mentions: unmatched,
215
+ mention_warning: `${unmatched.join(', ')} ${unmatched.length === 1 ? 'is' : 'are'} written as plain text: no mention names ` +
216
+ `${unmatched.length === 1 ? 'it' : 'them'}, so nobody is notified. To mention, add to mentions ` +
217
+ '(name_in_text, and person: an MRI, a display name, or this channel\'s or team\'s id or name); ' +
218
+ 'otherwise it is sent as written.',
219
+ }
220
+ : {}),
221
+ ...(notes.length > 0 ? { mention_notes: notes } : {}),
222
+ ...(summary !== undefined ? { mentions_summary: summary } : {}),
223
+ },
224
+ };
225
+ }
@@ -26,6 +26,7 @@
26
26
  * token search already captures.
27
27
  */
28
28
  import { McpToolError } from '@chrischall/mcp-utils';
29
+ import { captureFailure } from '../capture-feedback.js';
29
30
  import { isUserMessage, oneOnOnePeerMri, senderMri, summariseAll } from '../model.js';
30
31
  import { enrichTitles } from './titles.js';
31
32
  import { THIRD_PARTY_NAMES_NOTE } from './untrusted.js';
@@ -123,6 +124,14 @@ function candidateList(people) {
123
124
  })
124
125
  .join('; ');
125
126
  }
127
+ /** A refusal for one person, with its code. */
128
+ class PersonError extends McpToolError {
129
+ code;
130
+ constructor(code, message, opts = {}) {
131
+ super(message, opts);
132
+ this.code = code;
133
+ }
134
+ }
126
135
  /** The local match for a name: one person, none (`undefined`), or a refusal when several match. */
127
136
  function matchKnown(person, known) {
128
137
  const q = normaliseName(person);
@@ -134,22 +143,25 @@ function matchKnown(person, known) {
134
143
  if (found.length === 1)
135
144
  return found[0];
136
145
  if (found.length > 1) {
137
- 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.' });
146
+ throw new PersonError('person_ambiguous', `"${person}" matches ${found.length} people: ${candidateList(found)}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'Pass the MRI (8:orgid:…) of the one you mean, or map this entry to it in ids.' });
138
147
  }
139
148
  return undefined;
140
149
  }
141
- const PASS_ID = "Pass the person's email address or MRI (8:orgid:…) instead.";
142
- /** A directory failure as the refusal for `person`, keeping the failure's message, kind and remedy. */
150
+ const PASS_ID = "Pass the person's Entra object id or MRI (8:orgid:…) instead — e.g. from the Outlook MCP's people list — " +
151
+ 'in people, or map this entry to it in ids.';
152
+ /**
153
+ * A directory failure as the refusal for `person`. A capture failure (anything
154
+ * not already an `McpToolError`) names its step, how long it waited and its
155
+ * `token_<step>` code (`capture-feedback.ts`); its hint says to search WHILE the
156
+ * retry waits. An `McpToolError` (a disabled bridge, an HTTP error) keeps its
157
+ * own message, kind and remedy.
158
+ */
143
159
  function directoryFailed(person, err, email) {
144
- const message = err instanceof Error ? err.message : String(err);
145
- const own = err instanceof McpToolError ? err.hint : undefined;
146
- const remedy = own ??
147
- 'Run any search in the Teams search box of a signed-in Teams tab while retrying (that is what lets this ' +
148
- 'server capture the token it searches the directory with).';
160
+ const own = err instanceof McpToolError ? err : captureFailure(err, 'search the directory', 'substrate');
149
161
  const lead = email ? `Could not look up "${person}" because` : `No one in your chats is called "${person}", and`;
150
- return new McpToolError(`${lead} the directory could not be searched: ${message}`, {
151
- hint: `${remedy} Or pass the person's MRI (8:orgid:…) instead.`,
152
- ...(err instanceof McpToolError && err.kind !== undefined ? { kind: err.kind } : {}),
162
+ return new PersonError('directory_unavailable', `${lead} the directory could not be searched: ${own.message}`, {
163
+ hint: `${own.hint ?? ''} ${PASS_ID}`.trim(),
164
+ ...(own.kind !== undefined ? { kind: own.kind } : {}),
153
165
  cause: err,
154
166
  });
155
167
  }
@@ -164,9 +176,9 @@ function pickByEmail(person, found) {
164
176
  if (hits.length === 1)
165
177
  return fromDirectory(person, hits[0]);
166
178
  if (hits.length > 1) {
167
- 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.' });
179
+ throw new PersonError('person_ambiguous', `"${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.' });
168
180
  }
169
- throw new McpToolError(`No one in your organisation's directory has the address "${person}".`, {
181
+ throw new PersonError('person_not_found', `No one in your organisation's directory has the address "${person}".`, {
170
182
  hint: "Check the address, or pass the person's name or MRI (8:orgid:…) instead. Only people in your " +
171
183
  'organisation (not distribution lists or personal contacts) are found there.',
172
184
  });
@@ -182,44 +194,129 @@ function pickByName(person, found) {
182
194
  if (exact.length === 1)
183
195
  return fromDirectory(person, exact[0]);
184
196
  if (exact.length > 1) {
185
- 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.' });
197
+ throw new PersonError('person_ambiguous', `"${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.' });
186
198
  }
187
199
  if (found.length === 1 && ` ${normaliseName(found[0].name)} `.includes(` ${q} `))
188
200
  return fromDirectory(person, found[0]);
189
201
  if (found.length > 0) {
190
- throw new McpToolError(`No one in your chats is called "${person}", and no one in the directory is called exactly that; it ` +
202
+ throw new PersonError('person_ambiguous', `No one in your chats is called "${person}", and no one in the directory is called exactly that; it ` +
191
203
  `suggested: ${candidateList(found)}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'If one of them is who you mean, pass their email address or MRI (8:orgid:…).' });
192
204
  }
193
- throw new McpToolError(`No one in your chats or your organisation's directory is called "${person}".`, {
205
+ throw new PersonError('person_not_found', `No one in your chats or your organisation's directory is called "${person}".`, {
194
206
  hint: `${PASS_ID} A name is matched among the other person of each of your 1:1 chats and (for an existing chat) ` +
195
- "its recent senders, then searched in your organisation's directory.",
207
+ "its recent senders, then the ids you pass, then searched in your organisation's directory.",
208
+ });
209
+ }
210
+ /** The caller's id for `person`, as an MRI; `undefined` when there is none. Refuses one that is not an id. */
211
+ function callerId(person, ids) {
212
+ const want = person.trim().toLowerCase();
213
+ const entry = Object.entries(ids).find(([k]) => k.trim().toLowerCase() === want);
214
+ if (entry === undefined)
215
+ return undefined;
216
+ const mri = personMri(entry[1]);
217
+ if (mri === undefined) {
218
+ throw new PersonError('caller_id_invalid', `The id given for "${person}" in ids (${JSON.stringify(entry[1])}) is not an MRI (8:orgid:…) or an Entra object id.`, { hint: 'Map each entry to an MRI or a bare Entra object id (a GUID).' });
219
+ }
220
+ return mri;
221
+ }
222
+ /** How a resolved person reads in a partial-failure error. */
223
+ function resolvedLine(r) {
224
+ return `${JSON.stringify(r.name ?? r.person)} (${r.mri}, from ${r.source === 'id' ? 'the id given' : r.source === 'caller' ? 'your ids' : r.source === 'chat' ? 'your chats' : 'the directory'})`;
225
+ }
226
+ /** Every failure, and who did resolve, as the one refusal the call throws. */
227
+ function unresolved(failures, resolved, total) {
228
+ const named = resolved.some((r) => r.name !== undefined);
229
+ const ok = resolved.length > 0
230
+ ? ` Resolved: ${resolved.map(resolvedLine).join('; ')}.${named && !failures.some((f) => f.error.message.includes(THIRD_PARTY_NAMES_NOTE)) ? ` ${THIRD_PARTY_NAMES_NOTE}` : ''}`
231
+ : '';
232
+ // The remedy comes from a real failure, never from someone merely not checked.
233
+ const first = (failures.find((f) => f.error.code !== 'person_not_checked') ?? failures[0]).error;
234
+ if (failures.length === 1) {
235
+ return new McpToolError(`${first.message}${ok} (error code: ${first.code})`, {
236
+ ...(first.hint !== undefined ? { hint: first.hint } : {}),
237
+ ...(first.kind !== undefined ? { kind: first.kind } : {}),
238
+ cause: first,
239
+ });
240
+ }
241
+ const each = failures.map((f) => `"${f.person}" [${f.error.code}]: ${f.error.message}`).join(' ');
242
+ return new McpToolError(`Could not resolve ${failures.length} of ${total} people. ${each}${ok} (error code: people_unresolved)`, {
243
+ ...(first.hint !== undefined ? { hint: first.hint } : {}),
244
+ ...(first.kind !== undefined ? { kind: first.kind } : {}),
245
+ cause: first,
196
246
  });
197
247
  }
198
248
  /**
199
249
  * Each requested person's MRI (and name, source and — from the directory —
200
- * email), by the rules in the module comment. Every person resolves or the
201
- * call throws, naming the candidates or the failure. Local matching runs for
202
- * every input first, so a local ambiguity refuses before the directory is
203
- * asked; then the directory is asked once per distinct input that needs it
204
- * (`force`, so a retry after running a Teams search really re-captures).
250
+ * email). In order, for each input:
251
+ * (a) an MRI or a bare Entra object id — taken as given;
252
+ * (b) a name — matched among the people in the user's chats;
253
+ * (c) the caller's `ids` (the resolver hook) for that entry — also for an
254
+ * email; one that names someone other than the chat match is refused;
255
+ * (d) the directory (Substrate), last — the one step that needs a token
256
+ * captured from the browser.
257
+ * Nothing is guessed. Every person resolves or the call throws ONE error that
258
+ * names each failure (with its code) and lists who did resolve. The directory
259
+ * is asked once per distinct input (`force`, so a retry really re-captures),
260
+ * not at all when someone already failed locally, and not again after its
261
+ * token could not be captured — one wait, not one per person.
205
262
  */
206
- export async function resolvePeople(inputs, known, directory) {
207
- const local = inputs.map((person) => {
208
- const direct = personMri(person);
209
- if (direct !== undefined) {
210
- const name = knownName(direct, known);
211
- return { person, mri: direct, ...(name !== undefined ? { name } : {}), source: 'id' };
263
+ export async function resolvePeople(inputs, known, directory, ids = {}) {
264
+ const slots = inputs.map((person) => {
265
+ try {
266
+ const direct = personMri(person);
267
+ if (direct !== undefined) {
268
+ const name = knownName(direct, known);
269
+ return { person, mri: direct, ...(name !== undefined ? { name } : {}), source: 'id' };
270
+ }
271
+ const given = callerId(person, ids);
272
+ const asCaller = (mri) => {
273
+ const name = knownName(mri, known);
274
+ return { person, mri, ...(name !== undefined ? { name } : {}), source: 'caller' };
275
+ };
276
+ if (isEmail(person))
277
+ return given !== undefined ? asCaller(given) : { person, email: true };
278
+ let k;
279
+ try {
280
+ k = matchKnown(person, known);
281
+ }
282
+ catch (err) {
283
+ // Several in the chats: the caller's id is what tells them apart.
284
+ if (given !== undefined)
285
+ return asCaller(given);
286
+ throw err;
287
+ }
288
+ if (k !== undefined) {
289
+ if (given !== undefined && given.toLowerCase() !== k.mri.toLowerCase()) {
290
+ throw new PersonError('person_conflict', `"${person}" is ${JSON.stringify(k.name)} (${k.mri}) in your chats, but ids maps it to ${given}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'Pass the MRI of the one you mean in people, or fix the entry in ids.' });
291
+ }
292
+ return { person, mri: k.mri, name: k.name, source: 'chat' };
293
+ }
294
+ return given !== undefined ? asCaller(given) : { person, email: false };
295
+ }
296
+ catch (err) {
297
+ if (err instanceof PersonError)
298
+ return { person, error: err };
299
+ throw err;
212
300
  }
213
- if (isEmail(person))
214
- return { person, email: true };
215
- const k = matchKnown(person, known);
216
- return k !== undefined ? { person, mri: k.mri, name: k.name, source: 'chat' } : { person, email: false };
217
301
  });
302
+ const isFailed = (r) => 'error' in r;
303
+ const isResolved = (r) => 'mri' in r;
304
+ let directoryDown;
218
305
  const asked = new Map();
219
- const out = [];
220
- for (const r of local) {
221
- if ('mri' in r) {
222
- out.push(r);
306
+ const anyLocalFailure = slots.some(isFailed);
307
+ for (let i = 0; i < slots.length; i++) {
308
+ const r = slots[i];
309
+ if (isFailed(r) || isResolved(r))
310
+ continue;
311
+ if (anyLocalFailure) {
312
+ slots[i] = {
313
+ person: r.person,
314
+ error: new PersonError('person_not_checked', `"${r.person}" was not looked up in the directory, because someone else already failed.`),
315
+ };
316
+ continue;
317
+ }
318
+ if (directoryDown !== undefined) {
319
+ slots[i] = { person: r.person, error: directoryFailed(r.person, directoryDown.cause, r.email) };
223
320
  continue;
224
321
  }
225
322
  const text = r.person.trim();
@@ -230,11 +327,24 @@ export async function resolvePeople(inputs, known, directory) {
230
327
  found = await directory.suggestPeople(text, { force: true });
231
328
  }
232
329
  catch (err) {
233
- throw directoryFailed(r.person, err, r.email);
330
+ directoryDown = directoryFailed(r.person, err, r.email);
331
+ slots[i] = { person: r.person, error: directoryDown };
332
+ continue;
234
333
  }
235
334
  asked.set(key, found);
236
335
  }
237
- out.push(r.email ? pickByEmail(r.person, found) : pickByName(r.person, found));
336
+ try {
337
+ slots[i] = r.email ? pickByEmail(r.person, found) : pickByName(r.person, found);
338
+ }
339
+ catch (err) {
340
+ if (!(err instanceof PersonError))
341
+ throw err;
342
+ slots[i] = { person: r.person, error: err };
343
+ }
238
344
  }
239
- return out;
345
+ const failures = slots.filter(isFailed);
346
+ const resolved = slots.filter(isResolved);
347
+ if (failures.length > 0)
348
+ throw unresolved(failures, resolved, inputs.length);
349
+ return resolved;
240
350
  }
@@ -0,0 +1,67 @@
1
+ import { toolAnnotations } from '@chrischall/mcp-utils';
2
+ import { z } from 'zod';
3
+ import { lookupProfiles, MAX_PROFILES } from '../profile.js';
4
+ import { knownName, knownPeople } from './people.js';
5
+ import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
6
+ import { workMeta } from './hints.js';
7
+ export function registerProfileTools(server, { chatsvc, substrate }) {
8
+ server.registerTool('teams_get_profile', {
9
+ title: "Look up a colleague's Teams profile card",
10
+ description: "Look up a colleague's profile card, as Teams shows it: displayName, mri (8:orgid:…), email, " +
11
+ 'chatAddress, jobTitle, department, officeLocation, city, company and manager — each absent when the ' +
12
+ "directory does not say. person is an email address, a chat address (UPN), an MRI or a name (\"Last, " +
13
+ `First\" or \"First Last\"), or an array of up to ${MAX_PROFILES}. The result is { profiles: [...] }, one ` +
14
+ 'per person in order, each with status "found" (and profile), "ambiguous" (candidates, up to 10, each a ' +
15
+ 'card — a name several people share is never guessed: pass one candidate\'s email or MRI), "not_found" ' +
16
+ 'or "error" (with hint). include_presence: true also returns presence: [{ mri, availability, activity, ' +
17
+ 'lastSeen, timeZone, localTime }] for the people found — separately from the cards, fetched only when ' +
18
+ 'asked, never stored; if presence cannot be read, presence_error says why and the cards still come back. ' +
19
+ 'Read-only. Uses the same directory token as the group-chat member lookup: if none has been captured yet, ' +
20
+ 'run any search in the Teams search box of a signed-in Teams tab and retry. Pass an mri to ' +
21
+ 'teams_create_group_chat or teams_send_message mentions.' +
22
+ UNTRUSTED_DESCRIPTION_SUFFIX,
23
+ annotations: toolAnnotations({ readOnly: true, openWorld: true }),
24
+ _meta: workMeta('lookup', {
25
+ aliases: ['profile', 'profile card', 'who is', 'job title', 'colleague', 'org chart', 'where is'],
26
+ }),
27
+ inputSchema: {
28
+ person: z
29
+ .union([z.string().min(1), z.array(z.string().min(1)).min(1).max(MAX_PROFILES)])
30
+ .describe(`An email address, chat address (UPN), MRI (8:orgid:…) or name, or an array of up to ${MAX_PROFILES} of them.`),
31
+ include_presence: z
32
+ .boolean()
33
+ .optional()
34
+ .describe('Also return each found person\'s availability, last seen and local time, separately (default false; ' +
35
+ 'not fetched otherwise, never stored).'),
36
+ },
37
+ }, async ({ person, include_presence }) => {
38
+ const queries = Array.isArray(person) ? person : [person];
39
+ // An MRI the directory cannot be searched by is looked up by the name the user's chats know it by.
40
+ let known;
41
+ const nameForMri = async (mri) => {
42
+ known ??= chatsvc
43
+ .meMri()
44
+ .then((me) => knownPeople(chatsvc, me))
45
+ .catch(() => []);
46
+ return knownName(mri, await known);
47
+ };
48
+ const profiles = await lookupProfiles(queries, substrate, { nameForMri });
49
+ const fetched_at = new Date().toISOString();
50
+ if (!include_presence)
51
+ return untrustedResult({ profiles, fetched_at });
52
+ const mris = [...new Set(profiles.flatMap((r) => (r.status === 'found' ? [r.profile.mri] : [])))];
53
+ try {
54
+ const presence = await chatsvc.getPresence(mris);
55
+ return untrustedResult({ profiles, presence, fetched_at });
56
+ }
57
+ catch (err) {
58
+ const error = err instanceof Error ? err.message : String(err);
59
+ const hint = err.hint;
60
+ return untrustedResult({
61
+ profiles,
62
+ presence_error: { error, ...(typeof hint === 'string' ? { hint } : {}) },
63
+ fetched_at,
64
+ });
65
+ }
66
+ });
67
+ }