@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.1

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,20 +8,22 @@
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
19
20
  * response shapes the types below describe.
20
21
  */
21
- import { decodeJwtClaim, decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
22
+ import { decodeJwtClaim, decodeJwtExp, fetchBounded, errorKindOf, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
22
23
  import { TokenManager } from '@chrischall/mcp-utils/session';
23
24
  import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
24
25
  import { SELF_CHAT } from './model.js';
26
+ import { describeTransportFailure } from './network-error.js';
25
27
  /**
26
28
  * Load the bridge bootstrap lazily.
27
29
  *
@@ -78,6 +80,29 @@ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
78
80
  * host varies by region). The bearer is sent ONLY to hosts under this suffix.
79
81
  */
80
82
  const IMAGE_HOST_SUFFIX = '.asm.skype.com';
83
+ /**
84
+ * The Teams gateway in front of the same image store. Verified live
85
+ * 2026-10-12: `GET https://us-prod.asyncgw.teams.microsoft.com/v1/objects/<id>/views/imgo`
86
+ * with the chat-service bearer returns the identical bytes for objects of
87
+ * either region (`0-sin-…` and `0-eus-…`). Some networks reset every
88
+ * connection to `*.asm.skype.com` while allowing teams.microsoft.com, so an
89
+ * image the store cannot be REACHED at is retried here — never one the store
90
+ * answered. Only ever reached by rewriting a vetted `*.asm.skype.com` URL,
91
+ * never from a URL in message content.
92
+ */
93
+ const IMAGE_GATEWAY_HOST = 'us-prod.asyncgw.teams.microsoft.com';
94
+ /** What a transport failure calls the far side: the image store, or the chat service. */
95
+ function serviceFor(url) {
96
+ try {
97
+ const host = new URL(url).hostname;
98
+ if (host.endsWith(IMAGE_HOST_SUFFIX))
99
+ return "Teams' image store";
100
+ return host === IMAGE_GATEWAY_HOST ? 'the Teams image gateway' : 'the Teams chat service';
101
+ }
102
+ catch {
103
+ return 'the Teams chat service';
104
+ }
105
+ }
81
106
  /**
82
107
  * A write that failed after it may have reached Teams. A timeout or a
83
108
  * transport failure (dropped connection, broken body, the caller cancelling)
@@ -94,6 +119,8 @@ function outcomeUnknown(method, e, hint) {
94
119
  }
95
120
  const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_read_conversation) before retrying; do not resend blindly.';
96
121
  const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_read_conversation) before retrying.';
122
+ const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_read_conversation) before retrying; ' +
123
+ 'moving it again to the same message is harmless.';
97
124
  /**
98
125
  * The HTTP status behind a {@link WriteOutcomeUnknownError} that Teams
99
126
  * answered with a 5xx, or `undefined` when it timed out or the connection
@@ -271,8 +298,12 @@ export class ChatServiceClient {
271
298
  return out;
272
299
  }
273
300
  /**
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.
301
+ * One message by id, or `undefined` when the service answers 404. Used to
302
+ * quote a message (its sender and text go into the quote) and to fill in a
303
+ * channel thread's root post when it is older than a read's window — a
304
+ * channel root fetched by its id answers like any message (verified live
305
+ * 2026-10-12). An id the channel does not hold was answered 403, not 404,
306
+ * live, so that surfaces as an error.
276
307
  */
277
308
  async getMessage(conversationId, messageId) {
278
309
  this.#requireConfigured();
@@ -330,6 +361,27 @@ export class ChatServiceClient {
330
361
  const { status } = await this.#send(url, 'text', undefined, { method, body: { emotions }, hint: REACTION_OUTCOME_HINT });
331
362
  this.#checkWriteStatus(method, status, REACTION_OUTCOME_HINT);
332
363
  }
364
+ /**
365
+ * Move the user's read marker in a conversation to `messageId`:
366
+ * `PUT …/conversations/{id}/properties?name=consumptionhorizon` with
367
+ * `{ consumptionhorizon: "<id>;<client ms>;<id>" }` — the shape `readHorizon`
368
+ * parses, its first segment the message's arrival ms (which is its id).
369
+ * Teams clears the unread badge for everything up to it.
370
+ *
371
+ * Verified live 2026-10-12 on `48:notes`: 200, and the listing then carries
372
+ * the new horizon. A move BACKWARDS is also answered 200 but ignored, so a
373
+ * 200 does not prove the marker moved; never sending one is the caller's
374
+ * rule (`teams_mark_read`), which reports it as a no-op instead. A lost
375
+ * answer is a `WriteOutcomeUnknownError`, as for a reaction.
376
+ */
377
+ async setConsumptionHorizon(conversationId, messageId, at = Date.now()) {
378
+ this.#requireConfigured();
379
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
380
+ '/properties?name=consumptionhorizon';
381
+ const body = { consumptionhorizon: `${messageId};${at};${messageId}` };
382
+ const { status } = await this.#send(url, 'text', undefined, { method: 'PUT', body, hint: HORIZON_OUTCOME_HINT });
383
+ this.#checkWriteStatus('PUT', status, HORIZON_OUTCOME_HINT);
384
+ }
333
385
  /**
334
386
  * Download an inline image (`<img src>` in a message body).
335
387
  *
@@ -354,6 +406,24 @@ export class ChatServiceClient {
354
406
  hint: `Only https images on *${IMAGE_HOST_SUFFIX} (Teams' own image store) are fetched.`,
355
407
  });
356
408
  }
409
+ try {
410
+ return await this.#getImage(target);
411
+ }
412
+ catch (e) {
413
+ if (errorKindOf(e) !== 'transport')
414
+ throw e;
415
+ const viaGateway = new URL(target.pathname + target.search, `https://${IMAGE_GATEWAY_HOST}`);
416
+ try {
417
+ return await this.#getImage(viaGateway);
418
+ }
419
+ catch (e2) {
420
+ if (errorKindOf(e2) !== 'transport')
421
+ throw e2;
422
+ throw new McpToolError(`${e.message} The Teams gateway was tried too: ${e2.message}`, { kind: 'transport', hint: e.hint, cause: e });
423
+ }
424
+ }
425
+ }
426
+ async #getImage(target) {
357
427
  const { status, headers, body } = await this.#send(target.toString(), 'bytes', MAX_IMAGE_BYTES);
358
428
  this.#checkStatus(status);
359
429
  const mimeType = (headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
@@ -450,7 +520,9 @@ export class ChatServiceClient {
450
520
  r = await fetchBounded(url, init, opts);
451
521
  }
452
522
  catch (e) {
453
- throw write ? outcomeUnknown(method, e, write.hint) : e;
523
+ if (write)
524
+ throw outcomeUnknown(method, e, write.hint);
525
+ throw describeTransportFailure(e, url, serviceFor(url)) ?? e;
454
526
  }
455
527
  body = r.body;
456
528
  return r.res;
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,124 @@
1
+ /**
2
+ * A request that never got a response, said in a way someone can act on.
3
+ *
4
+ * Node's `fetch` (undici) reports every transport failure — DNS, a refused or
5
+ * reset connection, a TLS certificate it will not trust — as the same
6
+ * `TypeError('fetch failed')`, with the real reason on its `cause` chain.
7
+ * Surfaced as is, that reads "Failed to get the attachment: fetch failed",
8
+ * which names neither the host nor the reason (2026-10-12: two inline images
9
+ * on `in-api`/`us-api.asm.skype.com` failed that way on a machine whose
10
+ * chat-service calls to `teams.cloud.microsoft` were fine, while the same refs
11
+ * downloaded on another machine). This turns it into an `McpToolError` naming
12
+ * the HOST — never the path or query, which may carry ids — the cause's code,
13
+ * and a hint keyed to that code.
14
+ */
15
+ import { McpToolError } from '@chrischall/mcp-utils';
16
+ /** How far down a cause chain (and into an AggregateError) to look for a code. */
17
+ const MAX_CAUSE_DEPTH = 5;
18
+ const DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NONAME']);
19
+ const CONNECT_CODES = new Set([
20
+ 'ECONNREFUSED',
21
+ 'ECONNRESET',
22
+ 'ETIMEDOUT',
23
+ 'ENETUNREACH',
24
+ 'EHOSTUNREACH',
25
+ 'EPIPE',
26
+ 'UND_ERR_CONNECT_TIMEOUT',
27
+ 'UND_ERR_SOCKET',
28
+ 'UND_ERR_HEADERS_TIMEOUT',
29
+ ]);
30
+ const CERT_CODES = new Set([
31
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
32
+ 'UNABLE_TO_GET_ISSUER_CERT',
33
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
34
+ 'SELF_SIGNED_CERT_IN_CHAIN',
35
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
36
+ 'CERT_HAS_EXPIRED',
37
+ 'CERT_NOT_YET_VALID',
38
+ 'ERR_TLS_CERT_ALTNAME_INVALID',
39
+ ]);
40
+ function codeOf(e) {
41
+ if (e === null || typeof e !== 'object')
42
+ return undefined;
43
+ const code = e.code;
44
+ return typeof code === 'string' && code !== '' ? code : undefined;
45
+ }
46
+ /** The causes to look at, nearest first: the cause chain, and an AggregateError's members. */
47
+ function causes(err) {
48
+ const out = [];
49
+ let at = err;
50
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== undefined && at !== null; depth++) {
51
+ out.push(at);
52
+ if (at instanceof AggregateError)
53
+ out.push(...at.errors);
54
+ at = at.cause;
55
+ }
56
+ return out;
57
+ }
58
+ /** The first system/undici error code on `err`'s cause chain. */
59
+ export function transportCauseCode(err) {
60
+ for (const e of causes(err)) {
61
+ const code = codeOf(e);
62
+ if (code !== undefined)
63
+ return code;
64
+ }
65
+ return undefined;
66
+ }
67
+ /** The innermost cause's message, which is where undici puts the real reason. */
68
+ function causeMessage(err) {
69
+ const chain = causes(err).slice(1);
70
+ for (let i = chain.length - 1; i >= 0; i--) {
71
+ const e = chain[i];
72
+ if (e instanceof Error && e.message !== '')
73
+ return e.message;
74
+ }
75
+ return undefined;
76
+ }
77
+ /** Whether `err` is `fetch`'s "never got a response" failure. */
78
+ function isFetchFailed(err) {
79
+ return err instanceof TypeError && err.message === 'fetch failed';
80
+ }
81
+ function hintFor(code, host) {
82
+ if (code !== undefined && DNS_CODES.has(code)) {
83
+ return (`This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves ` +
84
+ 'teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts ' +
85
+ `fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`);
86
+ }
87
+ if (code !== undefined && CERT_CODES.has(code)) {
88
+ return (`Node did not trust the TLS certificate ${host} presented. On a corporate network this is ` +
89
+ 'usually TLS inspection: export your proxy\'s root CA as PEM and start this server with ' +
90
+ 'NODE_EXTRA_CA_CERTS=/path/to/ca.pem (Node does not read the system keychain). If the ' +
91
+ 'certificate is expired or not yet valid, also check the machine\'s clock.');
92
+ }
93
+ if (code !== undefined && CONNECT_CODES.has(code)) {
94
+ return (`The connection to ${host} was refused, reset or timed out before Teams answered — usually a ` +
95
+ 'firewall, or a network that only lets traffic out through a proxy. Node\'s fetch ignores ' +
96
+ 'proxy settings unless told: start this server with HTTPS_PROXY=<your proxy URL> and ' +
97
+ 'NODE_USE_ENV_PROXY=1 (Node 22.21+ / 24.5+), or allow the host through the firewall.');
98
+ }
99
+ return (`No response from ${host}. Check this machine can reach it (VPN, proxy, firewall); ` +
100
+ `\`curl -sI https://${host}/\` from the same machine is a quick test.`);
101
+ }
102
+ /**
103
+ * An `McpToolError` describing `err` when it is `fetch`'s transport failure
104
+ * for `url`, else `undefined` (the caller rethrows `err` as it was).
105
+ */
106
+ export function describeTransportFailure(err, url, service) {
107
+ if (!isFetchFailed(err))
108
+ return undefined;
109
+ let host;
110
+ try {
111
+ host = new URL(url).hostname;
112
+ }
113
+ catch {
114
+ host = '(unknown host)';
115
+ }
116
+ const code = transportCauseCode(err);
117
+ const detail = [code, causeMessage(err)].filter((s) => s !== undefined);
118
+ const why = detail.length > 0 ? ` (${[...new Set(detail)].join(': ')})` : '';
119
+ return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
120
+ kind: 'transport',
121
+ hint: hintFor(code, host),
122
+ cause: err,
123
+ });
124
+ }
@@ -23,6 +23,7 @@
23
23
  * `fetch` — the bridge is only ever touched to capture the token.
24
24
  */
25
25
  import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
26
+ import { describeTransportFailure } from './network-error.js';
26
27
  import { TokenManager } from '@chrischall/mcp-utils/session';
27
28
  import { createSharePointTokenCache } from './sharepoint-token-cache.js';
28
29
  /**
@@ -53,6 +54,15 @@ const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
53
54
  const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
54
55
  /** Per-request deadline, covering the body read. */
55
56
  const REQUEST_TIMEOUT_MS = 60_000;
57
+ /** Run one fetch, turning "never got a response" into an error naming the host and cause. */
58
+ async function reachable(url, run) {
59
+ try {
60
+ return await run();
61
+ }
62
+ catch (e) {
63
+ throw describeTransportFailure(e, url, 'SharePoint') ?? e;
64
+ }
65
+ }
56
66
  /** Copied faithfully from `chatsvc.ts`: a captured token as `TokenManager` input. */
57
67
  function toBearerTokens(accessToken) {
58
68
  let expiresAt;
@@ -195,7 +205,7 @@ export class SharePointClient {
195
205
  async #getDriveItem(captureHost, url) {
196
206
  let body = '';
197
207
  const res = await this.#managerFor(captureHost).withAuth(async (token) => {
198
- const r = await fetchBounded(url, {
208
+ const r = await reachable(url, () => fetchBounded(url, {
199
209
  method: 'GET',
200
210
  headers: {
201
211
  authorization: `Bearer ${token}`,
@@ -203,7 +213,7 @@ export class SharePointClient {
203
213
  behavioroverride: 'redirectAs404',
204
214
  },
205
215
  redirect: 'error',
206
- }, { read: 'text', service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
216
+ }, { read: 'text', service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl }));
207
217
  body = r.body;
208
218
  return r.res;
209
219
  });
@@ -246,7 +256,7 @@ export class SharePointClient {
246
256
  hint: 'SharePoint download links are expected to be https.',
247
257
  });
248
258
  }
249
- const r = await fetchBounded(target.toString(), { method: 'GET', headers: { accept: '*/*' }, redirect: 'follow' }, { read: 'bytes', maxBytes, service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
259
+ const r = await reachable(target.toString(), () => fetchBounded(target.toString(), { method: 'GET', headers: { accept: '*/*' }, redirect: 'follow' }, { read: 'bytes', maxBytes, service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl }));
250
260
  this.#checkStatus(r.status);
251
261
  const mimeType = (r.headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
252
262
  const data = Buffer.from(r.body);