@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.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/chatsvc.js CHANGED
@@ -8,11 +8,12 @@
8
8
  *
9
9
  * Reads are `listConversations`, `getMessages` (which also reads the Activity
10
10
  * feed, conversation `48:notifications`), `getMessage` and
11
- * `fetchImage`; the writes are `sendMessage`, `setReaction` and
12
- * `removeReaction`, which only the confirm-gated `teams_send_message` and
13
- * `teams_react` call. Nothing here writes the read marker
14
- * (`consumptionhorizon`), so reading a chat through this MCP never clears the
15
- * user's unread badges.
11
+ * `fetchImage`; the writes are `sendMessage`, `setReaction`,
12
+ * `removeReaction` and `setConsumptionHorizon`, which only the confirm-gated
13
+ * `teams_send_message`, `teams_react` and `teams_mark_read` (and the read
14
+ * tools' opt-in `mark_read`) call. A read never writes the read marker
15
+ * (`consumptionhorizon`) on its own, so reading a chat through this MCP leaves
16
+ * the user's unread badges alone unless they ask for it to be marked read.
16
17
  *
17
18
  * Verified live 2026-10-10 against a real Teams tenant — see the "Verified
18
19
  * live facts" section of `docs/plans/2026-10-10-chatsvc-api.md` for the
@@ -94,6 +95,8 @@ function outcomeUnknown(method, e, hint) {
94
95
  }
95
96
  const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_read_conversation) before retrying; do not resend blindly.';
96
97
  const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_read_conversation) before retrying.';
98
+ const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_read_conversation) before retrying; ' +
99
+ 'moving it again to the same message is harmless.';
97
100
  /**
98
101
  * The HTTP status behind a {@link WriteOutcomeUnknownError} that Teams
99
102
  * answered with a 5xx, or `undefined` when it timed out or the connection
@@ -271,8 +274,12 @@ export class ChatServiceClient {
271
274
  return out;
272
275
  }
273
276
  /**
274
- * One message by id, or `undefined` when the service has no such message
275
- * (404). Used to quote a message: its sender and text go into the quote.
277
+ * One message by id, or `undefined` when the service answers 404. Used to
278
+ * quote a message (its sender and text go into the quote) and to fill in a
279
+ * channel thread's root post when it is older than a read's window — a
280
+ * channel root fetched by its id answers like any message (verified live
281
+ * 2026-10-12). An id the channel does not hold was answered 403, not 404,
282
+ * live, so that surfaces as an error.
276
283
  */
277
284
  async getMessage(conversationId, messageId) {
278
285
  this.#requireConfigured();
@@ -330,6 +337,27 @@ export class ChatServiceClient {
330
337
  const { status } = await this.#send(url, 'text', undefined, { method, body: { emotions }, hint: REACTION_OUTCOME_HINT });
331
338
  this.#checkWriteStatus(method, status, REACTION_OUTCOME_HINT);
332
339
  }
340
+ /**
341
+ * Move the user's read marker in a conversation to `messageId`:
342
+ * `PUT …/conversations/{id}/properties?name=consumptionhorizon` with
343
+ * `{ consumptionhorizon: "<id>;<client ms>;<id>" }` — the shape `readHorizon`
344
+ * parses, its first segment the message's arrival ms (which is its id).
345
+ * Teams clears the unread badge for everything up to it.
346
+ *
347
+ * Verified live 2026-10-12 on `48:notes`: 200, and the listing then carries
348
+ * the new horizon. A move BACKWARDS is also answered 200 but ignored, so a
349
+ * 200 does not prove the marker moved; never sending one is the caller's
350
+ * rule (`teams_mark_read`), which reports it as a no-op instead. A lost
351
+ * answer is a `WriteOutcomeUnknownError`, as for a reaction.
352
+ */
353
+ async setConsumptionHorizon(conversationId, messageId, at = Date.now()) {
354
+ this.#requireConfigured();
355
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
356
+ '/properties?name=consumptionhorizon';
357
+ const body = { consumptionhorizon: `${messageId};${at};${messageId}` };
358
+ const { status } = await this.#send(url, 'text', undefined, { method: 'PUT', body, hint: HORIZON_OUTCOME_HINT });
359
+ this.#checkWriteStatus('PUT', status, HORIZON_OUTCOME_HINT);
360
+ }
333
361
  /**
334
362
  * Download an inline image (`<img src>` in a message body).
335
363
  *
package/dist/index.js CHANGED
@@ -3,14 +3,18 @@ import { runMcp, loadDotenvSafely } from '@chrischall/mcp-utils';
3
3
  import { VERSION } from './version.js';
4
4
  import { ChatServiceClient } from './chatsvc.js';
5
5
  import { SharePointClient } from './sharepoint.js';
6
+ import { SubstrateClient } from './substrate.js';
6
7
  import { registerChatTools } from './tools/chat.js';
7
8
  import { registerChannelTools } from './tools/channels.js';
8
9
  import { registerConversationTools } from './tools/conversation.js';
9
10
  import { registerUnreadTools } from './tools/unread.js';
11
+ import { registerChangesTools } from './tools/changes.js';
10
12
  import { registerAttachmentTools } from './tools/attachment.js';
11
13
  import { registerSendTools } from './tools/send.js';
12
14
  import { registerReactTools } from './tools/react.js';
15
+ import { registerMarkReadTools } from './tools/markread.js';
13
16
  import { registerActivityTools } from './tools/activity.js';
17
+ import { registerSearchTools } from './tools/search.js';
14
18
  import { registerHealthcheckTool } from './tools/healthcheck.js';
15
19
  loadDotenvSafely();
16
20
  /**
@@ -19,11 +23,13 @@ loadDotenvSafely();
19
23
  * connection, so anything built inside a registrar would be rebuilt). For
20
24
  * this MCP a second `ChatServiceClient` would mean a second token capture.
21
25
  * `SharePointClient` holds its own per-host token managers, so the same reason
22
- * applies — build it once, here, beside the chat-service client.
26
+ * applies — build it once, here, beside the chat-service client — and so does
27
+ * `SubstrateClient`, which holds the search token.
23
28
  */
24
29
  const deps = {
25
30
  chatsvc: new ChatServiceClient(),
26
31
  sharepoint: new SharePointClient(),
32
+ substrate: new SubstrateClient(),
27
33
  };
28
34
  await runMcp({
29
35
  name: 'microsoft-teams-mcp',
@@ -35,10 +41,13 @@ await runMcp({
35
41
  registerChannelTools,
36
42
  registerConversationTools,
37
43
  registerUnreadTools,
44
+ registerChangesTools,
38
45
  registerAttachmentTools,
39
46
  registerSendTools,
40
47
  registerReactTools,
48
+ registerMarkReadTools,
41
49
  registerActivityTools,
50
+ registerSearchTools,
42
51
  registerHealthcheckTool,
43
52
  ],
44
53
  });
package/dist/model.js CHANGED
@@ -136,6 +136,25 @@ export function newestActivityMs(c) {
136
136
  const signals = [lastArrival, lastImReceivedMs(c)].filter((n) => n !== undefined && Number.isFinite(n) && n > 0);
137
137
  return signals.length === 0 ? undefined : Math.max(...signals);
138
138
  }
139
+ /** A listing field that is epoch ms, as a number or a numeric string; `undefined` otherwise. */
140
+ function epochMs(raw) {
141
+ const ms = typeof raw === 'number' ? raw : typeof raw === 'string' && /^\s*\d+\s*$/.test(raw) ? Number(raw) : NaN;
142
+ return Number.isFinite(ms) && ms > 0 ? ms : undefined;
143
+ }
144
+ /**
145
+ * The conversation's newest change of any kind (epoch ms): {@link newestActivityMs}
146
+ * or the last updated message's id or version, whichever is later. Live
147
+ * (2026-10-12), a channel reply moves only `lastUpdatedMessageId` /
148
+ * `lastUpdatedMessageVersion` — `lastMessage` stays on the newest root post —
149
+ * so this is what says a channel thread got a reply. It also moves for an
150
+ * edit or a reaction, so a conversation past a time by this measure may hold
151
+ * no new message: only a read can tell. `undefined` when the listing carries
152
+ * none of them.
153
+ */
154
+ export function lastChangeMs(c) {
155
+ const signals = [newestActivityMs(c), epochMs(c.lastUpdatedMessageId), epochMs(c.lastUpdatedMessageVersion)].filter((n) => n !== undefined);
156
+ return signals.length === 0 ? undefined : Math.max(...signals);
157
+ }
139
158
  /**
140
159
  * Whether the conversation is an unread CANDIDATE: its newest activity — the
141
160
  * later of `lastimreceivedtime` and the last message's arrival, of any type —
@@ -188,6 +207,11 @@ function flag(c, name) {
188
207
  const v = c.properties?.[name];
189
208
  return v === true || (typeof v === 'string' && v.trim().toLowerCase() === 'true');
190
209
  }
210
+ /** A `properties` flag Teams sends as `"false"` / `"False"` (or a boolean) — absent is not false. */
211
+ function flagOff(c, name) {
212
+ const v = c.properties?.[name];
213
+ return v === false || (typeof v === 'string' && v.trim().toLowerCase() === 'false');
214
+ }
191
215
  /** A channel the user has hidden in Teams. */
192
216
  function isHiddenChannel(c) {
193
217
  return c.memberProperties?.interest === 'NotInterested';
@@ -238,6 +262,7 @@ export function conversationSummary(c, meMri, all = []) {
238
262
  unread,
239
263
  unread_confirmed: false,
240
264
  ...(hidden ? { hidden: true } : {}),
265
+ ...(flagOff(c, 'alerts') ? { muted: true } : {}),
241
266
  ...(flag(c, 'favorite') ? { favorite: true } : {}),
242
267
  ...(flag(c, 'ispinned') ? { pinned: true } : {}),
243
268
  ...(lastActivity !== undefined ? { lastActivity } : {}),
@@ -284,11 +309,24 @@ function attr(tag, name) {
284
309
  return m ? (m[1] ?? m[2]) : undefined;
285
310
  }
286
311
  const stripTags = (s) => s.replace(/<\/?[a-z!][^>]*>/gi, '');
312
+ /**
313
+ * One table row on one line, its `<td>`/`<th>` cells joined by ` | ` — a
314
+ * pasted table (a file-monitor report, a status grid) otherwise runs its cells
315
+ * together. Line breaks inside a cell become spaces so the row stays whole.
316
+ */
317
+ function tableRow(row) {
318
+ const cells = [...row.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)(?:<\/t[dh]\s*>|(?=<t[dh]\b)|$)/gi)].map(([, cell]) => cell
319
+ .replace(/[\u0001\u0002]/g, '')
320
+ .replace(/<br\s*\/?>|<\/?(p|div|li|h[1-6])\b[^>]*>|\r?\n/gi, ' ')
321
+ .trim());
322
+ return cells.length > 0 ? cells.join(' | ') : row;
323
+ }
287
324
  /**
288
325
  * A Teams message body as readable plain text. Links keep their target as
289
326
  * `text (url)`, inline images become `[image]` (emoji become their alt text),
290
- * and a quoted reply's lines are prefixed `> `. No HTML library: Teams bodies
291
- * are a small, regular subset.
327
+ * a table row becomes one line of ` | `-separated cells, and a quoted reply's
328
+ * lines are prefixed `> `. Never truncated: a long body comes back whole. No
329
+ * HTML library: Teams bodies are a small, regular subset.
292
330
  */
293
331
  export function htmlToText(html) {
294
332
  let s = html.replace(/[\u0001\u0002]/g, '');
@@ -307,6 +345,7 @@ export function htmlToText(html) {
307
345
  return href;
308
346
  return `${inner} (${href})`;
309
347
  });
348
+ s = s.replace(/<tr\b[^>]*>([\s\S]*?)<\/tr\s*>/gi, (_whole, row) => `\n${tableRow(row)}\n`);
310
349
  // Block elements start and end a line (a quote's author <strong> runs
311
350
  // straight into its <p> otherwise); the blank lines this makes collapse below.
312
351
  s = s.replace(/<br\s*\/?>/gi, '\n').replace(/<\/?(p|div|li|tr|h[1-6])\b[^>]*>/gi, '\n');
@@ -431,7 +470,49 @@ export function oldestFirst(messages) {
431
470
  .sort((a, b) => (Number.isNaN(a.t) || Number.isNaN(b.t) ? 0 : a.t - b.t))
432
471
  .map(({ m }) => m);
433
472
  }
434
- export function normaliseMessage(m, meMri) {
473
+ /** True when `Intl` knows `tz` as a time zone (an IANA name such as `America/New_York`, or `UTC`). */
474
+ export function isTimeZone(tz) {
475
+ if (tz.trim() === '')
476
+ return false;
477
+ try {
478
+ new Intl.DateTimeFormat('en-US', { timeZone: tz });
479
+ return true;
480
+ }
481
+ catch {
482
+ return false;
483
+ }
484
+ }
485
+ const pad = (n, width = 2) => String(n).padStart(width, '0');
486
+ /**
487
+ * An ISO instant as wall-clock time in `timeZone`, ISO 8601 with that zone's
488
+ * offset at that instant (`2026-10-09T08:05:00.000-04:00`) — so DST is right
489
+ * per message. `undefined` for an unreadable time; `timeZone` must be valid
490
+ * ({@link isTimeZone}).
491
+ */
492
+ export function localIsoTime(iso, timeZone) {
493
+ const ms = Date.parse(iso);
494
+ if (Number.isNaN(ms))
495
+ return undefined;
496
+ const parts = new Intl.DateTimeFormat('en-US', {
497
+ timeZone,
498
+ hourCycle: 'h23',
499
+ year: 'numeric',
500
+ month: '2-digit',
501
+ day: '2-digit',
502
+ hour: '2-digit',
503
+ minute: '2-digit',
504
+ second: '2-digit',
505
+ }).formatToParts(new Date(ms));
506
+ const get = (type) => Number(parts.find((p) => p.type === type)?.value);
507
+ const millis = ((ms % 1000) + 1000) % 1000;
508
+ const wall = Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second'), millis);
509
+ const offsetMin = Math.round((wall - ms) / 60_000);
510
+ const sign = offsetMin < 0 ? '-' : '+';
511
+ const abs = Math.abs(offsetMin);
512
+ return (`${pad(get('year'), 4)}-${pad(get('month'))}-${pad(get('day'))}T${pad(get('hour'))}:${pad(get('minute'))}:` +
513
+ `${pad(get('second'))}.${pad(millis, 3)}${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`);
514
+ }
515
+ export function normaliseMessage(m, meMri, opts = {}) {
435
516
  const props = m.properties ?? {};
436
517
  const mri = senderMri(m.from);
437
518
  const arrival = Number(m.id);
@@ -442,9 +523,11 @@ export function normaliseMessage(m, meMri) {
442
523
  const root = /;messageid=(\d+)/.exec(m.conversationLink ?? '')?.[1];
443
524
  const content = m.content ?? '';
444
525
  const reactions = reactionsOf(props.emotions, meMri);
526
+ const timeLocal = opts.timeZone !== undefined ? localIsoTime(time, opts.timeZone) : undefined;
445
527
  return {
446
528
  id: m.id,
447
529
  time,
530
+ ...(timeLocal !== undefined ? { time_local: timeLocal } : {}),
448
531
  sender: nonEmpty(m.imdisplayname) ?? mri ?? 'unknown',
449
532
  fromMe: mri !== undefined && mri === meMri,
450
533
  text: htmlToText(content),
@@ -470,30 +553,51 @@ export function summariseAll(raw, meMri) {
470
553
  /**
471
554
  * Resolve a user's `conversation` argument: an exact id wins outright, then
472
555
  * `notes` / `self` name the self-chat, else a case-insensitive substring of
473
- * the title, team name, or one of an untitled group chat's participants. A
474
- * title this server made up — "Group chat: …" or "(untitled group chat)" — is
475
- * not itself matched, so "group" or "chat" does not hit every untitled group
476
- * chat: such a chat matches by its participants instead.
556
+ * the title, team name, or one of an untitled group chat's participants (and,
557
+ * with `messages`, the last-message preview). A title this server made up —
558
+ * "Group chat: …", "(untitled group chat)", or an untitled 1:1's other person
559
+ * — is not itself matched, so "group" or "chat" does not hit every untitled
560
+ * group chat: such a chat matches by its participants instead. Each match is a
561
+ * copy carrying its {@link MatchReason} — the first that applies, in order.
477
562
  */
478
- export function matchConversations(summaries, query) {
563
+ export function matchConversations(summaries, query, { messages = false } = {}) {
479
564
  const exact = summaries.find((s) => s.id === query);
480
565
  if (exact)
481
- return [exact];
566
+ return [{ ...exact, match_reason: 'id' }];
482
567
  const q = query.trim().toLowerCase();
483
568
  if (q === '')
484
569
  return [];
485
570
  if (SELF_CHAT_ALIASES.has(q)) {
486
571
  const self = summaries.find((s) => s.id === SELF_CHAT);
487
572
  if (self)
488
- return [self];
573
+ return [{ ...self, match_reason: 'title' }];
489
574
  }
490
- return summaries.filter((s) => (hasRealTitle(s) && s.title.toLowerCase().includes(q)) ||
491
- (s.team?.toLowerCase().includes(q) ?? false) ||
492
- (s.participants?.some((p) => p.toLowerCase().includes(q)) ?? false));
575
+ return summaries.flatMap((s) => {
576
+ const reason = matchReason(s, q, messages);
577
+ return reason === undefined ? [] : [{ ...s, match_reason: reason }];
578
+ });
579
+ }
580
+ /** The first reason `s` matches the lower-cased query `q`, or `undefined`. */
581
+ function matchReason(s, q, messages) {
582
+ if (hasRealTitle(s) && s.title.toLowerCase().includes(q))
583
+ return 'title';
584
+ if (s.team?.toLowerCase().includes(q))
585
+ return 'team';
586
+ if (s.participants?.some((p) => p.toLowerCase().includes(q)))
587
+ return 'participant';
588
+ if (messages && s.lastMessagePreview !== undefined && s.lastMessagePreview !== SYSTEM_EVENT_PREVIEW) {
589
+ if (s.lastMessagePreview.toLowerCase().includes(q))
590
+ return 'message';
591
+ }
592
+ return undefined;
493
593
  }
494
- /** False for a title made from participants, or an untitled-group / untitled-1:1 stand-in. */
594
+ /**
595
+ * False for a title made from participants (an untitled group chat's, or an
596
+ * untitled 1:1's other person — only such chats carry `participants`), or an
597
+ * untitled-group / untitled-1:1 stand-in.
598
+ */
495
599
  function hasRealTitle(s) {
496
600
  if (s.title === UNTITLED_GROUP_TITLE || s.title === UNTITLED_ONE_ON_ONE_TITLE)
497
601
  return false;
498
- return !(s.participants !== undefined && s.title.startsWith(GROUP_TITLE_PREFIX));
602
+ return s.participants === undefined;
499
603
  }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Bootstrap-only fetchproxy auth for Microsoft Substrate search — the backend
3
+ * the Teams web client's own search box uses (`teams_search_messages`).
4
+ *
5
+ * Substrate does not accept the chat-service token (its audience is
6
+ * `https://ic3.teams.office.com`), so search needs a THIRD token, captured the
7
+ * same way the other two are: we snapshot the `Authorization: Bearer …` header
8
+ * off a request the signed-in Teams tab makes to
9
+ * `substrate.office.com/searchservice/*` — which it does when the user runs a
10
+ * search in Teams' search box — and then talk to Substrate with a plain Node
11
+ * `fetch` (`substrate.ts`). Requests only: nothing here, or anywhere in this
12
+ * MCP, reads a token out of page storage.
13
+ *
14
+ * The capture path is restricted to `/searchservice/*` rather than `/*`: other
15
+ * Substrate APIs the page calls are minted for other scopes, and a token lifted
16
+ * off one of those could fail on the search API in ways that look like a
17
+ * Substrate outage.
18
+ *
19
+ * Verified live 2026-10-12: after a one-time pair approval in the ContextMint
20
+ * Bridge popup (the `substrate.office.com` scope), running any search in the
21
+ * Teams search box during the capture window yielded a token off
22
+ * `/searchservice/*` (an app-GUID audience, ~1.4h lifetime) that
23
+ * `substrate.ts` replayed successfully from Node. Until the pair is approved,
24
+ * the capture fails fast with "pairing required" and search falls back to the
25
+ * scan.
26
+ *
27
+ * Import this module LAZILY (`await import('./substrate-auth.js')`), as
28
+ * `sharepoint-auth.ts` is, so a server run with `TEAMS_DISABLE_FETCHPROXY`
29
+ * never has to load the bridge to boot.
30
+ */
31
+ import { createBootstrapOpts, createFetchproxyTransport } from '@chrischall/mcp-utils/fetchproxy';
32
+ import { bridgeDeadlineMs, captureWindowMs } from './capture-window.js';
33
+ import { getWsPort, stripBearer } from './auth-fetchproxy.js';
34
+ import { PACKAGE_NAME, VERSION } from './version.js';
35
+ /** The one request we capture from: a search-service call the Teams tab makes. */
36
+ export const SUBSTRATE_CAPTURE_DECL = {
37
+ host: 'substrate.office.com',
38
+ path: '/searchservice/*',
39
+ headerName: 'authorization',
40
+ };
41
+ /**
42
+ * The extension's trust boundary for search: exactly the host we capture from.
43
+ * A third, independent scope beside `teams.cloud.microsoft` and
44
+ * `sharepoint.com` — granting it takes a one-time re-pair of
45
+ * `microsoft-teams-mcp` in the ContextMint Bridge popup; until then search falls
46
+ * back to the client-side scan.
47
+ */
48
+ export const SUBSTRATE_TRUST_DOMAINS = [SUBSTRATE_CAPTURE_DECL.host];
49
+ /** Shortest plausible token; guards against an empty or echoed header only. */
50
+ const MIN_TOKEN_LENGTH = 100;
51
+ /**
52
+ * Capture a Substrate search token from the user's signed-in Teams tab.
53
+ * Returns the bare token (no `Bearer ` prefix).
54
+ */
55
+ export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
56
+ // Read per capture, not at import: see `capture-window.ts`.
57
+ const windowMs = captureWindowMs(env);
58
+ const transport = createFetchproxyTransport({
59
+ // Same verb set as the other two captures (`capture_request_header` beside
60
+ // the always-on `fetch`); only the trusted domain differs.
61
+ ...createBootstrapOpts({
62
+ domains: [...SUBSTRATE_TRUST_DOMAINS],
63
+ bootstrap: { captureHeaders: [{ ...SUBSTRATE_CAPTURE_DECL }] },
64
+ }),
65
+ port: getWsPort(),
66
+ fetchTimeoutMs: bridgeDeadlineMs(windowMs),
67
+ captureWindowMs: windowMs,
68
+ serverName: PACKAGE_NAME,
69
+ version: VERSION,
70
+ });
71
+ try {
72
+ // Loads the identity keypair; skipping it makes the first verb throw
73
+ // "ensureConnected called before listen()" (see `auth-fetchproxy.ts`).
74
+ await transport.start();
75
+ try {
76
+ const raw = await transport.server.captureRequestHeader({ ...SUBSTRATE_CAPTURE_DECL, timeoutMs: windowMs });
77
+ if (typeof raw !== 'string') {
78
+ throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: capture returned no header`);
79
+ }
80
+ const token = stripBearer(raw);
81
+ if (token.length < MIN_TOKEN_LENGTH) {
82
+ throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: authorization header was present but too short to be a ` +
83
+ `token (${token.length} chars)`);
84
+ }
85
+ return token;
86
+ }
87
+ catch (e) {
88
+ const detail = e.message;
89
+ throw new Error(`could not capture a Substrate search token from the browser (${detail}). ` +
90
+ 'In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top ' +
91
+ 'and press Enter — that is what makes Teams call substrate.office.com, where the token ' +
92
+ 'is read from — then retry. A "not in declared set" error means the ContextMint Bridge ' +
93
+ 'pairing does not trust substrate.office.com yet: re-pair microsoft-teams-mcp once.');
94
+ }
95
+ }
96
+ finally {
97
+ try {
98
+ await transport.close();
99
+ }
100
+ catch {
101
+ /* the token, or the original failure, is what matters */
102
+ }
103
+ }
104
+ }
@@ -0,0 +1,64 @@
1
+ import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
+ import { parseBoolEnv } from '@chrischall/mcp-utils';
3
+ import { reportCacheWriteFailure } from './token-cache.js';
4
+ /**
5
+ * Where the captured Substrate search token is cached between runs.
6
+ *
7
+ * Its own file, beside `token.json` (chat service) and `sharepoint-tokens.json`:
8
+ * a different audience with its own lifetime, and one token overall (Substrate
9
+ * has a single host), so a plain `BearerTokens`, not a per-host map.
10
+ */
11
+ export function substrateTokenCachePath(env = process.env) {
12
+ return resolveStateFile({
13
+ env,
14
+ envVar: 'TEAMS_SUBSTRATE_TOKEN_FILE',
15
+ subdir: '.microsoft-teams-mcp',
16
+ fileName: 'substrate-token.json',
17
+ });
18
+ }
19
+ /** Same `BearerTokens` guard as the other caches; copied, as it is module-private there. */
20
+ function isToken(raw) {
21
+ if (raw === null || typeof raw !== 'object')
22
+ return false;
23
+ const t = raw;
24
+ return (typeof t.accessToken === 'string' &&
25
+ t.accessToken !== '' &&
26
+ typeof t.expiresAt === 'number' &&
27
+ (t.refreshToken === undefined || typeof t.refreshToken === 'string'));
28
+ }
29
+ /**
30
+ * The Substrate token cache, or `null` when it is off or there is nothing to
31
+ * cache. Gated like the SharePoint cache: `TEAMS_TOKEN_CACHE` (default on), and
32
+ * off under `TEAMS_DISABLE_FETCHPROXY` — the bridge is the only source of a
33
+ * Substrate token. A failed write is reported, never thrown.
34
+ */
35
+ export function createSubstrateTokenCache(env = process.env) {
36
+ if (!parseBoolEnv('TEAMS_TOKEN_CACHE', { env, default: true }))
37
+ return null;
38
+ if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
39
+ return null;
40
+ const file = createFileStatePersistence({
41
+ filePath: substrateTokenCachePath(env),
42
+ boundTo: 'fetchproxy',
43
+ validate: (raw) => (isToken(raw) ? raw : null),
44
+ });
45
+ return {
46
+ load: () => file.load(),
47
+ save(tokens) {
48
+ try {
49
+ file.save(tokens);
50
+ }
51
+ catch (err) {
52
+ reportCacheWriteFailure(err);
53
+ }
54
+ },
55
+ clear() {
56
+ try {
57
+ file.clear();
58
+ }
59
+ catch (err) {
60
+ reportCacheWriteFailure(err);
61
+ }
62
+ },
63
+ };
64
+ }