@chrischall/microsoft-teams-mcp 0.8.6 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chatsvc.js CHANGED
@@ -8,9 +8,11 @@
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`,
12
- * `removeReaction` and `setConsumptionHorizon`, which only the confirm-gated
13
- * `teams_send_message`, `teams_react` and `teams_mark_read` (and the read
11
+ * `fetchImage` and `getThread`; the writes are `sendMessage`, `setReaction`,
12
+ * `removeReaction`, `setConsumptionHorizon`, `setTopic`, `addMember` and
13
+ * `removeMember`, which only the confirm-gated `teams_send_message`,
14
+ * `teams_react`, `teams_mark_read`, `teams_rename_chat`,
15
+ * `teams_add_chat_members` and `teams_remove_chat_members` (and the read
14
16
  * tools' opt-in `mark_read`) call. A read never writes the read marker
15
17
  * (`consumptionhorizon`) on its own, so reading a chat through this MCP leaves
16
18
  * the user's unread badges alone unless they ask for it to be marked read.
@@ -106,6 +108,7 @@ function outcomeUnknown(method, e, hint) {
106
108
  }
107
109
  const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_list_messages) before retrying; do not resend blindly.';
108
110
  const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_list_messages) before retrying.';
111
+ const THREAD_OUTCOME_HINT = 'The change to the chat may already have been applied — check the chat (its name and members) before retrying.';
109
112
  const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_list_messages) before retrying; ' +
110
113
  'moving it again to the same message is harmless.';
111
114
  export class ChatServiceClient {
@@ -208,6 +211,9 @@ export class ChatServiceClient {
208
211
  async listConversations() {
209
212
  this.#requireConfigured();
210
213
  const out = [];
214
+ // A conversation that changes while the pages are read can come back on a
215
+ // later page too (seen live 2026-11-09); its first, newest copy is kept.
216
+ const seen = new Set();
211
217
  let url = `${this.#baseUrl}/users/ME/conversations?view=msnp24Equivalent&pageSize=200`;
212
218
  for (let page = 0; url !== undefined && page < MAX_CONVERSATION_PAGES; page++) {
213
219
  const body = await this.#getJson(url);
@@ -215,8 +221,10 @@ export class ChatServiceClient {
215
221
  if (convs.length === 0)
216
222
  break;
217
223
  for (const c of convs) {
218
- if (typeof c?.id === 'string' && (!c.id.startsWith('48:') || c.id === SELF_CHAT))
219
- out.push(c);
224
+ if (typeof c?.id !== 'string' || (c.id.startsWith('48:') && c.id !== SELF_CHAT) || seen.has(c.id))
225
+ continue;
226
+ seen.add(c.id);
227
+ out.push(c);
220
228
  }
221
229
  url = this.#nextLink(body);
222
230
  }
@@ -358,6 +366,41 @@ export class ChatServiceClient {
358
366
  const { status } = await this.#send(url, 'text', undefined, { method: 'PUT', body, hint: HORIZON_OUTCOME_HINT });
359
367
  this.#checkWriteStatus('PUT', status, HORIZON_OUTCOME_HINT);
360
368
  }
369
+ /**
370
+ * A chat thread's topic and members (`GET /threads/{id}?view=msnp24Equivalent`,
371
+ * verified live 2026-11-09). Members are MRIs and roles only.
372
+ */
373
+ async getThread(id) {
374
+ this.#requireConfigured();
375
+ return this.#getJson(`${this.#threadUrl(id)}?view=msnp24Equivalent`);
376
+ }
377
+ /**
378
+ * Rename a group chat: `PUT /threads/{id}/properties?name=topic` with
379
+ * `{ topic }` (verified live 2026-11-09: 200, `{}`). Teams posts a notice in
380
+ * the chat. A lost answer is a `WriteOutcomeUnknownError`.
381
+ */
382
+ async setTopic(id, topic) {
383
+ await this.#writeThread('PUT', `${this.#threadUrl(id)}/properties?name=topic`, { topic });
384
+ }
385
+ /**
386
+ * Add someone to a group chat: `PUT /threads/{id}/members/{mri}` with
387
+ * `{ role }` (verified live 2026-11-09). Repeating it is harmless.
388
+ */
389
+ async addMember(id, mri, role = 'User') {
390
+ await this.#writeThread('PUT', `${this.#threadUrl(id)}/members/${encodeURIComponent(mri)}`, { role });
391
+ }
392
+ /** Remove someone from a group chat: `DELETE /threads/{id}/members/{mri}`, no body (verified live 2026-11-09). */
393
+ async removeMember(id, mri) {
394
+ await this.#writeThread('DELETE', `${this.#threadUrl(id)}/members/${encodeURIComponent(mri)}`);
395
+ }
396
+ #threadUrl(id) {
397
+ return `${this.#baseUrl}/threads/${encodeURIComponent(id)}`;
398
+ }
399
+ async #writeThread(method, url, body) {
400
+ this.#requireConfigured();
401
+ const { status } = await this.#send(url, 'text', undefined, { method, body, hint: THREAD_OUTCOME_HINT });
402
+ this.#checkWriteStatus(method, status, THREAD_OUTCOME_HINT);
403
+ }
361
404
  /**
362
405
  * Download an inline image (`<img src>` in a message body).
363
406
  *
@@ -479,6 +522,8 @@ export class ChatServiceClient {
479
522
  write) {
480
523
  let body = '';
481
524
  const method = write?.method ?? 'GET';
525
+ // A write with no body (a member DELETE) sends neither a body nor a content-type.
526
+ const payload = write?.body !== undefined ? JSON.stringify(write.body) : undefined;
482
527
  const res = await this.#tokenManager().withAuth(async (token) => {
483
528
  const init = {
484
529
  method,
@@ -488,9 +533,9 @@ export class ChatServiceClient {
488
533
  // a redirect to a sign-in page instead of a status we can act on.
489
534
  behavioroverride: 'redirectAs404',
490
535
  accept: read === 'text' ? 'application/json' : '*/*',
491
- ...(write ? { 'content-type': 'application/json' } : {}),
536
+ ...(payload !== undefined ? { 'content-type': 'application/json' } : {}),
492
537
  },
493
- ...(write ? { body: JSON.stringify(write.body) } : {}),
538
+ ...(payload !== undefined ? { body: payload } : {}),
494
539
  // Never let a redirect carry the bearer somewhere we did not vet.
495
540
  redirect: 'error',
496
541
  };
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ import { registerAttachmentTools } from './tools/attachment.js';
13
13
  import { registerSendTools } from './tools/send.js';
14
14
  import { registerReactTools } from './tools/react.js';
15
15
  import { registerMarkReadTools } from './tools/markread.js';
16
+ import { registerGroupChatTools } from './tools/group-chat.js';
16
17
  import { registerActivityTools } from './tools/activity.js';
17
18
  import { registerSearchTools } from './tools/search.js';
18
19
  import { registerHealthcheckTool } from './tools/healthcheck.js';
@@ -24,7 +25,7 @@ loadDotenvSafely();
24
25
  * for the full rationale (`runMcp` builds a server instance per served
25
26
  * connection, so anything built inside a registrar would be rebuilt). For
26
27
  * this MCP a second `ChatServiceClient` would mean a second token capture.
27
- * `SharePointClient` holds its own per-host token managers, so the same reason
28
+ * `SharePointClient` holds its own SharePoint token manager, so the same reason
28
29
  * applies — build it once, here, beside the chat-service client — and so does
29
30
  * `SubstrateClient`, which holds the search token.
30
31
  */
@@ -48,6 +49,7 @@ await runMcp({
48
49
  registerSendTools,
49
50
  registerReactTools,
50
51
  registerMarkReadTools,
52
+ registerGroupChatTools,
51
53
  registerActivityTools,
52
54
  registerSearchTools,
53
55
  registerExportTools,
@@ -20,10 +20,13 @@
20
20
  * - that token authenticates a plain server-side GET of
21
21
  * `/_api/v2.1/shares/u!{base64url(objectUrl)}/driveItem`, whose
22
22
  * `@content.downloadUrl` is a pre-signed link fetched with no auth;
23
- * - it is short-lived (~53 min) and host-family-scoped: the
24
- * `{tenant}-my.sharepoint.com` OneDrive token also worked on
25
- * `{tenant}.sharepoint.com`, but got 403 on a separate OneDrive-region host
26
- * — so that region needs its own captured token.
23
+ * - it is short-lived.
24
+ *
25
+ * Verified live 2026-11-09: one token serves every SharePoint host of the
26
+ * tenant. Tokens captured from `{tenant}-my` and from a separate OneDrive-region
27
+ * host `{tenant}ind-my` each returned 200 on both of those hosts and on the
28
+ * `{tenant}` team-site root. (The 2026-10-11 spike read a 403 on the region host
29
+ * as the token not covering it; it was the file's own permissions.)
27
30
  *
28
31
  * The capture layer cannot wildcard the host: `validateCaptureHeaderDecls` runs
29
32
  * each capture host through `HOSTNAME_RE`, which rejects `*.sharepoint.com`. The
@@ -34,13 +37,16 @@
34
37
  * `endsWith('.' + domain)` — so one domain covers every tenant SP host without
35
38
  * re-pairing per host. That domain is one of the one bridge scope every capture
36
39
  * of this server declares (`bridge-scope.ts`); a capture host is added to it,
37
- * and remembered, once a capture of it succeeds.
40
+ * and remembered, once a capture of it succeeds. Since any granted host yields
41
+ * a token every host accepts, later captures read off the granted hosts and
42
+ * never widen the scope.
38
43
  *
39
44
  * Import this module LAZILY (`await import('./sharepoint-auth.js')`) from the
40
45
  * code that needs a token, as `auth-fetchproxy.ts` is, so a server run with
41
46
  * `TEAMS_DISABLE_FETCHPROXY` never has to load the bridge to boot.
42
47
  */
43
48
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
49
+ import { McpToolError } from '@chrischall/mcp-utils';
44
50
  import { captureWindowMs } from './capture-window.js';
45
51
  import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
46
52
  import { BRIDGE_TRUST_DOMAINS, isSharePointHost, rememberSharePointHost, sharePointCaptureDecl } from './bridge-scope.js';
@@ -48,7 +54,7 @@ import { PACKAGE_NAME, VERSION } from './version.js';
48
54
  /**
49
55
  * The domains the SharePoint capture trusts: the one bridge scope
50
56
  * (`bridge-scope.ts`), whose `sharepoint.com` covers every tenant SP host, while
51
- * the per-host capture decl below stays a concrete hostname (the capture layer
57
+ * each capture decl below stays a concrete hostname (the capture layer
52
58
  * rejects a wildcard).
53
59
  */
54
60
  export const SHAREPOINT_TRUST_DOMAINS = [...BRIDGE_TRUST_DOMAINS];
@@ -63,12 +69,11 @@ export { isSharePointHost } from './bridge-scope.js';
63
69
  * (`<tenant>.sharepoint.com`) — so capturing from the file's own host times out
64
70
  * for a team-site file. The `-my` token, however, downloads team-site files too
65
71
  * (it worked cross-host to `transunion.sharepoint.com` in the spike). So:
66
- * - a file already on a `*-my` host → capture from that host (incl. a separate
67
- * region OneDrive like `<tenant>ind-my`, which needs its own token);
72
+ * - a file already on a `*-my` host → capture from that host;
68
73
  * - a file on a `<tenant>.sharepoint.com` root → capture from `<tenant>-my`.
69
- * The result always satisfies {@link isSharePointHost}. One `-my` token thus
70
- * serves every file on both that OneDrive and its tenant root, which is why the
71
- * client keys its per-host token cache by this capture host.
74
+ * The result always satisfies {@link isSharePointHost}. Used only for the
75
+ * first capture, before any host has been granted: after that the client
76
+ * captures off the granted hosts, whose token serves every host.
72
77
  */
73
78
  export function captureHostFor(fileHost) {
74
79
  const h = fileHost.toLowerCase();
@@ -78,38 +83,87 @@ export function captureHostFor(fileHost) {
78
83
  return m ? `${m[1]}-my.sharepoint.com` : h;
79
84
  }
80
85
  /**
81
- * Capture a SharePoint access token for `host` from the user's signed-in Teams
82
- * tab. Returns the bare token (no `Bearer ` prefix).
86
+ * Capture a SharePoint access token from the user's signed-in Teams tab, off
87
+ * the first request the page makes to any of `hosts`. Returns the bare token
88
+ * (no `Bearer ` prefix).
89
+ *
90
+ * One token serves every SharePoint host of the tenant, so the caller passes
91
+ * the hosts the bridge has already granted (any of them yields a usable
92
+ * token), or the file's own capture host when none has been granted yet. Each
93
+ * must be a concrete SharePoint host — it becomes a capture decl.
83
94
  *
84
- * `host` must be a concrete SharePoint host — it becomes the capture decl, and
85
- * sending a bearer later depends on it being one we vetted.
95
+ * A host the bridge has not granted is refused by the extension, which queues
96
+ * a scope-update offer in its popup meanwhile. The bridge's own advice for that
97
+ * ("revoke and re-pair") is heavier than the fix, so a capture that failed
98
+ * with a refusal throws an `McpToolError` saying to approve the offer.
86
99
  */
87
- export async function captureSharePointTokenViaFetchproxy(host, env = process.env) {
88
- if (!isSharePointHost(host)) {
89
- throw new Error(`refusing to capture a SharePoint token for ${JSON.stringify(host)}: not a ` +
100
+ export async function captureSharePointTokenViaFetchproxy(hosts, env = process.env) {
101
+ const list = [...new Set((typeof hosts === 'string' ? [hosts] : [...hosts]).map((h) => h.toLowerCase()))];
102
+ const bad = list.find((h) => !isSharePointHost(h));
103
+ if (list.length === 0 || bad !== undefined) {
104
+ throw new Error(`refusing to capture a SharePoint token for ${JSON.stringify(bad ?? '')}: not a ` +
90
105
  '*.sharepoint.com host');
91
106
  }
92
- const token = await captureBearerHeader({
93
- // The one request we capture from: any call the browser makes to this
94
- // OneDrive host (the caller resolves it from the file's host via
95
- // `captureHostFor`). A concrete host, never a wildcard — see the module note.
96
- captures: [sharePointCaptureDecl(host)],
97
- // The one bridge scope (`bridge-scope.ts`), with this host's capture added
98
- // to the remembered ones so the hello asks for exactly what it is about to
99
- // read.
100
- domains: SHAREPOINT_TRUST_DOMAINS,
101
- // Read per capture, not at import: see `capture-window.ts`.
102
- windowMs: captureWindowMs(env),
103
- port: getWsPort(),
104
- serverName: PACKAGE_NAME,
105
- version: VERSION,
106
- what: `a SharePoint token for ${host}`,
107
- guidance: `Click around Teams or open one of your own OneDrive files — that makes the ` +
108
- `browser request ${host}, which is where the SharePoint token is captured ` +
109
- 'from — then retry.',
110
- createTransport: bridgeScopedTransport(env, host),
111
- });
112
- // Granted and captured: every later hello declares this host too.
113
- rememberSharePointHost(host, env);
107
+ const label = list.join(' or ');
108
+ // `captureBearerHeader` flattens a capture failure into a plain Error, so the
109
+ // refusal's type is noted here, where it is still a typed error.
110
+ let refused = false;
111
+ const scoped = bridgeScopedTransport(env, list);
112
+ let token;
113
+ try {
114
+ token = await captureBearerHeader({
115
+ // Any call the browser makes to one of these hosts. Concrete hosts, never
116
+ // a wildcard — see the module note.
117
+ captures: list.map(sharePointCaptureDecl),
118
+ // The one bridge scope (`bridge-scope.ts`), with these hosts' captures
119
+ // added to the remembered ones so the hello asks for exactly what it is
120
+ // about to read.
121
+ domains: SHAREPOINT_TRUST_DOMAINS,
122
+ // Read per capture, not at import: see `capture-window.ts`.
123
+ windowMs: captureWindowMs(env),
124
+ port: getWsPort(),
125
+ serverName: PACKAGE_NAME,
126
+ version: VERSION,
127
+ what: `a SharePoint token for ${label}`,
128
+ guidance: `Reload your signed-in Teams tab and retry while it loads — that makes the ` +
129
+ `page call ${label} with the SharePoint token we capture.`,
130
+ createTransport: (opts) => noteScopeRefusal(scoped(opts), () => (refused = true)),
131
+ });
132
+ }
133
+ catch (err) {
134
+ if (!refused)
135
+ throw err;
136
+ throw new McpToolError(`The ContextMint Bridge has not yet allowed a SharePoint token capture from ${label}.`, {
137
+ hint: `Open the ContextMint Bridge extension popup and approve the pending scope update for ${PACKAGE_NAME}, ` +
138
+ `which adds ${label} (no need to remove or re-pair it). Then retry, and reload your Teams tab while it waits.`,
139
+ cause: err,
140
+ });
141
+ }
142
+ // Granted and captured: every later hello declares these hosts too.
143
+ for (const h of list)
144
+ rememberSharePointHost(h, env);
114
145
  return token;
115
146
  }
147
+ /** Call `onRefused` when the bridge refuses a capture for being outside the granted scope. */
148
+ function noteScopeRefusal(transport, onRefused) {
149
+ const server = transport.server;
150
+ const capture = server.captureRequestHeader.bind(server);
151
+ return {
152
+ start: () => transport.start(),
153
+ close: () => transport.close(),
154
+ server: {
155
+ captureRequestHeader: async (...args) => {
156
+ try {
157
+ return await capture(...args);
158
+ }
159
+ catch (err) {
160
+ // @fetchproxy/server's FetchproxyScopeError, matched by name: this
161
+ // module must not import the optional bridge package for a class.
162
+ if (err instanceof Error && err.name === 'FetchproxyScopeError')
163
+ onRefused();
164
+ throw err;
165
+ }
166
+ },
167
+ },
168
+ };
169
+ }
@@ -5,10 +5,10 @@ import { reportCacheWriteFailure } from './token-cache.js';
5
5
  * Where the captured SharePoint access tokens are cached between runs.
6
6
  *
7
7
  * A SEPARATE file from the chat-service `token.json`: a SharePoint token is a
8
- * different audience with a very different lifetime (~53 min vs chatsvc's ~23h),
9
- * and there is one per SharePoint host rather than one overall — so this file
10
- * holds a `Record<host, BearerTokens>`, not a single token. Deliberately its own
11
- * directory for the same reason `tokenCachePath` is.
8
+ * different audience with a different lifetime. One token serves every
9
+ * SharePoint host of the tenant (see {@link SharePointTokenCache.shared}), held
10
+ * under the `*` key; older releases kept one entry per host, which `shared()`
11
+ * still reads. Deliberately its own file for the same reason `tokenCachePath` is.
12
12
  */
13
13
  export function sharePointTokenCachePath(env = process.env) {
14
14
  return resolveStateFile({
@@ -36,6 +36,8 @@ function validateMap(raw) {
36
36
  }
37
37
  return out;
38
38
  }
39
+ /** The key the one shared token is stored under. */
40
+ const SHARED_KEY = '*';
39
41
  /**
40
42
  * The SharePoint token cache, or `null` when it is off or there is nothing to
41
43
  * cache.
@@ -50,28 +52,31 @@ export function createSharePointTokenCache(env = process.env) {
50
52
  return null;
51
53
  if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env }))
52
54
  return null;
53
- // One file-backed persistence for the whole map; the per-host views below read
54
- // and write it. No `boundTo`: there is no single credential the whole map is
55
+ // One file-backed persistence for the map; the shared view below reads and
56
+ // writes it. No `boundTo`: there is no single credential the whole map is
55
57
  // minted from — each host's token stands or falls on its own shape.
56
58
  const file = createFileStatePersistence({
57
59
  filePath: sharePointTokenCachePath(env),
58
60
  validate: validateMap,
59
61
  });
60
62
  return {
61
- forHost(host) {
63
+ shared() {
62
64
  return {
63
65
  load() {
64
- return file.load()?.[host] ?? null;
66
+ const map = file.load();
67
+ if (!map)
68
+ return null;
69
+ if (map[SHARED_KEY])
70
+ return map[SHARED_KEY];
71
+ const legacy = Object.values(map).sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0));
72
+ return legacy[0] ?? null;
65
73
  },
66
74
  save(tokens) {
67
- // Read-modify-write the shared map so a sibling host's token survives.
68
75
  // A failed write is reported, never thrown: a SharePoint token is
69
76
  // cheap to re-capture, and a read-only data dir must not take the
70
77
  // tool down — it just loses the between-run cache.
71
78
  try {
72
- const map = file.load() ?? {};
73
- map[host] = tokens;
74
- file.save(map);
79
+ file.save({ [SHARED_KEY]: tokens });
75
80
  }
76
81
  catch (err) {
77
82
  reportCacheWriteFailure(err);
@@ -79,11 +84,8 @@ export function createSharePointTokenCache(env = process.env) {
79
84
  },
80
85
  clear() {
81
86
  try {
82
- const map = file.load();
83
- if (map && host in map) {
84
- delete map[host];
85
- file.save(map);
86
- }
87
+ if (file.load())
88
+ file.save({});
87
89
  }
88
90
  catch (err) {
89
91
  reportCacheWriteFailure(err);
@@ -12,12 +12,15 @@
12
12
  * GET {@content.downloadUrl} [no auth — pre-signed]
13
13
  * → the file's bytes
14
14
  *
15
- * The SP token is captured per host from the user's browser (see
16
- * `sharepoint-auth.ts`), is short-lived (~53 min) and host-family-scoped, so this
17
- * client holds one `TokenManager` per host — each with the same capture-on-401
18
- * recovery `ChatServiceClient` has. A 403 is expected (an account that cannot
19
- * open the file, or a host the captured token does not cover) and degrades
20
- * gracefully; it never crashes the tool.
15
+ * The SP token is captured from the user's browser (see `sharepoint-auth.ts`).
16
+ * One token serves every SharePoint host of the tenant — verified live
17
+ * 2026-11-09, a token captured from one OneDrive host returned 200 on another
18
+ * OneDrive region host and on the team-site root — so this client holds ONE
19
+ * `TokenManager`, with the same capture-on-401 recovery `ChatServiceClient` has.
20
+ * (It once held one per host, which made every new host wait for the user to
21
+ * open a file from it; the 403 that suggested per-host tokens was a per-file
22
+ * permission denial.) A 403 is expected — an account that cannot open the
23
+ * file — and degrades gracefully; it never crashes the tool.
21
24
  *
22
25
  * As with `chatsvc.ts`, once a token is held every request is a plain Node
23
26
  * `fetch` — the bridge is only ever touched to capture the token.
@@ -26,6 +29,7 @@ import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils'
26
29
  import { describeTransportFailure } from './network-error.js';
27
30
  import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
28
31
  import { createSharePointTokenCache } from './sharepoint-token-cache.js';
32
+ import { knownSharePointHosts } from './bridge-scope.js';
29
33
  /**
30
34
  * Capture a SharePoint token for `host` lazily.
31
35
  *
@@ -35,9 +39,9 @@ import { createSharePointTokenCache } from './sharepoint-token-cache.js';
35
39
  * server could answer `initialize`. Deferring it (exactly as `chatsvc.ts` does
36
40
  * for its own capture) keeps boot free of the bridge.
37
41
  */
38
- async function captureSharePointTokenLazily(host) {
42
+ async function captureSharePointTokenLazily(hosts) {
39
43
  const mod = await import('./sharepoint-auth.js');
40
- return mod.captureSharePointTokenViaFetchproxy(host);
44
+ return mod.captureSharePointTokenViaFetchproxy(hosts);
41
45
  }
42
46
  /** Per-request deadline, covering the body read. */
43
47
  const REQUEST_TIMEOUT_MS = 60_000;
@@ -53,6 +57,7 @@ async function reachable(url, run) {
53
57
  export class SharePointClient {
54
58
  #env;
55
59
  #capture;
60
+ #knownHosts;
56
61
  #fetchImpl;
57
62
  #cache;
58
63
  /**
@@ -60,11 +65,14 @@ export class SharePointClient {
60
65
  * still boots (and answers `tools/list`) with no credential present.
61
66
  */
62
67
  #configError = null;
63
- /** One `TokenManager` per SharePoint host — SP tokens are host-scoped. */
64
- #managers = new Map();
68
+ /** The one `TokenManager`: one SharePoint token serves every host of the tenant. */
69
+ #manager = null;
70
+ /** The capture host of the file being fetched — where a first-ever capture looks. */
71
+ #fileCaptureHost = '';
65
72
  constructor(opts = {}) {
66
73
  this.#env = opts.env ?? process.env;
67
74
  this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
75
+ this.#knownHosts = opts.knownHosts ?? (() => knownSharePointHosts(this.#env));
68
76
  // A receiver-safe wrapper, never the bare global: older undici throws
69
77
  // `Illegal invocation` when `fetch` is called with a non-global receiver.
70
78
  this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
@@ -115,16 +123,16 @@ export class SharePointClient {
115
123
  hint: 'Only https files on a *.sharepoint.com tenant host are downloaded.',
116
124
  });
117
125
  }
118
- // The driveItem GET goes to the FILE's host, but the token is captured from
119
- // (and cached under) the user's OneDrive host — the browser authenticates
120
- // that host, and its token reads the tenant root too. See `captureHostFor`.
126
+ // The driveItem GET goes to the FILE's host. The token comes from whichever
127
+ // host a capture reads it off: one already granted, else this file's
128
+ // OneDrive host (see `#captureHosts` and `captureHostFor`).
121
129
  const { captureHostFor } = await import('./sharepoint-auth.js');
122
- const captureHost = captureHostFor(host);
130
+ this.#fileCaptureHost = captureHostFor(host);
123
131
  // `u!` + unpadded base64url of the full objectUrl (Node's `base64url` already
124
132
  // uses `-`/`_` and drops padding), matching the live spike.
125
133
  const share = `u!${Buffer.from(objectUrl, 'utf8').toString('base64url')}`;
126
134
  const driveItemUrl = `https://${host}/_api/v2.1/shares/${share}/driveItem?$select=id,size,@content.downloadUrl`;
127
- const meta = await this.#getDriveItem(captureHost, driveItemUrl);
135
+ const meta = await this.#getDriveItem(driveItemUrl);
128
136
  // Refuse an oversize file BEFORE streaming it: the driveItem carries `size`,
129
137
  // so a file past the cap degrades to metadata + link (the attachment tool
130
138
  // surfaces this hint) instead of fetching to the byte limit and tripping a
@@ -152,22 +160,26 @@ export class SharePointClient {
152
160
  if (this.#configError)
153
161
  throw this.#configError;
154
162
  }
155
- /** The `TokenManager` for `host`, created (and cached) on first use. */
156
- #managerFor(host) {
157
- const existing = this.#managers.get(host);
158
- if (existing)
159
- return existing;
160
- // The per-host cache view already swallows-and-reports its own write
161
- // failures (see `sharepoint-token-cache.ts`), so it is passed straight
162
- // through — no inline wrapping as chatsvc needs for its raw persistence.
163
+ /**
164
+ * Where to capture the token from: the hosts the bridge has already granted
165
+ * (any of them yields a token every host accepts), or this file's OneDrive
166
+ * host when none has been. Declaring a new host when a granted one would do
167
+ * only widens the bridge scope, which the extension refuses until approved.
168
+ */
169
+ #captureHosts() {
170
+ const known = this.#knownHosts();
171
+ return known.length > 0 ? known : [this.#fileCaptureHost];
172
+ }
173
+ /** The one `TokenManager`, created on first use. */
174
+ #tokens() {
163
175
  // Captured on first use, re-captured on a 401 (no refresh grant), expiring
164
- // at the JWT's `exp`.
165
- const mgr = createCapturedTokenManager({
166
- capture: () => this.#capture(host),
167
- persistence: this.#cache?.forHost(host) ?? null,
176
+ // at the JWT's `exp`. The cache view swallows-and-reports its own write
177
+ // failures (see `sharepoint-token-cache.ts`).
178
+ this.#manager ??= createCapturedTokenManager({
179
+ capture: () => this.#capture(this.#captureHosts()),
180
+ persistence: this.#cache?.shared() ?? null,
168
181
  });
169
- this.#managers.set(host, mgr);
170
- return mgr;
182
+ return this.#manager;
171
183
  }
172
184
  /**
173
185
  * The authed driveItem GET, with chatsvc's discipline: `behavioroverride:
@@ -176,9 +188,9 @@ export class SharePointClient {
176
188
  * `TokenManager.withAuth` supplies the token and, on a 401, re-captures once
177
189
  * and replays once — so a 401 that reaches here is the second one.
178
190
  */
179
- async #getDriveItem(captureHost, url) {
191
+ async #getDriveItem(url) {
180
192
  let body = '';
181
- const res = await this.#managerFor(captureHost).withAuth(async (token) => {
193
+ const res = await this.#tokens().withAuth(async (token) => {
182
194
  const r = await reachable(url, () => fetchBounded(url, {
183
195
  method: 'GET',
184
196
  headers: {
@@ -195,11 +207,12 @@ export class SharePointClient {
195
207
  if (status === 403) {
196
208
  // mcp-utils' `kind` vocabulary has no 'forbidden'; the 403 is carried by
197
209
  // `status`, which the attachment tool reads to degrade to metadata + link.
210
+ // The token is good on every host of the tenant, so a 403 is the file's
211
+ // own permissions (verified live 2026-11-09).
198
212
  throw new McpToolError('SharePoint refused access to the file (403).', {
199
213
  status,
200
214
  kind: 'http',
201
- hint: 'Your account cannot open this file, or it is on a SharePoint host your captured ' +
202
- 'token does not cover. Open it once in Teams, then retry.',
215
+ hint: 'Your account cannot open this file. Ask whoever shared it to give you access, then retry.',
203
216
  });
204
217
  }
205
218
  if (status === 404) {
@@ -254,7 +267,7 @@ export class SharePointClient {
254
267
  throw new McpToolError('SharePoint rejected the access token (401) even after a fresh capture.', {
255
268
  status,
256
269
  kind: 'credential_rejected',
257
- hint: 'Open the shared file once in a signed-in Teams tab to mint a fresh SharePoint token, then retry.',
270
+ hint: 'Reload your signed-in Teams tab to mint a fresh SharePoint token, and retry while it loads.',
258
271
  });
259
272
  }
260
273
  if (status === 429) {