@chrischall/microsoft-teams-mcp 0.3.0 → 0.4.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 (39) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +279 -93
  4. package/dist/auth-fetchproxy.js +138 -0
  5. package/dist/bundle.js +42380 -37144
  6. package/dist/capture-window.js +41 -0
  7. package/dist/chatsvc.js +552 -0
  8. package/dist/compose.js +241 -0
  9. package/dist/deps.js +1 -0
  10. package/dist/index.js +26 -6
  11. package/dist/model.js +499 -0
  12. package/dist/sharepoint-auth.js +162 -0
  13. package/dist/sharepoint-token-cache.js +105 -0
  14. package/dist/sharepoint.js +289 -0
  15. package/dist/token-cache.js +67 -0
  16. package/dist/tools/activity.js +155 -19
  17. package/dist/tools/attachment.js +174 -0
  18. package/dist/tools/channels.js +60 -44
  19. package/dist/tools/chat.js +47 -42
  20. package/dist/tools/confirm.js +145 -0
  21. package/dist/tools/conversation.js +172 -32
  22. package/dist/tools/errors.js +18 -17
  23. package/dist/tools/healthcheck.js +86 -27
  24. package/dist/tools/limit.js +43 -12
  25. package/dist/tools/listing.js +116 -0
  26. package/dist/tools/react.js +217 -0
  27. package/dist/tools/send.js +309 -0
  28. package/dist/tools/titles.js +180 -0
  29. package/dist/tools/unread.js +162 -0
  30. package/dist/tools/untrusted.js +16 -1
  31. package/dist/version.js +1 -1
  32. package/mint.yaml +63 -20
  33. package/package.json +1 -2
  34. package/server.json +80 -3
  35. package/skills/teams-fpx/SKILL.md +108 -92
  36. package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
  37. package/skills/teams-fpx/references/teams-env.sh +146 -0
  38. package/dist/client.js +0 -290
  39. package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
@@ -0,0 +1,41 @@
1
+ /**
2
+ * How long a token capture may wait, and the bridge deadline that has to
3
+ * outlast it.
4
+ *
5
+ * Kept free of any bridge import, so it can be read and tested without
6
+ * loading `auth-fetchproxy.ts` (the one transport this MCP builds) and its
7
+ * optional `@fetchproxy/server` peer. Both are read at CALL time, not module
8
+ * load, so `TEAMS_CAPTURE_TIMEOUT` set by the host's env (or a `.env` loaded
9
+ * after import) is honoured.
10
+ */
11
+ import { readTtlMsEnv } from '@chrischall/mcp-utils';
12
+ /**
13
+ * The capture window when `TEAMS_CAPTURE_TIMEOUT` is unset, unparseable or 0.
14
+ *
15
+ * The window IS the mechanism: capture resolves on the NEXT matching request,
16
+ * so nothing the page did before the listener came up counts. 30s is long
17
+ * enough for the user to click into a chat, short enough that an idle tab does
18
+ * not hang a tool call for minutes.
19
+ */
20
+ export const DEFAULT_CAPTURE_WINDOW_MS = 30_000;
21
+ /** How far the bridge deadline outlasts the capture window (one round trip, generously). */
22
+ export const DEADLINE_MARGIN_MS = 15_000;
23
+ /** `@fetchproxy/server`'s own default deadline; never go below it. */
24
+ const MIN_DEADLINE_MS = 30_000;
25
+ /** `TEAMS_CAPTURE_TIMEOUT` (seconds) as milliseconds. */
26
+ export function captureWindowMs(env = process.env) {
27
+ const ms = readTtlMsEnv('TEAMS_CAPTURE_TIMEOUT', DEFAULT_CAPTURE_WINDOW_MS, { env });
28
+ return ms > 0 ? ms : DEFAULT_CAPTURE_WINDOW_MS;
29
+ }
30
+ /**
31
+ * The transport-wide deadline (`fetchTimeoutMs`) for a capture window.
32
+ *
33
+ * A verb's own `timeoutMs` is cut off by `fetchTimeoutMs` on older bridges, so
34
+ * a window raised past the deadline fails early at the deadline's number —
35
+ * which reads as a timeout nobody configured. Deriving it means the two cannot
36
+ * disagree, and the extension's own "no request arrived" answer is the one the
37
+ * caller sees.
38
+ */
39
+ export function bridgeDeadlineMs(windowMs) {
40
+ return Math.max(windowMs + DEADLINE_MARGIN_MS, MIN_DEADLINE_MS);
41
+ }
@@ -0,0 +1,552 @@
1
+ /**
2
+ * The Teams chat-service REST client.
3
+ *
4
+ * Auth is a bearer token whose only source is the user's browser (see
5
+ * `auth-fetchproxy.ts`), or a `TEAMS_ACCESS_TOKEN` supplied directly. Once
6
+ * held, every request is a plain Node `fetch` — the bridge is never on the hot
7
+ * path.
8
+ *
9
+ * Reads are `listConversations`, `getMessages` (which also reads the Activity
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.
16
+ *
17
+ * Verified live 2026-10-10 against a real Teams tenant — see the "Verified
18
+ * live facts" section of `docs/plans/2026-10-10-chatsvc-api.md` for the
19
+ * response shapes the types below describe.
20
+ */
21
+ import { decodeJwtClaim, decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
22
+ import { TokenManager } from '@chrischall/mcp-utils/session';
23
+ import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
24
+ import { SELF_CHAT } from './model.js';
25
+ /**
26
+ * Load the bridge bootstrap lazily.
27
+ *
28
+ * `auth-fetchproxy.ts` pulls in `@chrischall/mcp-utils/fetchproxy`, which
29
+ * imports the OPTIONAL `@fetchproxy/server` peer. The `.mcpb` bundle ships no
30
+ * `node_modules`, so a top-level import here would throw
31
+ * `ERR_MODULE_NOT_FOUND` before the server could answer `initialize`. Deferring
32
+ * it means a user who supplies `TEAMS_ACCESS_TOKEN` never needs it installed.
33
+ */
34
+ async function captureTokenLazily() {
35
+ const mod = await import('./auth-fetchproxy.js');
36
+ return mod.captureTokenViaFetchproxy();
37
+ }
38
+ /** The chat-service region this tenant was verified on. */
39
+ export const DEFAULT_REGION = 'amer';
40
+ /**
41
+ * The chat-service base URL: `TEAMS_CHATSVC_BASE` verbatim when set, else the
42
+ * New Teams proxy path for `TEAMS_CHATSVC_REGION` (default `amer`).
43
+ */
44
+ export function chatServiceBase(env = process.env) {
45
+ const override = readEnvVar('TEAMS_CHATSVC_BASE', { env });
46
+ if (override !== undefined)
47
+ return override.replace(/\/+$/, '');
48
+ const region = readEnvVar('TEAMS_CHATSVC_REGION', { env }) ?? DEFAULT_REGION;
49
+ return `https://teams.cloud.microsoft/api/chatsvc/${encodeURIComponent(region)}/v1`;
50
+ }
51
+ /**
52
+ * Fallback lifetime for a token whose `exp` we cannot read.
53
+ *
54
+ * Real tokens are JWTs carrying `exp` (~23.5h out), so this is only reached
55
+ * for a hand-supplied opaque `TEAMS_ACCESS_TOKEN`. Deliberately short: being
56
+ * wrong in this direction costs one extra 401-and-replay.
57
+ */
58
+ const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
59
+ /**
60
+ * Sentinel standing in for a refresh token this flow does not have.
61
+ *
62
+ * The token comes from MSAL's hidden-iframe flow; there is no refresh grant we
63
+ * can drive, so "refreshing" means capturing a new one. `TokenManager` only
64
+ * calls `refresh` when a refresh token is present, hence the sentinel.
65
+ */
66
+ const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
67
+ /** Per-request deadline, covering the body read. */
68
+ const REQUEST_TIMEOUT_MS = 60_000;
69
+ /** Paging caps — a runaway `backwardLink` chain must not hold a tool call open. */
70
+ const MAX_CONVERSATION_PAGES = 10;
71
+ const MAX_MESSAGE_PAGES = 20;
72
+ /** Messages per `getMessages` request unless the caller asks for fewer. */
73
+ const DEFAULT_MESSAGE_PAGE_SIZE = 200;
74
+ /** Largest inline image we will buffer (they measured 8–18 KB live). */
75
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
76
+ /**
77
+ * Inline images live on Skype's AMS object store (`us-api.asm.skype.com`, the
78
+ * host varies by region). The bearer is sent ONLY to hosts under this suffix.
79
+ */
80
+ const IMAGE_HOST_SUFFIX = '.asm.skype.com';
81
+ /**
82
+ * A write that failed after it may have reached Teams. A timeout or a
83
+ * transport failure (dropped connection, broken body, the caller cancelling)
84
+ * leaves the outcome unknown; an `McpToolError` raised before anything was
85
+ * sent (an oversized body cap, a bad URL) is a real failure and passes through.
86
+ */
87
+ function outcomeUnknown(method, e, hint) {
88
+ if (e instanceof RequestTimeoutError) {
89
+ return new WriteOutcomeUnknownError('Teams', method, { timeoutMs: e.timeoutMs, cause: e, hint });
90
+ }
91
+ if (e instanceof McpToolError)
92
+ return e;
93
+ return new WriteOutcomeUnknownError('Teams', method, { cause: e, hint });
94
+ }
95
+ const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_read_conversation) before retrying; do not resend blindly.';
96
+ const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_read_conversation) before retrying.';
97
+ /**
98
+ * The HTTP status behind a {@link WriteOutcomeUnknownError} that Teams
99
+ * answered with a 5xx, or `undefined` when it timed out or the connection
100
+ * dropped instead.
101
+ */
102
+ export function outcomeUnknownStatus(e) {
103
+ const status = e.cause?.status;
104
+ return typeof status === 'number' ? status : undefined;
105
+ }
106
+ function toBearerTokens(accessToken) {
107
+ let expiresAt;
108
+ try {
109
+ // decodeJwtExp returns seconds; a non-JWT throws.
110
+ expiresAt = decodeJwtExp(accessToken) * 1000;
111
+ }
112
+ catch {
113
+ expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
114
+ }
115
+ return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
116
+ }
117
+ export class ChatServiceClient {
118
+ #baseUrl;
119
+ /**
120
+ * Deferred configuration error. The constructor never throws, so the server
121
+ * still boots (and answers `tools/list`) with no credential present.
122
+ */
123
+ #configError = null;
124
+ #env;
125
+ #capture;
126
+ #fetchImpl;
127
+ #direct;
128
+ #tokens = null;
129
+ constructor(opts = {}) {
130
+ this.#env = opts.env ?? process.env;
131
+ this.#capture = opts.captureToken ?? captureTokenLazily;
132
+ // A receiver-safe wrapper, never the bare global: older undici throws
133
+ // `Illegal invocation` when `fetch` is called with a non-global receiver.
134
+ this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
135
+ this.#baseUrl = chatServiceBase(this.#env);
136
+ this.#direct = readEnvVar('TEAMS_ACCESS_TOKEN', { env: this.#env });
137
+ const bridgeOff = parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env: this.#env });
138
+ if (this.#direct === undefined && bridgeOff) {
139
+ this.#configError = new McpToolError('No Teams credential is configured.', {
140
+ kind: 'no_credential',
141
+ hint: 'Set TEAMS_ACCESS_TOKEN, or unset TEAMS_DISABLE_FETCHPROXY so the token can ' +
142
+ 'be captured from a signed-in Teams browser tab.',
143
+ });
144
+ }
145
+ }
146
+ /** Non-secret description of where the credential comes from. */
147
+ get tokenSource() {
148
+ return this.#direct !== undefined ? 'TEAMS_ACCESS_TOKEN' : 'browser capture';
149
+ }
150
+ /** The API base this client talks to. Non-secret; safe for healthcheck output. */
151
+ get apiBase() {
152
+ return this.#baseUrl;
153
+ }
154
+ /**
155
+ * Epoch ms at which the current token expires, or `null` if none is held —
156
+ * including after a capture that failed, when the token manager exists but
157
+ * holds nothing (it reports that as expiry 0, i.e. 1970).
158
+ */
159
+ tokenExpiresAt() {
160
+ const at = this.#tokens?.getExpiresAt();
161
+ return at !== undefined && Number.isFinite(at) && at > 0 ? at : null;
162
+ }
163
+ /**
164
+ * Hold a token — the cached one, or a fresh capture — without calling the
165
+ * API. The healthcheck resolves the credential with this before probing, so
166
+ * a capture failure is reported as one rather than as a failed request.
167
+ */
168
+ async ensureToken() {
169
+ this.#requireConfigured();
170
+ await this.#tokenManager().getAccessToken();
171
+ }
172
+ /**
173
+ * The signed-in user's MRI, `8:orgid:<oid>`, from the token's `oid` claim.
174
+ * Needed to tell the user's own messages from everyone else's.
175
+ */
176
+ async meMri() {
177
+ this.#requireConfigured();
178
+ const token = await this.#tokenManager().getAccessToken();
179
+ let oid;
180
+ try {
181
+ oid = decodeJwtClaim(token, 'oid');
182
+ }
183
+ catch {
184
+ oid = undefined;
185
+ }
186
+ if (typeof oid !== 'string' || oid === '') {
187
+ throw new McpToolError('The Teams token does not identify the signed-in user (no oid claim).', {
188
+ hint: 'Capture a fresh token from a signed-in teams.cloud.microsoft tab, or supply a ' +
189
+ 'TEAMS_ACCESS_TOKEN that is the chat-service JWT itself.',
190
+ });
191
+ }
192
+ return `8:orgid:${oid}`;
193
+ }
194
+ /**
195
+ * The signed-in user's display name, from the token's `name` claim — what a
196
+ * sent message carries as `imdisplayname`. `''` when the token has none.
197
+ */
198
+ async meDisplayName() {
199
+ this.#requireConfigured();
200
+ const token = await this.#tokenManager().getAccessToken();
201
+ try {
202
+ const name = decodeJwtClaim(token, 'name');
203
+ return typeof name === 'string' ? name : '';
204
+ }
205
+ catch {
206
+ return '';
207
+ }
208
+ }
209
+ /**
210
+ * Every conversation the user is in, across up to 10 pages, minus the
211
+ * `48:*` system threads (calendar, notifications, …) which are not chats —
212
+ * except `48:notes`, the user's self-chat, which is.
213
+ */
214
+ async listConversations() {
215
+ this.#requireConfigured();
216
+ const out = [];
217
+ let url = `${this.#baseUrl}/users/ME/conversations?view=msnp24Equivalent&pageSize=200`;
218
+ for (let page = 0; url !== undefined && page < MAX_CONVERSATION_PAGES; page++) {
219
+ const body = await this.#getJson(url);
220
+ const convs = body.conversations ?? [];
221
+ if (convs.length === 0)
222
+ break;
223
+ for (const c of convs) {
224
+ if (typeof c?.id === 'string' && (!c.id.startsWith('48:') || c.id === SELF_CHAT))
225
+ out.push(c);
226
+ }
227
+ url = this.#nextLink(body);
228
+ }
229
+ return out;
230
+ }
231
+ /**
232
+ * A conversation's messages, newest first, paging back until `stopAt`
233
+ * accepts a message, `max` are collected, the pages run out, or 20 pages
234
+ * have been read.
235
+ */
236
+ async getMessages(id, opts) {
237
+ this.#requireConfigured();
238
+ const out = [];
239
+ if (!(opts.max > 0))
240
+ return out;
241
+ let url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages` +
242
+ `?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
243
+ for (let page = 0; url !== undefined; page++) {
244
+ if (page >= MAX_MESSAGE_PAGES) {
245
+ opts.onCapped?.();
246
+ break;
247
+ }
248
+ const body = await this.#getJson(url);
249
+ const msgs = body.messages ?? [];
250
+ if (msgs.length === 0)
251
+ break;
252
+ // A page is newest first but not strictly ordered (seen live
253
+ // 2026-10-10), so the page `stopAt` fires in is finished — skipping
254
+ // each message it rejects — and only the NEXT page is not fetched.
255
+ let stopped = false;
256
+ for (const m of msgs) {
257
+ if (opts.stopAt?.(m)) {
258
+ stopped = true;
259
+ continue;
260
+ }
261
+ out.push(m);
262
+ if (out.length >= opts.max) {
263
+ opts.onCapped?.();
264
+ return out;
265
+ }
266
+ }
267
+ if (stopped)
268
+ return out;
269
+ url = this.#nextLink(body);
270
+ }
271
+ return out;
272
+ }
273
+ /**
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.
276
+ */
277
+ async getMessage(conversationId, messageId) {
278
+ this.#requireConfigured();
279
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
280
+ `/messages/${encodeURIComponent(messageId)}`;
281
+ const { status, body } = await this.#send(url, 'text');
282
+ if (status === 404)
283
+ return undefined;
284
+ return this.#parseJson(status, body);
285
+ }
286
+ /**
287
+ * Post a message (the body `compose.ts` builds). `conversationId` is the
288
+ * chat or channel — or, for a threaded channel reply, `<channelId>;messageid=<rootId>`,
289
+ * encoded as one path segment. Resolves the new message's id from the
290
+ * `Location` header when the service sends one.
291
+ *
292
+ * Not idempotent, so a request that was SENT but got no usable answer (a
293
+ * timeout, a dropped connection, a 5xx from a gateway or a failing backend)
294
+ * is a `WriteOutcomeUnknownError` — the post may already be in the chat,
295
+ * and a blind retry would post it twice. A 4xx is a refusal and stays a
296
+ * plain error. A 401 is still replayed once after a re-capture: Teams
297
+ * refused that request, so nothing was posted.
298
+ */
299
+ async sendMessage(conversationId, body) {
300
+ this.#requireConfigured();
301
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}/messages`;
302
+ const { status, headers } = await this.#send(url, 'text', undefined, { method: 'POST', body, hint: SEND_OUTCOME_HINT });
303
+ this.#checkWriteStatus('POST', status, SEND_OUTCOME_HINT);
304
+ const id = /\/messages\/([^/?#]+)\/?(?:[?#].*)?$/.exec(headers.get('location') ?? '')?.[1];
305
+ return id !== undefined ? { id: decodeURIComponent(id) } : {};
306
+ }
307
+ /**
308
+ * React to a message: `PUT …/messages/{id}/properties?name=emotions` with
309
+ * `{ emotions: { key, value: <epoch ms> } }` (captured live). Only the
310
+ * message's `emotions` property is written — never the user's
311
+ * `recentReactions` preference, which Teams updates as a UI nicety.
312
+ *
313
+ * A timeout, a dropped connection or a 5xx after the request was sent is a
314
+ * `WriteOutcomeUnknownError`, as for a post: the change may have landed.
315
+ * Repeating it is harmless (the same key twice is still one reaction), but
316
+ * the tool reads the message back rather than reporting a plain failure for
317
+ * a change that may well be visible already.
318
+ */
319
+ async setReaction(conversationId, messageId, key, at = Date.now()) {
320
+ await this.#writeEmotions('PUT', conversationId, messageId, { key, value: at });
321
+ }
322
+ /** Withdraw the user's reaction: `DELETE` on the same property (unverified live — see the plan). */
323
+ async removeReaction(conversationId, messageId, key) {
324
+ await this.#writeEmotions('DELETE', conversationId, messageId, { key });
325
+ }
326
+ async #writeEmotions(method, conversationId, messageId, emotions) {
327
+ this.#requireConfigured();
328
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
329
+ `/messages/${encodeURIComponent(messageId)}/properties?name=emotions`;
330
+ const { status } = await this.#send(url, 'text', undefined, { method, body: { emotions }, hint: REACTION_OUTCOME_HINT });
331
+ this.#checkWriteStatus(method, status, REACTION_OUTCOME_HINT);
332
+ }
333
+ /**
334
+ * Download an inline image (`<img src>` in a message body).
335
+ *
336
+ * The URL comes out of message content — i.e. it is attacker-influenced —
337
+ * so it is checked BEFORE a token is even resolved: https only, and a host
338
+ * under `.asm.skype.com`. Anything else would hand the user's bearer to
339
+ * whoever wrote the message.
340
+ */
341
+ async fetchImage(url) {
342
+ this.#requireConfigured();
343
+ let target;
344
+ try {
345
+ target = new URL(url);
346
+ }
347
+ catch {
348
+ throw new McpToolError('Refusing to fetch an image link that is not a URL.', {
349
+ hint: 'Pass an image ref exactly as a message listing returned it.',
350
+ });
351
+ }
352
+ if (target.protocol !== 'https:' || !target.hostname.endsWith(IMAGE_HOST_SUFFIX)) {
353
+ throw new McpToolError(`Refusing to fetch an image from ${target.protocol}//${target.hostname}.`, {
354
+ hint: `Only https images on *${IMAGE_HOST_SUFFIX} (Teams' own image store) are fetched.`,
355
+ });
356
+ }
357
+ const { status, headers, body } = await this.#send(target.toString(), 'bytes', MAX_IMAGE_BYTES);
358
+ this.#checkStatus(status);
359
+ const mimeType = (headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
360
+ return { mimeType, data: Buffer.from(body) };
361
+ }
362
+ #requireConfigured() {
363
+ if (this.#configError)
364
+ throw this.#configError;
365
+ }
366
+ #tokenManager() {
367
+ if (this.#tokens)
368
+ return this.#tokens;
369
+ const direct = this.#direct;
370
+ const persistence = direct === undefined ? createTokenCache(this.#env) : null;
371
+ const mint = async () => toBearerTokens(direct ?? (await this.#capture()));
372
+ this.#tokens = new TokenManager({
373
+ initial: mint,
374
+ // There is no refresh grant — re-capture instead. But a token supplied as
375
+ // TEAMS_ACCESS_TOKEN must NOT be "refreshed" from the browser: that would
376
+ // silently swap the operator's chosen credential for whichever account a
377
+ // tab is signed into.
378
+ refresh: async () => {
379
+ if (direct !== undefined)
380
+ throw this.#directRejected();
381
+ return toBearerTokens(await this.#capture());
382
+ },
383
+ // A failed cache write must not fail the call that triggered it.
384
+ ...(persistence
385
+ ? {
386
+ persistence: {
387
+ load: () => persistence.load(),
388
+ save: (t) => {
389
+ try {
390
+ persistence.save(t);
391
+ }
392
+ catch (e) {
393
+ reportCacheWriteFailure(e);
394
+ }
395
+ },
396
+ clear: () => {
397
+ try {
398
+ persistence.clear();
399
+ }
400
+ catch {
401
+ /* nothing useful to do; the next capture overwrites it */
402
+ }
403
+ },
404
+ },
405
+ }
406
+ : {}),
407
+ });
408
+ return this.#tokens;
409
+ }
410
+ #directRejected() {
411
+ return new McpToolError('TEAMS_ACCESS_TOKEN was rejected by Teams (401).', {
412
+ status: 401,
413
+ kind: 'credential_rejected',
414
+ hint: 'A directly-supplied token cannot be refreshed automatically. Replace ' +
415
+ 'TEAMS_ACCESS_TOKEN with a current one, or unset it to capture from a signed-in ' +
416
+ 'Teams browser tab instead.',
417
+ });
418
+ }
419
+ /**
420
+ * One authenticated GET. `TokenManager.withAuth` supplies the token and, on a
421
+ * 401, re-captures once and replays once — so a 401 that reaches the caller
422
+ * is the second one.
423
+ *
424
+ * The body is read as text/bytes rather than JSON so a 401's non-JSON body
425
+ * cannot throw inside the call and pre-empt that replay.
426
+ */
427
+ async #send(url, read, maxBytes,
428
+ /** A write: a lost answer is a `WriteOutcomeUnknownError` carrying `hint`. */
429
+ write) {
430
+ let body = '';
431
+ const method = write?.method ?? 'GET';
432
+ const res = await this.#tokenManager().withAuth(async (token) => {
433
+ const init = {
434
+ method,
435
+ headers: {
436
+ authorization: `Bearer ${token}`,
437
+ // Verified live: without it the service answers some failures with
438
+ // a redirect to a sign-in page instead of a status we can act on.
439
+ behavioroverride: 'redirectAs404',
440
+ accept: read === 'text' ? 'application/json' : '*/*',
441
+ ...(write ? { 'content-type': 'application/json' } : {}),
442
+ },
443
+ ...(write ? { body: JSON.stringify(write.body) } : {}),
444
+ // Never let a redirect carry the bearer somewhere we did not vet.
445
+ redirect: 'error',
446
+ };
447
+ const opts = { read, maxBytes, service: 'Teams', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl };
448
+ let r;
449
+ try {
450
+ r = await fetchBounded(url, init, opts);
451
+ }
452
+ catch (e) {
453
+ throw write ? outcomeUnknown(method, e, write.hint) : e;
454
+ }
455
+ body = r.body;
456
+ return r.res;
457
+ });
458
+ return { status: res.status, headers: res.headers, body };
459
+ }
460
+ async #getJson(url) {
461
+ const { status, body } = await this.#send(url, 'text');
462
+ return this.#parseJson(status, body);
463
+ }
464
+ #parseJson(status, body) {
465
+ this.#checkStatus(status);
466
+ try {
467
+ return JSON.parse(body);
468
+ }
469
+ catch {
470
+ // Never echo the body: it is the user's message content.
471
+ throw new McpToolError('Teams chat service returned a response that is not JSON.', {
472
+ status,
473
+ kind: 'http',
474
+ });
475
+ }
476
+ }
477
+ /**
478
+ * A write's status: a 5xx means the request reached Teams and failed
479
+ * somewhere past the front door — a gateway that lost the backend's answer
480
+ * (502/504) or a backend that may have committed before failing — so the
481
+ * outcome is unknown, never a plain "retry shortly". Anything else maps as
482
+ * for a read.
483
+ */
484
+ #checkWriteStatus(method, status, hint) {
485
+ if (status >= 500 && status < 600) {
486
+ throw new WriteOutcomeUnknownError('Teams', method, {
487
+ cause: new McpToolError(`Teams chat service returned HTTP ${status}.`, { status, kind: 'http' }),
488
+ hint,
489
+ });
490
+ }
491
+ this.#checkStatus(status);
492
+ }
493
+ /**
494
+ * Map a non-2xx to an `McpToolError` carrying its status. No retry loop: a
495
+ * 429 or 5xx is reported, and the model decides whether to try again. The
496
+ * body is never included — it may be message content.
497
+ */
498
+ #checkStatus(status) {
499
+ if (status >= 200 && status < 300)
500
+ return;
501
+ if (status === 401) {
502
+ if (this.#direct !== undefined)
503
+ throw this.#directRejected();
504
+ throw new McpToolError('Teams rejected the access token (401) even after a fresh capture.', {
505
+ status,
506
+ kind: 'credential_rejected',
507
+ hint: 'Re-open Teams in a signed-in teams.cloud.microsoft tab (sign in again if it ' +
508
+ 'asks), click into any chat, then retry.',
509
+ });
510
+ }
511
+ if (status === 429) {
512
+ throw new McpToolError('Teams chat service is rate-limiting requests (429).', {
513
+ status,
514
+ kind: 'http',
515
+ hint: 'Wait a minute before retrying.',
516
+ });
517
+ }
518
+ throw new McpToolError(`Teams chat service returned HTTP ${status}.`, {
519
+ status,
520
+ kind: 'http',
521
+ ...(status >= 500 ? { hint: 'A Teams-side failure; retry shortly.' } : {}),
522
+ });
523
+ }
524
+ /**
525
+ * The next (older) page's URL, re-rooted onto the configured base.
526
+ *
527
+ * The service hands back an absolute `backwardLink`. Rather than trust its
528
+ * origin with the bearer token, only its `/users/…` path and query are kept
529
+ * and requested against our own base — so a link naming another host (the
530
+ * service's internal one, or anything else) can never receive the token. A
531
+ * link with no `/v1/users/` path is refused outright.
532
+ */
533
+ #nextLink(page) {
534
+ const link = page._metadata?.backwardLink;
535
+ if (typeof link !== 'string' || link === '')
536
+ return undefined;
537
+ let target;
538
+ try {
539
+ target = new URL(link);
540
+ }
541
+ catch {
542
+ throw new McpToolError('Refusing to follow a Teams paging link that is not a URL.');
543
+ }
544
+ const at = target.pathname.indexOf('/v1/users/');
545
+ if (at < 0) {
546
+ throw new McpToolError(`Refusing to follow a Teams paging link to ${target.origin}${target.pathname}.`, {
547
+ hint: 'Paging links must be chat-service /v1/users/… paths.',
548
+ });
549
+ }
550
+ return `${this.#baseUrl}${target.pathname.slice(at + '/v1'.length)}${target.search}`;
551
+ }
552
+ }