@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.
package/dist/substrate.js CHANGED
@@ -47,6 +47,25 @@
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` /
52
+ * `teams_create_group_chat`), verified live
53
+ * 2026-11-09 with the SAME captured token — no new token or bridge scope:
54
+ *
55
+ * POST https://substrate.office.com/search/api/v1/suggestions?scenario=powerbar
56
+ * { EntityRequests: [{ EntityType: "People", Query: { QueryString },
57
+ * Size }], Cvid, LogicalId, Scenario: { Name: "powerbar" } }
58
+ * → { Groups: [{ Type: "People", Suggestions: [{ DisplayName,
59
+ * EmailAddresses: string[], UserPrincipalName, JobTitle, Department,
60
+ * PeopleSubtype, MRI, ExternalDirectoryObjectId, … }] }] }
61
+ *
62
+ * - A surname, or "First Last", found the person; their
63
+ * `ExternalDirectoryObjectId` is their Entra oid, and their chat MRI is
64
+ * `8:orgid:<that oid>`.
65
+ * - `PeopleSubtype` seen: `OrganizationUser`, `PersonalContact`, `Unknown`,
66
+ * `PublicDistributionList` — only the first can be a chat member.
67
+ * - The v2 query endpoint with `EntityType: "People"` is a 400: not used.
68
+ *
50
69
  * As with the other clients, the bridge is touched only to capture the token
51
70
  * (`substrate-auth.ts`); every request is a plain Node `fetch`.
52
71
  */
@@ -55,6 +74,11 @@ import { describeTransportFailure } from './network-error.js';
55
74
  import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
56
75
  import { createSubstrateTokenCache } from './substrate-token-cache.js';
57
76
  export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
77
+ export const SUBSTRATE_SUGGESTIONS_URL = 'https://substrate.office.com/search/api/v1/suggestions?scenario=powerbar';
78
+ /** Directory suggestions asked for when the caller names no size. */
79
+ const DEFAULT_SUGGESTIONS = 10;
80
+ /** Most suggestions one lookup asks for. */
81
+ const MAX_SUGGESTIONS = 25;
58
82
  /**
59
83
  * How long after a failed capture (or a 401 on a freshly captured token) an
60
84
  * unforced search skips straight to failing
@@ -194,6 +218,73 @@ export function parseQueryResponse(body) {
194
218
  unmapped,
195
219
  };
196
220
  }
221
+ /** The suggestions body, as verified live 2026-11-09 (capitalised keys, as Teams sends them). */
222
+ export function buildSuggestionsBody(text, size) {
223
+ return {
224
+ EntityRequests: [{ EntityType: 'People', Query: { QueryString: text }, Size: size }],
225
+ Cvid: crypto.randomUUID(),
226
+ LogicalId: crypto.randomUUID(),
227
+ Scenario: { Name: 'powerbar' },
228
+ };
229
+ }
230
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
231
+ const ORGID_MRI = /^8:orgid:\S+$/i;
232
+ /**
233
+ * A suggestion as a directory person, or `undefined` when it cannot be a chat
234
+ * member: only an `OrganizationUser` (or an entry with no subtype) with a
235
+ * usable id — its `MRI` when that is `8:orgid:…`, else `8:orgid:<its
236
+ * ExternalDirectoryObjectId, lower-cased>`.
237
+ */
238
+ function mapSuggestion(raw) {
239
+ const r = obj(raw);
240
+ if (r === undefined)
241
+ return undefined;
242
+ const subtype = str(r.PeopleSubtype);
243
+ if (subtype !== undefined && subtype !== 'OrganizationUser')
244
+ return undefined;
245
+ const mriField = str(r.MRI)?.trim();
246
+ const oid = str(r.ExternalDirectoryObjectId)?.trim();
247
+ const mri = mriField !== undefined && ORGID_MRI.test(mriField)
248
+ ? mriField
249
+ : oid !== undefined && GUID.test(oid)
250
+ ? `8:orgid:${oid.toLowerCase()}`
251
+ : undefined;
252
+ if (mri === undefined)
253
+ return undefined;
254
+ const email = Array.isArray(r.EmailAddresses) ? r.EmailAddresses.map(str).find((e) => e !== undefined) : undefined;
255
+ const upn = str(r.UserPrincipalName);
256
+ const name = str(r.DisplayName)?.trim() ?? email ?? upn ?? mri;
257
+ const jobTitle = str(r.JobTitle);
258
+ const department = str(r.Department);
259
+ return {
260
+ mri,
261
+ name,
262
+ ...(email !== undefined ? { email } : {}),
263
+ ...(upn !== undefined ? { upn } : {}),
264
+ ...(jobTitle !== undefined ? { jobTitle } : {}),
265
+ ...(department !== undefined ? { department } : {}),
266
+ };
267
+ }
268
+ /** Parse a suggestions response into the people who can be chat members, one per MRI. Never throws on shape. */
269
+ export function parseSuggestionsResponse(body) {
270
+ const groups = obj(body)?.Groups;
271
+ if (!Array.isArray(groups))
272
+ return [];
273
+ const byMri = new Map();
274
+ for (const g of groups) {
275
+ const group = obj(g);
276
+ if (group?.Type !== 'People' || !Array.isArray(group.Suggestions))
277
+ continue;
278
+ for (const raw of group.Suggestions) {
279
+ const p = mapSuggestion(raw);
280
+ if (p !== undefined && !byMri.has(p.mri.toLowerCase()))
281
+ byMri.set(p.mri.toLowerCase(), p);
282
+ }
283
+ }
284
+ return [...byMri.values()];
285
+ }
286
+ const SEARCH = { url: SUBSTRATE_QUERY_URL, service: 'Substrate search', plural: 'searches' };
287
+ const PEOPLE = { url: SUBSTRATE_SUGGESTIONS_URL, service: 'Substrate people lookup', plural: 'people lookups' };
197
288
  export class SubstrateClient {
198
289
  #fetchImpl;
199
290
  #configError = null;
@@ -236,23 +327,44 @@ export class SubstrateClient {
236
327
  return this.#configError === null;
237
328
  }
238
329
  async searchMessages(req, opts = {}) {
330
+ return parseQueryResponse(await this.#post(SEARCH, buildQueryBody(req), opts.force === true));
331
+ }
332
+ /**
333
+ * People in the directory matching `text` (a name, part of one, or an
334
+ * address), as Teams' search box suggests them — only those who can be a
335
+ * chat member (see {@link parseSuggestionsResponse}). Blank text asks nothing.
336
+ */
337
+ async suggestPeople(text, opts = {}) {
338
+ const q = text.trim();
339
+ if (q === '')
340
+ return [];
341
+ const size = Math.min(Math.max(1, Math.floor(opts.size ?? DEFAULT_SUGGESTIONS)), MAX_SUGGESTIONS);
342
+ return parseSuggestionsResponse(await this.#post(PEOPLE, buildSuggestionsBody(q, size), opts.force === true));
343
+ }
344
+ /**
345
+ * POST `body` to Substrate with the captured token and return the parsed
346
+ * JSON: the config error, the capture cooldown (unless `force`), one
347
+ * re-capture on a 401, a bounded read, no redirects, and the status mapped
348
+ * to an `McpToolError` — the body is never echoed.
349
+ */
350
+ async #post(lookup, body, force) {
239
351
  if (this.#configError)
240
352
  throw this.#configError;
241
353
  const failed = this.#captureFailure;
242
- if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
354
+ if (!force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
243
355
  throw failed.error;
244
356
  let text = '';
245
357
  const res = await this.#manager.withAuth(async (token) => {
246
358
  let r;
247
359
  try {
248
- r = await fetchBounded(SUBSTRATE_QUERY_URL, {
360
+ r = await fetchBounded(lookup.url, {
249
361
  method: 'POST',
250
362
  headers: {
251
363
  authorization: `Bearer ${token}`,
252
364
  'content-type': 'application/json',
253
365
  accept: 'application/json',
254
366
  },
255
- body: JSON.stringify(buildQueryBody(req)),
367
+ body: JSON.stringify(body),
256
368
  redirect: 'error',
257
369
  }, {
258
370
  read: 'text',
@@ -263,33 +375,33 @@ export class SubstrateClient {
263
375
  });
264
376
  }
265
377
  catch (e) {
266
- throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, 'Substrate search') ?? e;
378
+ throw describeTransportFailure(e, lookup.url, lookup.service) ?? e;
267
379
  }
268
380
  text = r.body;
269
381
  return r.res;
270
382
  });
271
383
  try {
272
- checkStatus(res.status);
384
+ checkStatus(res.status, lookup);
273
385
  }
274
386
  catch (error) {
275
387
  // A 401 here is on a token `withAuth` just re-captured: the capture itself
276
388
  // 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.
389
+ // unforced call does not hold the caller for another capture window.
278
390
  if (res.status === 401)
279
391
  this.#captureFailure = { at: Date.now(), error };
280
392
  throw error;
281
393
  }
282
394
  try {
283
- return parseQueryResponse(JSON.parse(text));
395
+ return JSON.parse(text);
284
396
  }
285
397
  catch {
286
- // Never echo the body: it holds message content.
398
+ // Never echo the body: it holds message content or people's details.
287
399
  throw new McpToolError('Substrate returned a response that is not JSON.', { status: res.status, kind: 'http' });
288
400
  }
289
401
  }
290
402
  }
291
403
  /** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
292
- function checkStatus(status) {
404
+ function checkStatus(status, lookup) {
293
405
  if (status >= 200 && status < 300)
294
406
  return;
295
407
  if (status === 401) {
@@ -300,9 +412,13 @@ function checkStatus(status) {
300
412
  });
301
413
  }
302
414
  if (status === 429) {
303
- throw new McpToolError('Substrate is rate-limiting searches (429).', { status, kind: 'http', hint: 'Wait a minute before retrying.' });
415
+ throw new McpToolError(`Substrate is rate-limiting ${lookup.plural} (429).`, {
416
+ status,
417
+ kind: 'http',
418
+ hint: 'Wait a minute before retrying.',
419
+ });
304
420
  }
305
- throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
421
+ throw new McpToolError(`${lookup.service} returned HTTP ${status}.`, {
306
422
  status,
307
423
  kind: 'http',
308
424
  ...(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
- 'your Teams tab reloaded 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 your Teams tab reloaded 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.';