@chrischall/microsoft-teams-mcp 0.8.6 → 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.
package/dist/substrate.js CHANGED
@@ -47,6 +47,24 @@
47
47
  * stays client-side.
48
48
  * - A bad token is a 401.
49
49
  *
50
+ * People lookup (`suggestPeople`, the directory fallback of
51
+ * `teams_add_chat_members` / `teams_remove_chat_members`), verified live
52
+ * 2026-11-09 with the SAME captured token — no new token or bridge scope:
53
+ *
54
+ * POST https://substrate.office.com/search/api/v1/suggestions?scenario=powerbar
55
+ * { EntityRequests: [{ EntityType: "People", Query: { QueryString },
56
+ * Size }], Cvid, LogicalId, Scenario: { Name: "powerbar" } }
57
+ * → { Groups: [{ Type: "People", Suggestions: [{ DisplayName,
58
+ * EmailAddresses: string[], UserPrincipalName, JobTitle, Department,
59
+ * PeopleSubtype, MRI, ExternalDirectoryObjectId, … }] }] }
60
+ *
61
+ * - A surname, or "First Last", found the person; their
62
+ * `ExternalDirectoryObjectId` is their Entra oid, and their chat MRI is
63
+ * `8:orgid:<that oid>`.
64
+ * - `PeopleSubtype` seen: `OrganizationUser`, `PersonalContact`, `Unknown`,
65
+ * `PublicDistributionList` — only the first can be a chat member.
66
+ * - The v2 query endpoint with `EntityType: "People"` is a 400: not used.
67
+ *
50
68
  * As with the other clients, the bridge is touched only to capture the token
51
69
  * (`substrate-auth.ts`); every request is a plain Node `fetch`.
52
70
  */
@@ -55,6 +73,11 @@ import { describeTransportFailure } from './network-error.js';
55
73
  import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
56
74
  import { createSubstrateTokenCache } from './substrate-token-cache.js';
57
75
  export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
76
+ export const SUBSTRATE_SUGGESTIONS_URL = 'https://substrate.office.com/search/api/v1/suggestions?scenario=powerbar';
77
+ /** Directory suggestions asked for when the caller names no size. */
78
+ const DEFAULT_SUGGESTIONS = 10;
79
+ /** Most suggestions one lookup asks for. */
80
+ const MAX_SUGGESTIONS = 25;
58
81
  /**
59
82
  * How long after a failed capture (or a 401 on a freshly captured token) an
60
83
  * unforced search skips straight to failing
@@ -194,6 +217,73 @@ export function parseQueryResponse(body) {
194
217
  unmapped,
195
218
  };
196
219
  }
220
+ /** The suggestions body, as verified live 2026-11-09 (capitalised keys, as Teams sends them). */
221
+ export function buildSuggestionsBody(text, size) {
222
+ return {
223
+ EntityRequests: [{ EntityType: 'People', Query: { QueryString: text }, Size: size }],
224
+ Cvid: crypto.randomUUID(),
225
+ LogicalId: crypto.randomUUID(),
226
+ Scenario: { Name: 'powerbar' },
227
+ };
228
+ }
229
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
230
+ const ORGID_MRI = /^8:orgid:\S+$/i;
231
+ /**
232
+ * A suggestion as a directory person, or `undefined` when it cannot be a chat
233
+ * member: only an `OrganizationUser` (or an entry with no subtype) with a
234
+ * usable id — its `MRI` when that is `8:orgid:…`, else `8:orgid:<its
235
+ * ExternalDirectoryObjectId, lower-cased>`.
236
+ */
237
+ function mapSuggestion(raw) {
238
+ const r = obj(raw);
239
+ if (r === undefined)
240
+ return undefined;
241
+ const subtype = str(r.PeopleSubtype);
242
+ if (subtype !== undefined && subtype !== 'OrganizationUser')
243
+ return undefined;
244
+ const mriField = str(r.MRI)?.trim();
245
+ const oid = str(r.ExternalDirectoryObjectId)?.trim();
246
+ const mri = mriField !== undefined && ORGID_MRI.test(mriField)
247
+ ? mriField
248
+ : oid !== undefined && GUID.test(oid)
249
+ ? `8:orgid:${oid.toLowerCase()}`
250
+ : undefined;
251
+ if (mri === undefined)
252
+ return undefined;
253
+ const email = Array.isArray(r.EmailAddresses) ? r.EmailAddresses.map(str).find((e) => e !== undefined) : undefined;
254
+ const upn = str(r.UserPrincipalName);
255
+ const name = str(r.DisplayName)?.trim() ?? email ?? upn ?? mri;
256
+ const jobTitle = str(r.JobTitle);
257
+ const department = str(r.Department);
258
+ return {
259
+ mri,
260
+ name,
261
+ ...(email !== undefined ? { email } : {}),
262
+ ...(upn !== undefined ? { upn } : {}),
263
+ ...(jobTitle !== undefined ? { jobTitle } : {}),
264
+ ...(department !== undefined ? { department } : {}),
265
+ };
266
+ }
267
+ /** Parse a suggestions response into the people who can be chat members, one per MRI. Never throws on shape. */
268
+ export function parseSuggestionsResponse(body) {
269
+ const groups = obj(body)?.Groups;
270
+ if (!Array.isArray(groups))
271
+ return [];
272
+ const byMri = new Map();
273
+ for (const g of groups) {
274
+ const group = obj(g);
275
+ if (group?.Type !== 'People' || !Array.isArray(group.Suggestions))
276
+ continue;
277
+ for (const raw of group.Suggestions) {
278
+ const p = mapSuggestion(raw);
279
+ if (p !== undefined && !byMri.has(p.mri.toLowerCase()))
280
+ byMri.set(p.mri.toLowerCase(), p);
281
+ }
282
+ }
283
+ return [...byMri.values()];
284
+ }
285
+ const SEARCH = { url: SUBSTRATE_QUERY_URL, service: 'Substrate search', plural: 'searches' };
286
+ const PEOPLE = { url: SUBSTRATE_SUGGESTIONS_URL, service: 'Substrate people lookup', plural: 'people lookups' };
197
287
  export class SubstrateClient {
198
288
  #fetchImpl;
199
289
  #configError = null;
@@ -236,23 +326,44 @@ export class SubstrateClient {
236
326
  return this.#configError === null;
237
327
  }
238
328
  async searchMessages(req, opts = {}) {
329
+ return parseQueryResponse(await this.#post(SEARCH, buildQueryBody(req), opts.force === true));
330
+ }
331
+ /**
332
+ * People in the directory matching `text` (a name, part of one, or an
333
+ * address), as Teams' search box suggests them — only those who can be a
334
+ * chat member (see {@link parseSuggestionsResponse}). Blank text asks nothing.
335
+ */
336
+ async suggestPeople(text, opts = {}) {
337
+ const q = text.trim();
338
+ if (q === '')
339
+ return [];
340
+ const size = Math.min(Math.max(1, Math.floor(opts.size ?? DEFAULT_SUGGESTIONS)), MAX_SUGGESTIONS);
341
+ return parseSuggestionsResponse(await this.#post(PEOPLE, buildSuggestionsBody(q, size), opts.force === true));
342
+ }
343
+ /**
344
+ * POST `body` to Substrate with the captured token and return the parsed
345
+ * JSON: the config error, the capture cooldown (unless `force`), one
346
+ * re-capture on a 401, a bounded read, no redirects, and the status mapped
347
+ * to an `McpToolError` — the body is never echoed.
348
+ */
349
+ async #post(lookup, body, force) {
239
350
  if (this.#configError)
240
351
  throw this.#configError;
241
352
  const failed = this.#captureFailure;
242
- if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
353
+ if (!force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
243
354
  throw failed.error;
244
355
  let text = '';
245
356
  const res = await this.#manager.withAuth(async (token) => {
246
357
  let r;
247
358
  try {
248
- r = await fetchBounded(SUBSTRATE_QUERY_URL, {
359
+ r = await fetchBounded(lookup.url, {
249
360
  method: 'POST',
250
361
  headers: {
251
362
  authorization: `Bearer ${token}`,
252
363
  'content-type': 'application/json',
253
364
  accept: 'application/json',
254
365
  },
255
- body: JSON.stringify(buildQueryBody(req)),
366
+ body: JSON.stringify(body),
256
367
  redirect: 'error',
257
368
  }, {
258
369
  read: 'text',
@@ -263,33 +374,33 @@ export class SubstrateClient {
263
374
  });
264
375
  }
265
376
  catch (e) {
266
- throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, 'Substrate search') ?? e;
377
+ throw describeTransportFailure(e, lookup.url, lookup.service) ?? e;
267
378
  }
268
379
  text = r.body;
269
380
  return r.res;
270
381
  });
271
382
  try {
272
- checkStatus(res.status);
383
+ checkStatus(res.status, lookup);
273
384
  }
274
385
  catch (error) {
275
386
  // A 401 here is on a token `withAuth` just re-captured: the capture itself
276
387
  // is not yielding a usable token. Cool down like a failed capture, so each
277
- // unforced search does not hold the call for another capture window.
388
+ // unforced call does not hold the caller for another capture window.
278
389
  if (res.status === 401)
279
390
  this.#captureFailure = { at: Date.now(), error };
280
391
  throw error;
281
392
  }
282
393
  try {
283
- return parseQueryResponse(JSON.parse(text));
394
+ return JSON.parse(text);
284
395
  }
285
396
  catch {
286
- // Never echo the body: it holds message content.
397
+ // Never echo the body: it holds message content or people's details.
287
398
  throw new McpToolError('Substrate returned a response that is not JSON.', { status: res.status, kind: 'http' });
288
399
  }
289
400
  }
290
401
  }
291
402
  /** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
292
- function checkStatus(status) {
403
+ function checkStatus(status, lookup) {
293
404
  if (status >= 200 && status < 300)
294
405
  return;
295
406
  if (status === 401) {
@@ -300,9 +411,13 @@ function checkStatus(status) {
300
411
  });
301
412
  }
302
413
  if (status === 429) {
303
- throw new McpToolError('Substrate is rate-limiting searches (429).', { status, kind: 'http', hint: 'Wait a minute before retrying.' });
414
+ throw new McpToolError(`Substrate is rate-limiting ${lookup.plural} (429).`, {
415
+ status,
416
+ kind: 'http',
417
+ hint: 'Wait a minute before retrying.',
418
+ });
304
419
  }
305
- throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
420
+ throw new McpToolError(`${lookup.service} returned HTTP ${status}.`, {
306
421
  status,
307
422
  kind: 'http',
308
423
  ...(status >= 500 ? { hint: 'A Substrate-side failure; retry shortly.' } : {}),
@@ -23,22 +23,23 @@ const MAX_RAW_MESSAGES = 4000;
23
23
  */
24
24
  export const MAX_FILE_BYTES = 25 * 1024 * 1024;
25
25
  const FILE_HINT = 'A shared file is downloaded from SharePoint and returned as its contents (an image as an image, ' +
26
- 'anything else as an embedded resource; over 10 MiB as a download link, or a saved file on a local ' +
27
- 'install). The first file from a given SharePoint host may need ' +
28
- 'opening once in Teams to mint a short-lived token; a file your account cannot open comes back as ' +
29
- 'metadata and its link.';
26
+ 'anything else as an embedded resource; over 10 MiB, or with save, as a download link or a saved file ' +
27
+ 'on a local install). The first download may need your Teams tab reloaded to capture a SharePoint ' +
28
+ 'token; a file your account cannot open comes back as metadata and its link.';
30
29
  export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
31
30
  server.registerTool('teams_get_attachment', {
32
31
  title: 'Get a Teams message attachment',
33
32
  description: 'Fetch one attachment of a Teams chat or channel message, as listed by ' +
34
- 'teams_list_messages / teams_list_unread_messages. An inline image (attachments.images[].ref) ' +
35
- 'is returned as the image itself. A shared file (attachments.files[].name) is downloaded ' +
36
- 'from SharePoint and returned as its contents: an image as the image, anything else as an ' +
37
- 'embedded resource carrying the bytes. Anything over 10 MiB comes back instead as a signed, ' +
33
+ 'teams_list_messages / teams_list_unread_messages. ref names it: an inline image\'s ref ' +
34
+ '(attachments.images[].ref) or a shared file\'s name (attachments.files[].name), matched ignoring case ' +
35
+ 'and, for a file, with or without its extension. An inline image is returned as the image itself. A ' +
36
+ 'shared file is downloaded from SharePoint and returned as its contents: an image as the image, anything ' +
37
+ 'else as an embedded resource carrying the bytes. Anything over 10 MiB comes back instead as a signed, ' +
38
38
  'expiring download link (downloadUrl) on a hosted install, or saved to a fresh file (path) under ' +
39
39
  `${EXPORT_OUTPUT_ENV}, else ~/Downloads/${EXPORT_SERVER_NAME}, on a local one; the caption's via ` +
40
- 'says which. The first file from a given SharePoint host in a ' +
41
- 'session may need opening once in Teams to mint a short-lived token; a file your account ' +
40
+ 'says which. save: true does the same for any size — use it when the user wants the file itself rather ' +
41
+ 'than its contents read here. The first download may need your Teams tab reloaded to capture a ' +
42
+ 'short-lived SharePoint token, which then serves every SharePoint host; a file your account ' +
42
43
  'cannot open, or one that could not be fetched, comes back as metadata and its open link ' +
43
44
  'instead of failing. Its caption names the conversation beside its id: title (as teams_list_conversations ' +
44
45
  'names it — an untitled group chat by its participants, a 1:1 by the other person) and participants. ' +
@@ -55,9 +56,15 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
55
56
  ref: z
56
57
  .string()
57
58
  .min(1)
58
- .describe("An inline image's ref (attachments.images[].ref) or a shared file's name (attachments.files[].name)."),
59
+ .describe("An inline image's ref (attachments.images[].ref) or a shared file's name (attachments.files[].name). " +
60
+ 'Case is ignored, and a file may be named without its extension.'),
61
+ save: z
62
+ .boolean()
63
+ .optional()
64
+ .describe(`Save the attachment to a fresh file under ${EXPORT_OUTPUT_ENV} (else ~/Downloads/${EXPORT_SERVER_NAME}) ` +
65
+ 'and return its path instead of its contents; a hosted install returns a download link instead. Default false.'),
59
66
  },
60
- }, async ({ conversation, message_id, ref }) => {
67
+ }, async ({ conversation, message_id, ref, save = false }) => {
61
68
  try {
62
69
  // A message id IS its arrival ms, and pages run newest first: the first
63
70
  // message older than it means it was not there.
@@ -74,15 +81,16 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
74
81
  const message = normaliseMessage(raw, '');
75
82
  // Named while the attachment is fetched; naming never throws, so it never fails the call.
76
83
  const naming = nameConversations(chatsvc, [conversation]).then((names) => nameFields(names.get(conversation)));
77
- const image = message.attachments.images.find((i) => i.ref === ref);
78
- if (image !== undefined) {
84
+ const found = findAttachment(message, ref, message_id);
85
+ if (found.kind === 'image') {
86
+ const image = found.image;
79
87
  const { mimeType, data } = await chatsvc.fetchImage(image.url);
80
88
  if (!mimeType.startsWith('image/')) {
81
- throw new McpToolError(`The attachment ${ref} is not an image (the image store returned ${mimeType}).`);
89
+ throw new McpToolError(`The attachment ${image.ref} is not an image (the image store returned ${mimeType}).`);
82
90
  }
83
- const delivered = await deliver(data, imageFileName(ref, mimeType), mimeType);
91
+ const delivered = await deliver(data, imageFileName(image.ref, mimeType), mimeType, save);
84
92
  const caption = untrustedResult({
85
- ref,
93
+ ref: image.ref,
86
94
  message_id,
87
95
  conversation,
88
96
  ...(await naming),
@@ -94,15 +102,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
94
102
  });
95
103
  return { content: [...delivered.content, ...caption.content] };
96
104
  }
97
- const file = message.attachments.files.find((f) => f.name === ref);
98
- if (file !== undefined) {
99
- return downloadSharedFile(sharepoint, file, message, { conversation, message_id }, naming);
100
- }
101
- const { images, files } = message.attachments;
102
- throw new McpToolError(`Message ${message_id} has no attachment "${ref}".`, {
103
- hint: `It has ${images.length} inline image(s) and ${files.length} shared file(s); pass an ` +
104
- 'image ref or a file name exactly as teams_list_messages listed it.',
105
- });
105
+ return downloadSharedFile(sharepoint, found.file, message, { conversation, message_id }, naming, save);
106
106
  }
107
107
  catch (err) {
108
108
  throw wrapApiError(err, 'get the attachment');
@@ -116,7 +116,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
116
116
  * `downloadFile` error and returns today's metadata result with a hint saying
117
117
  * why. A file with no `url` at all (nothing to download) takes the same path.
118
118
  */
119
- async function downloadSharedFile(sharepoint, file, message, ids, naming) {
119
+ async function downloadSharedFile(sharepoint, file, message, ids, naming, save) {
120
120
  if (file.url === undefined) {
121
121
  return untrustedResult({ ...file, content_available: false, hint: FILE_HINT });
122
122
  }
@@ -134,7 +134,7 @@ async function downloadSharedFile(sharepoint, file, message, ids, naming) {
134
134
  // keep the open link in the hint so the file is still reachable.
135
135
  let delivered;
136
136
  try {
137
- delivered = await deliver(downloaded.data, file.name, downloaded.mimeType);
137
+ delivered = await deliver(downloaded.data, file.name, downloaded.mimeType, save);
138
138
  }
139
139
  catch (err) {
140
140
  if (err instanceof McpToolError && file.openUrl !== undefined) {
@@ -170,18 +170,63 @@ async function downloadSharedFile(sharepoint, file, message, ids, naming) {
170
170
  const content = delivered.content.map((block) => block.type === 'resource' ? { ...block, resource: { ...block.resource, uri } } : block);
171
171
  return { content: [...content, ...caption.content] };
172
172
  }
173
+ /** A file name without its last extension: `report.csv` → `report`; `.env` stays `.env`. */
174
+ function withoutExtension(name) {
175
+ const dot = name.lastIndexOf('.');
176
+ return dot > 0 ? name.slice(0, dot) : name;
177
+ }
178
+ /**
179
+ * The attachment `ref` names. An exact match wins; failing that, one matched
180
+ * ignoring case; failing that, a file matched ignoring case and its extension
181
+ * (`Report` → `report.csv`). A looser match that names more than one
182
+ * attachment is refused with the candidates, never guessed between.
183
+ */
184
+ function findAttachment(message, ref, messageId) {
185
+ const { images, files } = message.attachments;
186
+ const all = [
187
+ ...images.map((image) => ({ kind: 'image', image })),
188
+ ...files.map((file) => ({ kind: 'file', file })),
189
+ ];
190
+ const nameOf = (a) => (a.kind === 'image' ? a.image.ref : a.file.name);
191
+ const lower = ref.toLowerCase();
192
+ const rules = [
193
+ (a) => nameOf(a) === ref,
194
+ (a) => nameOf(a).toLowerCase() === lower,
195
+ (a) => a.kind === 'file' && withoutExtension(a.file.name).toLowerCase() === lower,
196
+ ];
197
+ for (const rule of rules) {
198
+ const hits = all.filter(rule);
199
+ if (hits.length === 1)
200
+ return hits[0];
201
+ if (hits.length > 1) {
202
+ throw new McpToolError(`"${ref}" matches ${hits.length} attachments of message ${messageId}.`, {
203
+ hint: `Pass one of them exactly: ${hits.map((h) => JSON.stringify(nameOf(h))).join(', ')}.`,
204
+ });
205
+ }
206
+ }
207
+ const names = files.map((f) => JSON.stringify(f.name));
208
+ throw new McpToolError(`Message ${messageId} has no attachment "${ref}".`, {
209
+ hint: `It has ${images.length} inline image(s) and ${files.length} shared file(s)` +
210
+ (names.length > 0 ? ` (${names.join(', ')})` : '') +
211
+ '; pass an image ref or a file name as teams_list_messages listed it.',
212
+ });
213
+ }
173
214
  /**
174
215
  * Hand bytes back by the first route that reaches the caller (`deliverFile`):
175
216
  * inline up to 10 MiB, else a signed link from the blob store (hosted), else a
176
217
  * fresh, never-overwriting file in the download folder — offered only on a
177
218
  * local install, since a hosted runner's disk is unreachable from the session.
219
+ * `save` puts the download folder first (a link when hosted).
178
220
  */
179
- function deliver(bytes, fileName, mimeType) {
221
+ function deliver(bytes, fileName, mimeType, save) {
180
222
  return deliverFile({
181
223
  bytes,
182
224
  fileName,
183
225
  mimeType,
184
226
  keyPrefix: 'attachments',
227
+ // `save` asks for a file rather than the contents; on a hosted install
228
+ // deliverFile turns the disk route into a link, saying why in `note`.
229
+ ...(save ? { prefer: 'disk' } : {}),
185
230
  ...(isHostedEnv() ? {} : { disk: { dir: downloadDir() } }),
186
231
  });
187
232
  }
@@ -228,8 +273,9 @@ export function hostOf(url) {
228
273
  */
229
274
  export function degradeHint(err, host) {
230
275
  if (errorStatusOf(err) === 403) {
231
- return (`Your account cannot open this file, or it is on a SharePoint host (${host}) your captured ` +
232
- 'token does not cover. Open it once in a signed-in Teams tab, then retry.');
276
+ // One token serves every SharePoint host of the tenant, so a 403 is the
277
+ // file's own permissions, not the token (verified live 2026-11-09).
278
+ return `Your account cannot open this file on ${host}. Ask whoever shared it to give you access, then retry.`;
233
279
  }
234
280
  if (errorKindOf(err) === 'no_credential') {
235
281
  return 'SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.';
@@ -246,6 +292,6 @@ export function degradeHint(err, host) {
246
292
  // "open the file" cannot fix a refusal.
247
293
  if (err instanceof Error && err.message !== '')
248
294
  return err.message;
249
- return (`Couldn't mint a SharePoint token for ${host} — open the shared file once in a signed-in Teams ` +
250
- 'tab (that browser request is where the token is captured from), then retry.');
295
+ return (`Couldn't mint a SharePoint token for ${host} — reload your signed-in Teams tab and retry while ` +
296
+ 'it loads (that page load is where the token is captured from).');
251
297
  }