@chrischall/microsoft-teams-mcp 0.14.0 → 0.15.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 (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +241 -33
  4. package/dist/attachments.js +238 -0
  5. package/dist/auth-fetchproxy.js +7 -6
  6. package/dist/browser-open.js +138 -0
  7. package/dist/bundle.js +6840 -3949
  8. package/dist/capture-feedback.js +283 -0
  9. package/dist/chatsvc.js +132 -7
  10. package/dist/compose.js +9 -1
  11. package/dist/file-upload.js +335 -0
  12. package/dist/index.js +11 -1
  13. package/dist/model.js +1 -0
  14. package/dist/presence.js +120 -0
  15. package/dist/profile.js +182 -0
  16. package/dist/recap-auth.js +6 -4
  17. package/dist/recap.js +3 -1
  18. package/dist/sender-email.js +147 -0
  19. package/dist/sharepoint-auth.js +42 -21
  20. package/dist/sharepoint.js +150 -3
  21. package/dist/substrate-auth.js +8 -7
  22. package/dist/substrate.js +98 -4
  23. package/dist/tools/attach.js +167 -0
  24. package/dist/tools/attachment.js +3 -1
  25. package/dist/tools/conversation.js +14 -5
  26. package/dist/tools/edit.js +42 -14
  27. package/dist/tools/errors.js +10 -11
  28. package/dist/tools/export.js +30 -3
  29. package/dist/tools/format.js +29 -6
  30. package/dist/tools/group-chat.js +349 -33
  31. package/dist/tools/healthcheck.js +23 -9
  32. package/dist/tools/mention-check.js +225 -0
  33. package/dist/tools/people.js +149 -39
  34. package/dist/tools/profile.js +67 -0
  35. package/dist/tools/send.js +134 -37
  36. package/dist/tools/sender-email-arg.js +37 -0
  37. package/dist/tools/token-status.js +97 -0
  38. package/dist/tools/unread.js +3 -2
  39. package/dist/tools/upload-slots.js +51 -0
  40. package/dist/version.js +1 -1
  41. package/mint.yaml +19 -0
  42. package/package.json +4 -1
  43. package/server.json +30 -2
  44. package/skills/teams-fpx/references/teams-env.sh +1 -1
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Profile-card lookup for `teams_get_profile`: who a person is — name, MRI,
3
+ * email, chat address, job title, department, office, city, company and
4
+ * manager — as the Teams profile card shows it.
5
+ *
6
+ * Source: the Substrate people suggestions the Teams search box (and the
7
+ * group-chat member tools, `tools/people.ts`) already use, through the token
8
+ * `substrate-auth.ts` already captures — no new token and no new bridge scope.
9
+ * Teams' own card reads its extended fields (manager, city, LinkedIn) from
10
+ * the Loki/Delve profile service, which needs a token for another audience on
11
+ * another host (`*.loki.delve.office.com`) and so a new capture declaration
12
+ * and a bridge re-pair; this lookup deliberately stays on the existing token
13
+ * and reads what the suggestion carries. Fields it does not carry are simply
14
+ * absent (see `substrate.ts`: `OfficeLocation` and `ImAddress` were in the
15
+ * live sample; `CompanyName`, `City` and `Manager` are read when present).
16
+ *
17
+ * A person is matched, never guessed:
18
+ * - an MRI (`8:orgid:<oid>`) or bare oid — the suggestion with that MRI, the
19
+ * directory asked by the oid, then (if that finds no one) by the name the
20
+ * user's chats know them by;
21
+ * - an address (has an `@`) — the suggestion whose email, UPN or chat
22
+ * address equals it, ignoring case;
23
+ * - a name — the one suggestion whose name equals it ("Last, First" and
24
+ * "First Last" compare equal), or the only suggestion when the name is a
25
+ * run of its whole words. Several, or several near matches, come back as
26
+ * candidates.
27
+ */
28
+ import { mapWithConcurrency, McpToolError } from '@chrischall/mcp-utils';
29
+ import { normaliseName, personMri } from './tools/people.js';
30
+ /** People one call may look up. */
31
+ export const MAX_PROFILES = 50;
32
+ /** Candidates an ambiguous lookup lists. */
33
+ const MAX_CANDIDATES = 10;
34
+ /** Suggestions asked for: enough to see that a surname is shared. */
35
+ const SUGGESTIONS = 25;
36
+ /** Directory lookups run at once after the first. */
37
+ const LOOKUP_CONCURRENCY = 4;
38
+ export function cardOf(p) {
39
+ const chatAddress = p.chatAddress ?? p.upn;
40
+ return {
41
+ displayName: p.name,
42
+ mri: p.mri,
43
+ ...(p.email !== undefined ? { email: p.email } : {}),
44
+ ...(chatAddress !== undefined ? { chatAddress } : {}),
45
+ ...(p.jobTitle !== undefined ? { jobTitle: p.jobTitle } : {}),
46
+ ...(p.department !== undefined ? { department: p.department } : {}),
47
+ ...(p.officeLocation !== undefined ? { officeLocation: p.officeLocation } : {}),
48
+ ...(p.city !== undefined ? { city: p.city } : {}),
49
+ ...(p.company !== undefined ? { company: p.company } : {}),
50
+ ...(p.manager !== undefined ? { manager: p.manager } : {}),
51
+ };
52
+ }
53
+ function kindOf(query) {
54
+ const mri = personMri(query);
55
+ if (mri !== undefined)
56
+ return { kind: 'mri', mri };
57
+ if (/^[^@\s]+@[^@\s]+$/.test(query.trim()))
58
+ return { kind: 'address' };
59
+ return { kind: 'name' };
60
+ }
61
+ /** The key two queries share when they must mean the same person. */
62
+ function keyOf(query) {
63
+ const { kind, mri } = kindOf(query);
64
+ if (kind === 'mri')
65
+ return `mri:${mri.toLowerCase()}`;
66
+ if (kind === 'address')
67
+ return `@${query.trim().toLowerCase()}`;
68
+ return `name:${normaliseName(query)}`;
69
+ }
70
+ const PASS_ADDRESS = 'Pass their email address or MRI (8:orgid:…) to pick one.';
71
+ function ambiguous(query, people) {
72
+ return { query, status: 'ambiguous', candidates: people.slice(0, MAX_CANDIDATES).map(cardOf), hint: PASS_ADDRESS };
73
+ }
74
+ function found(query, p) {
75
+ return { query, status: 'found', profile: cardOf(p) };
76
+ }
77
+ function byAddress(query, people) {
78
+ const want = query.trim().toLowerCase();
79
+ const hits = people.filter((p) => [p.email, p.upn, p.chatAddress].some((a) => a?.toLowerCase() === want));
80
+ if (hits.length === 1)
81
+ return found(query, hits[0]);
82
+ if (hits.length > 1)
83
+ return ambiguous(query, hits);
84
+ return {
85
+ query,
86
+ status: 'not_found',
87
+ hint: "No one in your organisation's directory has that address. Check it, or pass the person's name or MRI " +
88
+ '(only people in your organisation, not distribution lists or personal contacts, are found).',
89
+ };
90
+ }
91
+ function byName(query, people) {
92
+ const q = normaliseName(query);
93
+ const exact = people.filter((p) => normaliseName(p.name) === q);
94
+ if (exact.length === 1)
95
+ return found(query, exact[0]);
96
+ if (exact.length > 1)
97
+ return ambiguous(query, exact);
98
+ if (people.length === 1 && ` ${normaliseName(people[0].name)} `.includes(` ${q} `))
99
+ return found(query, people[0]);
100
+ if (people.length > 0)
101
+ return ambiguous(query, people);
102
+ return {
103
+ query,
104
+ status: 'not_found',
105
+ hint: "No one in your organisation's directory is called that. Try their surname alone, or their email address.",
106
+ };
107
+ }
108
+ function withMri(people, mri) {
109
+ const want = mri.toLowerCase();
110
+ return people.find((p) => p.mri.toLowerCase() === want);
111
+ }
112
+ async function byMri(query, mri, ask, opts) {
113
+ const id = mri.replace(/^8:orgid:/i, '');
114
+ const direct = withMri(await ask(id), mri);
115
+ if (direct !== undefined)
116
+ return found(query, direct);
117
+ const name = await opts.nameForMri?.(mri);
118
+ if (name !== undefined && name.trim() !== '') {
119
+ const viaName = withMri(await ask(name), mri);
120
+ if (viaName !== undefined)
121
+ return found(query, viaName);
122
+ }
123
+ return {
124
+ query,
125
+ status: 'not_found',
126
+ hint: "No directory entry with that MRI was found. Pass the person's email address or name instead.",
127
+ };
128
+ }
129
+ /**
130
+ * A failed directory as the lookup's failure: its message and kind kept, its
131
+ * own remedy if it has one, else how to let this server capture the token —
132
+ * as the group-chat member tools word it.
133
+ */
134
+ export function directoryFailed(err) {
135
+ const message = err instanceof Error ? err.message : String(err);
136
+ const own = err instanceof McpToolError ? err.hint : undefined;
137
+ return new McpToolError(`Could not look up profiles because the directory could not be searched: ${message}`, {
138
+ hint: own ??
139
+ 'Run any search in the Teams search box of a signed-in Teams tab while retrying (that is what lets this ' +
140
+ 'server capture the token it searches the directory with).',
141
+ ...(err instanceof McpToolError && err.kind !== undefined ? { kind: err.kind } : {}),
142
+ cause: err,
143
+ });
144
+ }
145
+ /**
146
+ * Each query's result, in order. The directory is asked once per distinct
147
+ * person: the first alone and forced (so a retry after running a Teams search
148
+ * really re-captures), and if THAT fails the whole lookup fails with
149
+ * {@link directoryFailed}; the rest a few at a time, a failure then reported
150
+ * on that person alone.
151
+ */
152
+ export async function lookupProfiles(queries, directory, opts = {}) {
153
+ const distinct = [...new Map(queries.map((q) => [keyOf(q), q])).entries()];
154
+ const results = new Map();
155
+ const one = async (query, force) => {
156
+ const ask = (text) => directory.suggestPeople(text, { size: SUGGESTIONS, force });
157
+ const { kind, mri } = kindOf(query);
158
+ if (kind === 'mri')
159
+ return byMri(query, mri, ask, opts);
160
+ const people = await ask(query.trim());
161
+ return kind === 'address' ? byAddress(query, people) : byName(query, people);
162
+ };
163
+ const [first, ...rest] = distinct;
164
+ if (first !== undefined) {
165
+ try {
166
+ results.set(first[0], await one(first[1], true));
167
+ }
168
+ catch (err) {
169
+ throw directoryFailed(err);
170
+ }
171
+ }
172
+ await mapWithConcurrency(rest, LOOKUP_CONCURRENCY, async ([key, query]) => {
173
+ try {
174
+ results.set(key, await one(query, false));
175
+ }
176
+ catch (err) {
177
+ const e = directoryFailed(err);
178
+ results.set(key, { query, status: 'error', error: e.message, ...(e.hint !== undefined ? { hint: e.hint } : {}) });
179
+ }
180
+ });
181
+ return queries.map((query) => ({ ...results.get(keyOf(query)), query }));
182
+ }
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
20
20
  import { captureWindowMs } from './capture-window.js';
21
+ import { whileWaitingGuidance } from './capture-feedback.js';
21
22
  import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
22
23
  import { BRIDGE_TRUST_DOMAINS, RECAP_CAPTURE_DECL } from './bridge-scope.js';
23
24
  import { PACKAGE_NAME, VERSION } from './version.js';
@@ -27,18 +28,19 @@ export { RECAP_CAPTURE_DECL } from './bridge-scope.js';
27
28
  * Returns the bare token (no `Bearer ` prefix).
28
29
  */
29
30
  export async function captureRecapTokenViaFetchproxy(env = process.env) {
31
+ const windowMs = captureWindowMs(env);
30
32
  return captureBearerHeader({
31
33
  // The one bridge scope every capture of this server declares (`bridge-scope.ts`).
32
34
  captures: [{ ...RECAP_CAPTURE_DECL }],
33
35
  domains: [...BRIDGE_TRUST_DOMAINS],
34
- windowMs: captureWindowMs(env),
36
+ windowMs,
35
37
  port: getWsPort(),
36
38
  serverName: PACKAGE_NAME,
37
39
  version: VERSION,
38
40
  what: 'a Teams meeting-recap token',
39
- guidance: "In a signed-in teams.cloud.microsoft tab, open any meeting chat and click its Recap tab — that is what " +
40
- 'makes Teams call its meeting-recap service, where the token is read from — then retry. If the ContextMint ' +
41
- 'Bridge asks to re-pair microsoft-teams-mcp, approve it once: the recap capture is new to its scope.',
41
+ // The click has to happen WHILE the capture waits: see `capture-feedback.ts`.
42
+ guidance: whileWaitingGuidance('recap', windowMs) +
43
+ ' If the ContextMint Bridge asks to re-pair microsoft-teams-mcp, approve it once: the recap capture is new to its scope.',
42
44
  createTransport: bridgeScopedTransport(env),
43
45
  });
44
46
  }
package/dist/recap.js CHANGED
@@ -40,6 +40,8 @@
40
40
  import { fetchBounded, McpToolError, parseBoolEnv, readEnvVar } from '@chrischall/mcp-utils';
41
41
  import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
42
42
  import { describeTransportFailure } from './network-error.js';
43
+ import { whileWaitingGuidance } from './capture-feedback.js';
44
+ import { captureWindowMs } from './capture-window.js';
43
45
  import { createRecapTokenCache } from './recap-token-cache.js';
44
46
  /** The MCPS region this tenant was verified on. */
45
47
  export const DEFAULT_MCPS_REGION = 'us';
@@ -304,7 +306,7 @@ function checkStatus(status) {
304
306
  throw new McpToolError('The Teams meeting-recap service rejected the recap token (401) even after a fresh capture.', {
305
307
  status,
306
308
  kind: 'credential_rejected',
307
- hint: "Open a meeting chat's Recap tab in a signed-in Teams tab to mint a fresh recap token, then retry.",
309
+ hint: whileWaitingGuidance('recap', captureWindowMs()),
308
310
  });
309
311
  }
310
312
  if (status === 403) {
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Sender email addresses for `teams_list_messages` and
3
+ * `teams_export_messages` (opt-in `sender_email`).
4
+ *
5
+ * A chat-service message names its sender by display name and MRI only (the
6
+ * MRI is the end of its `from` URL), never by address. So the address comes
7
+ * from the directory (Substrate people suggestions, `substrate.ts`, with the
8
+ * token the directory lookup already captures): the sender's display name is
9
+ * searched and the entry with EXACTLY the sender's MRI gives its email (else
10
+ * UPN). A namesake with another MRI is never taken.
11
+ *
12
+ * One lookup per distinct sender, never per message, and each answer — a
13
+ * miss included — is cached in memory (an hour by default, a bounded number
14
+ * of entries) so a later read or export part asks nothing again. A directory
15
+ * failure is reported once and cached as nothing, so the next call retries.
16
+ */
17
+ import { mapWithConcurrency, McpToolError } from '@chrischall/mcp-utils';
18
+ /** New senders one call looks up; the rest are counted as unresolved. */
19
+ export const MAX_SENDER_LOOKUPS = 50;
20
+ const DEFAULT_TTL_MS = 60 * 60 * 1000;
21
+ const MAX_ENTRIES = 2000;
22
+ const CONCURRENCY = 4;
23
+ /** Suggestions asked per name: enough to hold namesakes. */
24
+ const SUGGESTIONS = 10;
25
+ const ORGID = /^8:orgid:(\S+)$/i;
26
+ export class SenderEmailResolver {
27
+ #directory;
28
+ #ttlMs;
29
+ #now;
30
+ #cache = new Map();
31
+ constructor(directory, opts = {}) {
32
+ this.#directory = directory;
33
+ this.#ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;
34
+ this.#now = opts.now ?? Date.now;
35
+ }
36
+ #cached(key) {
37
+ const hit = this.#cache.get(key);
38
+ if (hit === undefined)
39
+ return undefined;
40
+ if (this.#now() - hit.at > this.#ttlMs) {
41
+ this.#cache.delete(key);
42
+ return undefined;
43
+ }
44
+ return hit;
45
+ }
46
+ #remember(key, email) {
47
+ if (this.#cache.size >= MAX_ENTRIES)
48
+ this.#cache.delete(this.#cache.keys().next().value);
49
+ this.#cache.set(key, { ...(email !== undefined ? { email } : {}), at: this.#now() });
50
+ }
51
+ async resolve(senders) {
52
+ const emails = new Map();
53
+ const todo = [];
54
+ const seen = new Set();
55
+ for (const s of senders) {
56
+ const key = s.mri.toLowerCase();
57
+ if (seen.has(key) || !ORGID.test(s.mri))
58
+ continue;
59
+ seen.add(key);
60
+ const hit = this.#cached(key);
61
+ if (hit === undefined)
62
+ todo.push(s);
63
+ else if (hit.email !== undefined)
64
+ emails.set(key, hit.email);
65
+ }
66
+ const now = todo.slice(0, MAX_SENDER_LOOKUPS);
67
+ const unresolved = todo.length - now.length;
68
+ let error;
69
+ await mapWithConcurrency(now, CONCURRENCY, async (s) => {
70
+ if (error !== undefined)
71
+ return;
72
+ const key = s.mri.toLowerCase();
73
+ const name = s.name.trim();
74
+ const text = name === '' || name.toLowerCase() === key ? ORGID.exec(s.mri)[1] : name;
75
+ try {
76
+ const people = await this.#directory.suggestPeople(text, { size: SUGGESTIONS });
77
+ const p = people.find((x) => x.mri.toLowerCase() === key);
78
+ const email = p?.email ?? p?.upn;
79
+ this.#remember(key, email);
80
+ if (email !== undefined)
81
+ emails.set(key, email);
82
+ }
83
+ catch (err) {
84
+ error ??= {
85
+ error: `Sender emails could not be looked up: ${err instanceof Error ? err.message : String(err)}`,
86
+ hint: (err instanceof McpToolError ? err.hint : undefined) ??
87
+ 'Run any search in the Teams search box of a signed-in Teams tab, then retry (that is what lets this ' +
88
+ 'server capture the token it searches the directory with).',
89
+ };
90
+ }
91
+ });
92
+ return { emails, ...(unresolved > 0 ? { unresolved } : {}), ...(error !== undefined ? { error } : {}) };
93
+ }
94
+ }
95
+ const resolvers = new WeakMap();
96
+ /** The one resolver (and so the one cache) per directory client. */
97
+ export function senderEmailResolver(directory) {
98
+ let r = resolvers.get(directory);
99
+ if (r === undefined) {
100
+ r = new SenderEmailResolver(directory);
101
+ resolvers.set(directory, r);
102
+ }
103
+ return r;
104
+ }
105
+ /** Every message object (one with a string `senderMri` and `sender`) anywhere in `value`. */
106
+ function walk(value, visit) {
107
+ if (Array.isArray(value)) {
108
+ for (const v of value)
109
+ walk(v, visit);
110
+ return;
111
+ }
112
+ if (value === null || typeof value !== 'object')
113
+ return;
114
+ const o = value;
115
+ if (typeof o.senderMri === 'string' && typeof o.sender === 'string')
116
+ visit(o);
117
+ for (const v of Object.values(o))
118
+ if (v !== null && typeof v === 'object')
119
+ walk(v, visit);
120
+ }
121
+ /** The distinct senders of the messages in `value`, first appearance first. */
122
+ export function collectSenders(value) {
123
+ const out = new Map();
124
+ walk(value, (m) => {
125
+ const key = m.senderMri.toLowerCase();
126
+ if (!out.has(key))
127
+ out.set(key, { mri: m.senderMri, name: m.sender });
128
+ });
129
+ return [...out.values()];
130
+ }
131
+ /** Set `senderEmail` on each message in `value` whose sender has one in `emails`. Mutates. */
132
+ export function addSenderEmails(value, emails) {
133
+ walk(value, (m) => {
134
+ const email = emails.get(m.senderMri.toLowerCase());
135
+ if (email !== undefined)
136
+ m.senderEmail = email;
137
+ });
138
+ }
139
+ /**
140
+ * Resolve and set the sender emails of every message in `value` (mutating
141
+ * it); what could not be done comes back to be reported beside the result.
142
+ */
143
+ export async function withSenderEmails(directory, value) {
144
+ const { emails, ...rest } = await senderEmailResolver(directory).resolve(collectSenders(value));
145
+ addSenderEmails(value, emails);
146
+ return rest;
147
+ }
@@ -57,6 +57,7 @@ import { randomUUID } from 'node:crypto';
57
57
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
58
58
  import { McpToolError } from '@chrischall/mcp-utils';
59
59
  import { captureWindowMs } from './capture-window.js';
60
+ import { whileWaitingGuidance } from './capture-feedback.js';
60
61
  import { bridgeScopedTransport, bridgeDownloadTransport, DOWNLOAD_VERB_TIMEOUT_MS, getWsPort } from './auth-fetchproxy.js';
61
62
  import { BRIDGE_TRUST_DOMAINS, isSharePointHost, rememberSharePointHost, sharePointCaptureDecl } from './bridge-scope.js';
62
63
  import { PACKAGE_NAME, VERSION } from './version.js';
@@ -97,21 +98,39 @@ export async function downloadSharePointFileViaBrowser(objectUrl, env = process.
97
98
  hint: 'Only https files on a *.sharepoint.com tenant host are downloaded.',
98
99
  });
99
100
  }
100
- const transport = bridgeDownloadTransport(env);
101
- await transport.start();
102
- try {
103
- const res = await transport.server.download({
104
- url: withDownloadQuery(target),
105
- // A fresh unguessable name under one subdir, so the read-then-delete below
106
- // never collides and never touches a file this server did not create.
107
- filename: `microsoft-teams-mcp-tmp/${randomUUID()}`,
108
- timeoutMs: DOWNLOAD_VERB_TIMEOUT_MS,
109
- });
110
- return { path: res.path, bytes: res.bytes, ...(res.mime !== undefined ? { mime: res.mime } : {}) };
111
- }
112
- finally {
113
- await transport.close().catch(() => { });
114
- }
101
+ return oneAtATime(async () => {
102
+ const transport = bridgeDownloadTransport(env);
103
+ await transport.start();
104
+ try {
105
+ const res = await transport.server.download({
106
+ url: withDownloadQuery(target),
107
+ // A fresh unguessable name under one subdir, so the read-then-delete below
108
+ // never collides and never touches a file this server did not create.
109
+ filename: `microsoft-teams-mcp-tmp/${randomUUID()}`,
110
+ timeoutMs: DOWNLOAD_VERB_TIMEOUT_MS,
111
+ });
112
+ return { path: res.path, bytes: res.bytes, ...(res.mime !== undefined ? { mime: res.mime } : {}) };
113
+ }
114
+ finally {
115
+ await transport.close().catch(() => { });
116
+ }
117
+ });
118
+ }
119
+ /** The tail of the browser-download queue (see {@link oneAtATime}). */
120
+ let downloadQueue = Promise.resolve();
121
+ /**
122
+ * Run browser downloads one at a time in this process. Each opens its own
123
+ * transport on the one bridge port and closes it when done; two at once
124
+ * collided — the first `close()` tore down the port the second was still using
125
+ * ("the MCP process holding the bridge port exited while this request was in
126
+ * flight"), so a parallel fetch of two attachments lost one to the slow token
127
+ * fallback (seen live 2026-11-30). A download takes about a second, so queueing
128
+ * costs little. A failed download releases the queue like a finished one.
129
+ */
130
+ function oneAtATime(run) {
131
+ const result = downloadQueue.then(run, run);
132
+ downloadQueue = result.catch(() => { });
133
+ return result;
115
134
  }
116
135
  /** Add `download=1` so SharePoint serves the file bytes, not the web viewer HTML. */
117
136
  function withDownloadQuery(target) {
@@ -177,6 +196,7 @@ export async function captureSharePointTokenViaFetchproxy(hosts, env = process.e
177
196
  // is turned into a typed, actionable McpToolError here — it will NOT get
178
197
  // better on a retry, so the retry wrapper leaves McpToolErrors alone and only
179
198
  // re-runs a plain capture failure (an idle-tab timeout).
199
+ const windowMs = captureWindowMs(env);
180
200
  const attempt = async () => {
181
201
  let refused = false;
182
202
  const scoped = bridgeScopedTransport(env, list);
@@ -190,14 +210,15 @@ export async function captureSharePointTokenViaFetchproxy(hosts, env = process.e
190
210
  // about to read.
191
211
  domains: SHAREPOINT_TRUST_DOMAINS,
192
212
  // Read per capture, not at import: see `capture-window.ts`.
193
- windowMs: captureWindowMs(env),
213
+ windowMs,
194
214
  port: getWsPort(),
195
215
  serverName: PACKAGE_NAME,
196
216
  version: VERSION,
197
217
  what: `a SharePoint token for ${label}`,
198
- guidance: `Open the file once in your signed-in browser (or reload your Teams tab) and retry while it ` +
199
- `loads — that is what makes the page call ${label} with the SharePoint token we capture. ` +
200
- `On a local install the file is normally downloaded straight through the browser with no token at all.`,
218
+ // The page load has to happen WHILE the capture waits: see `capture-feedback.ts`.
219
+ guidance: whileWaitingGuidance('sharepoint', windowMs) +
220
+ ` That is what makes the page call ${label} with the SharePoint token we capture. On a local ` +
221
+ `install the file is normally downloaded straight through the browser with no token at all.`,
201
222
  createTransport: (opts) => noteScopeRefusal(scoped(opts), () => (refused = true)),
202
223
  });
203
224
  }
@@ -274,8 +295,8 @@ function verifySharePointAudience(token, label) {
274
295
  if (!ok) {
275
296
  throw new McpToolError(`Captured a token for ${label} whose audience is not SharePoint's.`, {
276
297
  kind: 'credential_rejected',
277
- hint: `The browser's last request to ${label} carried a token for a different service. Open the file in ` +
278
- `SharePoint (or reload Teams) so the page makes a SharePoint request, then retry.`,
298
+ hint: `The browser's last request to ${label} carried a token for a different service. ` +
299
+ whileWaitingGuidance('sharepoint', captureWindowMs()),
279
300
  });
280
301
  }
281
302
  }