@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.
@@ -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
+ }
@@ -0,0 +1,326 @@
1
+ /**
2
+ * The Microsoft Substrate search client — the backend Teams' own search box
3
+ * uses, and the primary path of `teams_search_messages` (the client-side
4
+ * chat-service scan in `tools/search.ts` is the fallback).
5
+ *
6
+ * POST https://substrate.office.com/searchservice/api/v2/query
7
+ * [Authorization: Bearer <token>, Content-Type: application/json]
8
+ * { entityRequests: [{ entityType: "Message", contentSources: ["Teams"],
9
+ * query: { queryString, displayQueryString }, from, size,
10
+ * sort: [{ Field: "Time", SortDirection: "Desc" }] }],
11
+ * cvid, logicalId, scenario: { Name: "powerbar", … } }
12
+ * → { EntitySets: [{ ResultSets: [{ Total, MoreResultsAvailable,
13
+ * Results: [{ HitHighlightedSummary, Source: {
14
+ * ClientThreadId, ClientConversationId, InternetMessageId,
15
+ * DateTimeSent, Sender: { EmailAddress: { Name, Address } },
16
+ * Preview, Subject, ChannelName, TeamName, … } }] }] }] }
17
+ *
18
+ * Verified live 2026-10-12 (token captured off the Teams tab, replayed from
19
+ * Node; read-only queries such as "deploy"; a redacted response is
20
+ * `tests/fixtures/substrate-query-response.json`):
21
+ * - No header beyond the bearer and the JSON content type is needed. The
22
+ * token `substrate-auth.ts` captures off `/searchservice/*` worked (an
23
+ * app-GUID audience, ~1.4h lifetime); so did one captured off another
24
+ * substrate.office.com path (audience `https://outlook.office.com/`).
25
+ * - Body: `cvid`/`logicalId` and `scenario.Name` are REQUIRED (400 without);
26
+ * the sort must be `Field: "Time"` with capitalised keys (`DateTime`, or
27
+ * `field`/`sortDirection`, is a 400). `size` up to 200 works; `from`
28
+ * pages without overlap, newest first.
29
+ * - Response: the Teams conversation is `Source.ClientThreadId`;
30
+ * `ClientConversationId` is the same plus `;messageid=<root>` for a
31
+ * channel post or reply. `InternetMessageId` is the Teams message id
32
+ * (equal to the root id on a root post). `Sender` (= `From`) carries a
33
+ * display name and an SMTP address — NO MRI, and the address need not be
34
+ * the token's UPN, so `fromMe` cannot be decided from a hit. `Preview`
35
+ * (= `HitHighlightedSummary`, no highlight markup) is PLAIN TEXT capped
36
+ * at ~255 characters; there is no body. `Subject` is set on a channel
37
+ * root post with a subject. A query with no hits has no `Results` key.
38
+ * `Total` is an estimate (one phrase query said 86 and paged to 11).
39
+ * - Matching is Substrate's: words ANDed with stemming ("deploy" matches
40
+ * "deployed", "deployment"), `"phrases"`, `OR`; not window-bound (all
41
+ * history unless restricted).
42
+ * - Server-side restrictions in the query string, ANDed with a
43
+ * parenthesised user query: `ClientThreadId:"<conversation id>"` (also
44
+ * for `48:notes`) and `sent>=<ISO date-time, UNQUOTED>` (a quoted value
45
+ * was mis-read). `from:<word>` exists but matches name/address word
46
+ * PREFIXES, not the "display name contains" the tool promises, so `from`
47
+ * stays client-side.
48
+ * - A bad token is a 401.
49
+ *
50
+ * As with the other clients, the bridge is touched only to capture the token
51
+ * (`substrate-auth.ts`); every request is a plain Node `fetch`.
52
+ */
53
+ import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
54
+ import { describeTransportFailure } from './network-error.js';
55
+ import { TokenManager } from '@chrischall/mcp-utils/session';
56
+ import { createSubstrateTokenCache } from './substrate-token-cache.js';
57
+ export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
58
+ /**
59
+ * How long after a failed capture (or a 401 on a freshly captured token) an
60
+ * unforced search skips straight to failing
61
+ * (so mode "auto" falls back to the scan at once) instead of holding the call
62
+ * for another capture window. Mode "substrate" forces a fresh attempt.
63
+ */
64
+ export const CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1000;
65
+ /** Fallback lifetime for a token whose `exp` we cannot read (as in `sharepoint.ts`). */
66
+ const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
67
+ /** Stands in for a refresh token this flow does not have (see `sharepoint.ts`). */
68
+ const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
69
+ /** Per-request deadline, covering the body read. */
70
+ const REQUEST_TIMEOUT_MS = 30_000;
71
+ /** A search response is a page of summaries; anything near this is not one. */
72
+ const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
73
+ function toBearerTokens(accessToken) {
74
+ let expiresAt;
75
+ try {
76
+ expiresAt = decodeJwtExp(accessToken) * 1000;
77
+ }
78
+ catch {
79
+ expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
80
+ }
81
+ return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
82
+ }
83
+ /** Capture lazily, so boot never loads the bridge (see `sharepoint.ts`). */
84
+ async function captureSubstrateTokenLazily() {
85
+ const mod = await import('./substrate-auth.js');
86
+ return mod.captureSubstrateTokenViaFetchproxy();
87
+ }
88
+ /** `sent>=` takes an unquoted ISO date-time (a quoted one was mis-read live); whole seconds, rounded down. */
89
+ function sentBound(ms) {
90
+ return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace(/\.000Z$/, 'Z');
91
+ }
92
+ /**
93
+ * The query string: the user's query, ANDed with the verified KQL-style
94
+ * property restrictions. With a restriction, the user's query is
95
+ * parenthesised so an `OR` in it cannot escape the filter (verified live).
96
+ */
97
+ export function buildQueryString(req) {
98
+ const filters = [];
99
+ if (req.conversationId !== undefined) {
100
+ if (/["\s]/.test(req.conversationId)) {
101
+ throw new McpToolError('That conversation id cannot be expressed as a Substrate filter.', { kind: 'unknown' });
102
+ }
103
+ filters.push(`ClientThreadId:"${req.conversationId}"`);
104
+ }
105
+ if (req.sentAfter !== undefined && Number.isFinite(req.sentAfter))
106
+ filters.push(`sent>=${sentBound(req.sentAfter)}`);
107
+ return filters.length === 0 ? req.query : [`(${req.query})`, ...filters].join(' ');
108
+ }
109
+ /**
110
+ * The query body, as verified live 2026-10-12. Required (400 without them):
111
+ * `cvid` + `logicalId`, and a `scenario` with a `Name`. `sort` must be
112
+ * `{ Field: "Time", SortDirection: "Desc" }` — `DateTime`, or lower-case keys,
113
+ * are a 400.
114
+ */
115
+ export function buildQueryBody(req) {
116
+ const cvid = crypto.randomUUID();
117
+ return {
118
+ entityRequests: [
119
+ {
120
+ entityType: 'Message',
121
+ contentSources: ['Teams'],
122
+ query: { queryString: buildQueryString(req), displayQueryString: req.query },
123
+ from: req.from,
124
+ size: req.size,
125
+ sort: [{ Field: 'Time', SortDirection: 'Desc' }],
126
+ },
127
+ ],
128
+ cvid,
129
+ logicalId: cvid,
130
+ scenario: {
131
+ Name: 'powerbar',
132
+ Dimensions: [
133
+ { DimensionName: 'QueryType', DimensionValue: 'Messages' },
134
+ { DimensionName: 'FormFactor', DimensionValue: 'general.web.reactSearch' },
135
+ ],
136
+ },
137
+ QueryAlterationOptions: { EnableSuggestion: false, EnableAlteration: false },
138
+ };
139
+ }
140
+ function obj(v) {
141
+ return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
142
+ }
143
+ function str(v) {
144
+ return typeof v === 'string' && v.trim() !== '' ? v : undefined;
145
+ }
146
+ function isoOf(v) {
147
+ const s = str(v);
148
+ if (s === undefined)
149
+ return undefined;
150
+ const ms = Date.parse(s);
151
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
152
+ }
153
+ function mapResult(raw) {
154
+ const r = obj(raw);
155
+ const source = obj(r?.Source);
156
+ if (r === undefined || source === undefined)
157
+ return undefined;
158
+ // `19:x@thread.tacv2;messageid=<root>` for a channel post or reply; the bare id for a chat.
159
+ const clientConv = str(source.ClientConversationId) ?? str(source.ClientThreadId);
160
+ if (clientConv === undefined)
161
+ return undefined;
162
+ const [conversationId, ...params] = clientConv.split(';');
163
+ if (str(conversationId) === undefined)
164
+ return undefined;
165
+ const root = params.map((p) => /^messageid=(.+)$/i.exec(p.trim())?.[1]).find((v) => v !== undefined);
166
+ const messageId = str(source.InternetMessageId);
167
+ // `Sender` and `From` were identical on every hit seen live.
168
+ const from = obj(obj(source.Sender)?.EmailAddress) ?? obj(obj(source.From)?.EmailAddress);
169
+ const text = str(source.Preview) ?? str(r.HitHighlightedSummary) ?? '';
170
+ const time = isoOf(source.DateTimeSent) ?? isoOf(source.DateTimeReceived) ?? isoOf(source.DateTimeCreated);
171
+ const sender = str(from?.Name);
172
+ const senderEmail = str(from?.Address);
173
+ const subject = str(source.Subject);
174
+ return {
175
+ conversationId,
176
+ ...(messageId !== undefined ? { messageId } : {}),
177
+ ...(time !== undefined ? { time } : {}),
178
+ ...(sender !== undefined ? { sender } : {}),
179
+ ...(senderEmail !== undefined ? { senderEmail } : {}),
180
+ text,
181
+ ...(subject !== undefined ? { subject } : {}),
182
+ ...(root !== undefined && root !== messageId ? { replyTo: root } : {}),
183
+ };
184
+ }
185
+ /** Parse a v2 query response into a page of message hits. Never throws on shape. */
186
+ export function parseQueryResponse(body) {
187
+ const sets = obj(body)?.EntitySets;
188
+ const firstSet = Array.isArray(sets) ? obj(sets[0]) : undefined;
189
+ const resultSets = firstSet?.ResultSets;
190
+ const rs = Array.isArray(resultSets) ? obj(resultSets[0]) : undefined;
191
+ if (rs === undefined)
192
+ return { results: [], moreAvailable: false, unmapped: 0 };
193
+ // A query with no hits has no `Results` key at all (seen live).
194
+ const raw = Array.isArray(rs.Results) ? rs.Results : [];
195
+ const results = [];
196
+ let unmapped = 0;
197
+ for (const r of raw) {
198
+ const m = mapResult(r);
199
+ if (m === undefined)
200
+ unmapped++;
201
+ else
202
+ results.push(m);
203
+ }
204
+ return {
205
+ results,
206
+ ...(typeof rs.Total === 'number' ? { total: rs.Total } : {}),
207
+ moreAvailable: rs.MoreResultsAvailable === true,
208
+ unmapped,
209
+ };
210
+ }
211
+ export class SubstrateClient {
212
+ #fetchImpl;
213
+ #configError = null;
214
+ #manager;
215
+ /**
216
+ * When the last capture failed, or a freshly captured token was still
217
+ * refused (401), and how; cleared by a successful capture.
218
+ */
219
+ #captureFailure = null;
220
+ constructor(opts = {}) {
221
+ const env = opts.env ?? process.env;
222
+ const capture = opts.captureToken ?? captureSubstrateTokenLazily;
223
+ // A receiver-safe wrapper, never the bare global (see `sharepoint.ts`).
224
+ this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
225
+ const recapture = async () => {
226
+ try {
227
+ const tokens = toBearerTokens(await capture());
228
+ this.#captureFailure = null;
229
+ return tokens;
230
+ }
231
+ catch (error) {
232
+ this.#captureFailure = { at: Date.now(), error };
233
+ throw error;
234
+ }
235
+ };
236
+ const persistence = createSubstrateTokenCache(env);
237
+ this.#manager = new TokenManager({
238
+ initial: recapture,
239
+ refresh: recapture,
240
+ ...(persistence ? { persistence } : {}),
241
+ });
242
+ // Like SharePoint, there is no direct-token env var: the bridge is the only source.
243
+ if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env })) {
244
+ this.#configError = new McpToolError('Substrate search is disabled (no token source).', {
245
+ kind: 'no_credential',
246
+ hint: 'Unset TEAMS_DISABLE_FETCHPROXY so a Substrate token can be captured from a signed-in Teams tab.',
247
+ });
248
+ }
249
+ }
250
+ /** Whether a token could be obtained at all (the bridge is not disabled). */
251
+ isConfigured() {
252
+ return this.#configError === null;
253
+ }
254
+ async searchMessages(req, opts = {}) {
255
+ if (this.#configError)
256
+ throw this.#configError;
257
+ const failed = this.#captureFailure;
258
+ if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
259
+ throw failed.error;
260
+ let text = '';
261
+ const res = await this.#manager.withAuth(async (token) => {
262
+ let r;
263
+ try {
264
+ r = await fetchBounded(SUBSTRATE_QUERY_URL, {
265
+ method: 'POST',
266
+ headers: {
267
+ authorization: `Bearer ${token}`,
268
+ 'content-type': 'application/json',
269
+ accept: 'application/json',
270
+ },
271
+ body: JSON.stringify(buildQueryBody(req)),
272
+ redirect: 'error',
273
+ }, {
274
+ read: 'text',
275
+ maxBytes: MAX_RESPONSE_BYTES,
276
+ service: 'Substrate',
277
+ timeoutMs: REQUEST_TIMEOUT_MS,
278
+ fetchImpl: this.#fetchImpl,
279
+ });
280
+ }
281
+ catch (e) {
282
+ throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, 'Substrate search') ?? e;
283
+ }
284
+ text = r.body;
285
+ return r.res;
286
+ });
287
+ try {
288
+ checkStatus(res.status);
289
+ }
290
+ catch (error) {
291
+ // A 401 here is on a token `withAuth` just re-captured: the capture itself
292
+ // is not yielding a usable token. Cool down like a failed capture, so each
293
+ // unforced search does not hold the call for another capture window.
294
+ if (res.status === 401)
295
+ this.#captureFailure = { at: Date.now(), error };
296
+ throw error;
297
+ }
298
+ try {
299
+ return parseQueryResponse(JSON.parse(text));
300
+ }
301
+ catch {
302
+ // Never echo the body: it holds message content.
303
+ throw new McpToolError('Substrate returned a response that is not JSON.', { status: res.status, kind: 'http' });
304
+ }
305
+ }
306
+ }
307
+ /** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
308
+ function checkStatus(status) {
309
+ if (status >= 200 && status < 300)
310
+ return;
311
+ if (status === 401) {
312
+ throw new McpToolError('Substrate rejected the search token (401) even after a fresh capture.', {
313
+ status,
314
+ kind: 'credential_rejected',
315
+ hint: 'Run a search in a signed-in Teams tab to mint a fresh Substrate token, then retry.',
316
+ });
317
+ }
318
+ if (status === 429) {
319
+ throw new McpToolError('Substrate is rate-limiting searches (429).', { status, kind: 'http', hint: 'Wait a minute before retrying.' });
320
+ }
321
+ throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
322
+ status,
323
+ kind: 'http',
324
+ ...(status >= 500 ? { hint: 'A Substrate-side failure; retry shortly.' } : {}),
325
+ });
326
+ }
@@ -167,6 +167,11 @@ function degradeHint(err, host) {
167
167
  if (errorKindOf(err) === 'no_credential') {
168
168
  return 'SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.';
169
169
  }
170
+ // A network failure is about this machine's route to the host, not the token:
171
+ // say which host and why, never "open the file once in Teams".
172
+ if (errorKindOf(err) === 'transport' && err instanceof McpToolError) {
173
+ return err.hint !== undefined ? `${err.message} ${err.hint}` : err.message;
174
+ }
170
175
  if (err instanceof McpToolError && err.hint !== undefined)
171
176
  return err.hint;
172
177
  return (`Couldn't mint a SharePoint token for ${host} — open the shared file once in a signed-in Teams ` +