mcp-teams 0.3.30 → 0.3.32

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/README.md CHANGED
@@ -90,7 +90,9 @@ You don't need to keep Teams open for most tools. When no Teams tab is open, the
90
90
 
91
91
  Teams on the web talks to several services, each with its own sign-in token: chats and messages (`chatsvc`), the team and chat list (`csa`), people (`mt`) and search (`substrate.office.com`). The extension notes the tokens Teams sends on its own requests and replays them from inside the Teams tab. They are kept in the browser's session memory and never leave the browser. Teams calls most of these services as soon as it loads. Search may only be signed in once you have used Teams' search box; until then `search_messages` and `find_people` say so.
92
92
 
93
- The browser clears that memory when the extension is reloaded or updated. A Teams tab left in the background may not call its services again for a while, so if it hasn't within 15 s, the extension opens Teams in another background tab, notes the tokens from that tab's requests and closes it again as soon as the chat session is back, or at the latest about 75 s after the reload (it stays open if you switch to it). This recovery restores the chat session without reloading your Teams tab, and after a reload or update the extension never reloads your Teams tab itself, so a call, meeting, draft or screen share there goes on. A tool call made meanwhile waits for the recovery; if a service it needs is still missing afterwards (for example search, which Teams signs in to only once you have used its search box), the call says so and asks you to click into or reload Teams yourself. Nothing is opened when no Teams tab is open, when the Teams tab is still loading (it signs in by itself), or when the browser has put every Teams tab to sleep (discarded).
93
+ The extension never reloads your Teams tab, so a call, meeting, draft or screen share there goes on. When a tool needs a session that isn't there, or Teams rejects one (tokens expire after about an hour), Teams' own tab gets a few seconds to send a fresh one; if it doesn't (and at once after a rejection), the extension opens Teams in a background tab, notes the tokens from that tab's requests and closes it again as soon as the sessions the waiting calls need are back, or after at most a minute (it stays open if you switch to it, and closing it ends the wait). There is only ever one such tab: calls that need different services at the same time wait on the same one. No tab is opened while your Teams tab is still loading, since it signs in by itself; the call waits up to 30 s for it instead. If the session still isn't back, the call says so and asks you to reload Teams yourself. Search is the exception: Teams signs in to it only once you have used its search box, so no tab is opened for it, and `search_messages` and `find_people` say so after a short wait.
94
+
95
+ The browser clears that memory when the extension is reloaded or updated. A Teams tab left in the background may not call its services again for a while, so if it hasn't within 15 s, the extension opens Teams in the same kind of background tab until the chat session is back, or at the latest about 75 s after the reload. A tool call made meanwhile uses that tab too. Nothing is opened after a reload or update when no Teams tab is open, when the Teams tab is still loading (it signs in by itself), or when the browser has put every Teams tab to sleep (discarded).
94
96
 
95
97
  ## Several sessions at once
96
98
 
@@ -157,10 +157,13 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
157
157
 
158
158
  /**
159
159
  * Waits until Teams sends the service a session after `since` (a new one, or the stored one
160
- * again); null on timeout. Listens for the capture instead of asking for it.
160
+ * again); null on timeout. Listens for the capture instead of asking for it. `rejected`: the
161
+ * headers Teams refused (401); that session sent again (by Teams, or replayed by another call)
162
+ * doesn't count, only one with other credentials. `signal`: aborting it ends the wait (null).
161
163
  */
162
- function waitForCapture(service, since, timeoutMs) {
164
+ function waitForCapture(service, since, timeoutMs, rejected = null, signal = null) {
163
165
  const key = `capture:${service}`;
166
+ if (signal?.aborted) return Promise.resolve(null);
164
167
  return new Promise((resolve) => {
165
168
  let done = false;
166
169
  const finish = (cap) => {
@@ -169,11 +172,14 @@ function waitForCapture(service, since, timeoutMs) {
169
172
  clearTimeout(timer);
170
173
  chrome.storage.onChanged.removeListener(onChanged);
171
174
  captureSeen.delete(onSeen);
175
+ signal?.removeEventListener("abort", onAbort);
172
176
  resolve(cap);
173
177
  };
178
+ const onAbort = () => finish(null);
179
+ signal?.addEventListener("abort", onAbort);
174
180
  const check = async () => {
175
181
  const cap = await getCapture(service);
176
- if (cap && cap.at > since) finish(cap);
182
+ if (cap && cap.at > since && !(rejected && sameHeaders(cap.headers, rejected))) finish(cap);
177
183
  };
178
184
  const onChanged = (changes, area) => area === "session" && changes[key]?.newValue && check();
179
185
  const onSeen = (s) => s === service && check();
@@ -236,9 +242,23 @@ function knownTab(ctx, tab) {
236
242
  return tab;
237
243
  }
238
244
 
239
- /** The Teams tab to run requests in: one on the origin of the service's capture, else any. */
245
+ /**
246
+ * The user's Teams tabs among `tabs`: never the background tab opened to recapture a session while
247
+ * it is recorded (it closes soon, and a request running there would fail with it). Once the user
248
+ * switched to it (it opens inactive, so active means they did), it is kept, so it counts like
249
+ * any other at once, before the worker forgets it.
250
+ */
251
+ async function userTeamsTabs(tabs) {
252
+ const helper = await helperTabId();
253
+ return tabs.filter((t) => TEAMS_TAB.test(t.url ?? "") && (t.id !== helper || t.active));
254
+ }
255
+
256
+ /**
257
+ * The Teams tab to run requests in: one on the origin of the service's capture, else any. With
258
+ * only the helper open, it opens one as with none (the helper is about to close).
259
+ */
240
260
  async function findTeamsTab(origin, ctx = null) {
241
- const tabs = (await openTabs(ctx)).filter((t) => TEAMS_TAB.test(t.url ?? ""));
261
+ const tabs = await userTeamsTabs(await openTabs(ctx));
242
262
  if (!tabs.length) return knownTab(ctx, await openTeamsTab());
243
263
  const sameOrigin = tabs.filter((t) => origin && t.url?.startsWith(origin));
244
264
  const pool = sameOrigin.length ? sameOrigin : tabs;
@@ -247,7 +267,7 @@ async function findTeamsTab(origin, ctx = null) {
247
267
 
248
268
  /** For list_teams and list_chats: with no Teams tab open, say so now rather than open one and wait. */
249
269
  async function requireTeamsTab(ctx) {
250
- const tabs = (await openTabs(ctx)).filter((t) => TEAMS_TAB.test(t.url ?? ""));
270
+ const tabs = await userTeamsTabs(await openTabs(ctx));
251
271
  if (!tabs.length) throw new Error("There is no Teams tab open. Open Teams in your browser, sign in, then try again.");
252
272
  }
253
273
 
@@ -285,93 +305,171 @@ async function waitForTabLoaded(tabId, timeoutMs = 30_000) {
285
305
  if (await waitForTab(tabId, (t) => t.status === "complete", timeoutMs)) await sleep(SETTLE_MS);
286
306
  }
287
307
 
288
- const refreshing = new Map(); // service -> Promise<capture|null>, so parallel calls reload once
308
+ // service -> { promise (capture|null), waiting (calls), kept, stop }, so parallel calls for a service wait once
309
+ const refreshing = new Map();
289
310
 
290
311
  /**
291
312
  * A captured token is lost when the extension reloads and expires after about an hour.
292
- * Teams' next own request to the service brings a fresh one; if none comes soon, reload
293
- * the Teams tab, which makes Teams call its services again. In a worker that started after a
294
- * reload or update (recoveryRan) it never reloads the tab: null (the caller says what to do).
313
+ * Teams' next own request to the service brings a fresh one; if none comes within
314
+ * `quickWaitMs`, Teams is opened in a background tab (recaptureInHelperTab), whose requests
315
+ * bring the session. The user's own Teams tab is never reloaded (a call or meeting there would
316
+ * drop): null when the session didn't come back (the caller fails with SERVICE_HELP).
317
+ * Search (substrate) gets no background tab: Teams signs in to it only once its search box was
318
+ * used, so a tab that just loaded wouldn't bring it. Nor does a user's tab that is still loading:
319
+ * it calls its services by itself, so the call waits for that (at most LOADING_TAB_WAIT_MS).
320
+ * `rejected`: the headers of a session Teams refused (401), which doesn't count as a fresh one.
321
+ * A call (`ctx`) that is withdrawn stops waiting at once (its reason); once every call waiting
322
+ * for the service was withdrawn, the wait itself is dropped, so the background tab doesn't stay
323
+ * open for nobody (a call without a ctx never withdraws).
295
324
  */
296
- function refreshSession(service, tab, { quickWaitMs = 4_000 } = {}) {
297
- if (!refreshing.has(service)) {
325
+ function refreshSession(service, tab, { quickWaitMs = 4_000, rejected = null } = {}, ctx = null) {
326
+ if (ctx?.cancelled) return Promise.reject(ctx.reason);
327
+ let entry = refreshing.get(service);
328
+ if (!entry) {
298
329
  const since = Date.now();
299
- const p = (async () => {
300
- // Right after a reload the worker is already getting Teams to sign in again without
301
- // touching the user's tab (recaptureAfterReload): wait for that rather than reload it.
302
- if (recapturing) {
303
- await recapturing;
304
- const cap = await getCapture(service);
305
- if (cap) return cap;
306
- }
307
- const quick = quickWaitMs ? await waitForCapture(service, since, quickWaitMs) : null;
330
+ const stop = new AbortController();
331
+ const { signal } = stop;
332
+ entry = { waiting: 0, kept: false, stop };
333
+ const self = entry;
334
+ entry.promise = (async () => {
335
+ const current = await chrome.tabs.get(tab.id).catch(() => null);
336
+ if (current?.status === "loading") return waitForCapture(service, since, LOADING_TAB_WAIT_MS, rejected, signal);
337
+ const quick = quickWaitMs ? await waitForCapture(service, since, quickWaitMs, rejected, signal) : null;
308
338
  if (quick) return quick;
309
- // After a reload or update the user's tab may be in a call or meeting: never reload it
310
- // from here. The call fails with SERVICE_HELP, which asks the user to do it.
311
- if (recoveryRan) return null;
312
- await chrome.tabs.reload(tab.id);
313
- const cap = await waitForCapture(service, since, 45_000);
314
- if (cap) await waitForTabLoaded(tab.id);
315
- return cap;
316
- })().finally(() => refreshing.delete(service));
317
- refreshing.set(service, p);
339
+ if (service === "substrate" || signal.aborted) return null;
340
+ return recaptureInHelperTab(service, teamsOrigin(tab), since, rejected, signal);
341
+ })().finally(() => refreshing.get(service) === self && refreshing.delete(service));
342
+ refreshing.set(service, entry);
343
+ }
344
+ if (!ctx) {
345
+ entry.kept = true;
346
+ return entry.promise;
318
347
  }
319
- return refreshing.get(service);
348
+ const self = entry;
349
+ self.waiting++;
350
+ const stopWatching = ctx.onCancel(() => {
351
+ if (--self.waiting > 0 || self.kept) return;
352
+ // Nobody waits for it anymore: a later call starts afresh.
353
+ if (refreshing.get(service) === self) refreshing.delete(service);
354
+ self.stop.abort();
355
+ });
356
+ self.promise.then(stopWatching, stopWatching);
357
+ return guarded(self.promise, ctx);
320
358
  }
321
359
 
322
- // After a reload: how long Teams' own requests get to bring the session back, then how long
323
- // Teams in the background tab gets to sign in.
360
+ const teamsOrigin = (tab) => {
361
+ const url = tab?.url || tab?.pendingUrl;
362
+ return TEAMS_TAB.test(url ?? "") ? new URL(url).origin : new URL(DEFAULT_TEAMS_URL).origin;
363
+ };
364
+
365
+ // After a reload: how long Teams' own requests get to bring the session back. Then, as after any
366
+ // missing or rejected session, how long Teams in the background tab gets to sign in.
324
367
  const RECAPTURE_GRACE_MS = 15_000;
325
368
  const RECAPTURE_WAIT_MS = 60_000;
326
- let recapturing = null; // Promise of the run below while it runs, so a second report of the reload starts none
327
- let recoveryRan = false; // this worker started after a reload or update: refreshSession never reloads a tab
328
- // The background tab it opened, kept in chrome.storage.session so a later worker can close it.
369
+ // A call that joins the background tab late still waits at least this long (the tab stays open for it).
370
+ const RECAPTURE_JOIN_MIN_MS = 20_000;
371
+ // How long a call waits for a user's Teams tab that is still loading to bring the session.
372
+ const LOADING_TAB_WAIT_MS = 30_000;
373
+ let recapturing = null; // Promise of recaptureAfterReload while it runs, so a second report of the reload starts none
374
+ // The background tab (one at a time), kept in chrome.storage.session so a later worker can close it.
329
375
  const HELPER_TAB_KEY = "recaptureHelperTab";
376
+ // The background tab's run while it is open: { since, waits (Promise<capture|null>[]), tabGone, done, closing }.
377
+ let helperRun = null;
378
+
379
+ /**
380
+ * Opens Teams (`origin`) in a background tab, where it signs in and calls its services as on any
381
+ * load, and waits until `service` is captured there (other credentials than `rejected`), at most
382
+ * RECAPTURE_WAIT_MS from when the tab was opened, or RECAPTURE_JOIN_MIN_MS for a call that joins
383
+ * late: the capture, or null. One tab at a time: a call for another service while it is open
384
+ * waits on the same tab, which closes once every wait asked of it ended (unless the user switched
385
+ * to it), or as soon as the user closes it. It never reloads or scripts the user's own Teams tab.
386
+ * `signal`: aborting it ends this wait (null) when nobody waits for it anymore, so the tab closes
387
+ * once no other wait is left.
388
+ */
389
+ function recaptureInHelperTab(service, origin, since = Date.now(), rejected = null, signal = null) {
390
+ if (!helperRun || helperRun.closing) {
391
+ const run = { since: Date.now(), waits: [], closing: false };
392
+ let tabClosed;
393
+ run.tabGone = new Promise((r) => (tabClosed = r));
394
+ let tabId = null;
395
+ let closed = false;
396
+ const onRemoved = (id) => id === tabId && tabClosed();
397
+ const previous = helperRun?.done;
398
+ run.done = (async () => {
399
+ await previous; // a run still closing its tab finishes first: one background tab at a time
400
+ chrome.tabs.onRemoved.addListener(onRemoved);
401
+ const tab = await chrome.tabs.create({ url: `${origin}/`, active: false });
402
+ tabId = tab.id;
403
+ await chrome.storage.session.set({ [HELPER_TAB_KEY]: tab.id });
404
+ // Until every wait settled, including those that joined meanwhile, or the user closed the tab.
405
+ for (let n = -1; n !== run.waits.length; ) {
406
+ n = run.waits.length;
407
+ await Promise.race([Promise.all(run.waits), run.tabGone]);
408
+ }
409
+ run.closing = true;
410
+ closed = true;
411
+ await closeHelperTab(tab.id);
412
+ })()
413
+ .catch(() => {})
414
+ .finally(async () => {
415
+ run.closing = true;
416
+ chrome.tabs.onRemoved.removeListener(onRemoved);
417
+ tabClosed();
418
+ // Something failed after the tab was opened (e.g. recording it): it isn't left open.
419
+ if (tabId !== null && !closed) await closeHelperTab(tabId).catch(() => {});
420
+ if (helperRun === run) helperRun = null;
421
+ });
422
+ helperRun = run;
423
+ }
424
+ const run = helperRun;
425
+ const left = Math.max(run.since + RECAPTURE_WAIT_MS - Date.now(), RECAPTURE_JOIN_MIN_MS);
426
+ const wait = Promise.race([waitForCapture(service, since, left, rejected, signal), run.tabGone.then(() => null)]);
427
+ run.waits.push(wait);
428
+ return wait;
429
+ }
430
+
431
+ /** The id of that background tab while it is recorded, else null. */
432
+ async function helperTabId() {
433
+ const { [HELPER_TAB_KEY]: tabId } = await chrome.storage.session.get(HELPER_TAB_KEY);
434
+ return tabId ?? null;
435
+ }
330
436
 
331
437
  /**
332
438
  * Chrome clears chrome.storage.session when the extension is reloaded or updated, so the
333
439
  * captured sessions are gone; a Teams tab left in the background may not call its services
334
- * again for a long time. Unless Teams does so within RECAPTURE_GRACE_MS, this opens Teams (the
335
- * origin of the open tab) in a background tab, where it signs in and calls its services as on
336
- * any load, and closes that tab once the chat session is captured or after RECAPTURE_WAIT_MS
337
- * (unless the user switched to it). It never reloads or scripts the user's own Teams tab; a tool
338
- * call meanwhile waits for it, and from then on refreshSession doesn't reload that tab either
339
- * (a service still missing fails the call with SERVICE_HELP). Nothing is
340
- * done without a Teams tab that has loaded and is awake: one still loading calls its services
341
- * itself, and a discarded or unloaded one isn't woken.
440
+ * again for a long time. Unless Teams does so within RECAPTURE_GRACE_MS, this gets the chat
441
+ * session back through the background tab (recaptureInHelperTab). Nothing is done without a
442
+ * Teams tab that has loaded and is awake: one still loading calls its services itself, and a
443
+ * discarded or unloaded one isn't woken.
342
444
  */
343
445
  function recaptureAfterReload() {
344
- recoveryRan = true;
345
446
  recapturing ??= (async () => {
346
447
  const since = Date.now();
347
448
  if (await getCapture("chatsvc")) return;
348
449
  const awake = (await chrome.tabs.query({ url: TEAMS_URLS })).filter((t) => TEAMS_TAB.test(t.url ?? "") && !t.discarded && t.status === "complete");
349
450
  if (!awake.length) return;
350
451
  if (await waitForCapture("chatsvc", since, RECAPTURE_GRACE_MS)) return;
351
- const tab = await chrome.tabs.create({ url: `${new URL(awake[0].url).origin}/`, active: false });
352
- await chrome.storage.session.set({ [HELPER_TAB_KEY]: tab.id });
353
- await waitForCapture("chatsvc", since, RECAPTURE_WAIT_MS);
354
- await closeHelperTab(tab.id);
452
+ await recaptureInHelperTab("chatsvc", teamsOrigin(awake[0]), since);
355
453
  })()
356
454
  .catch(() => {})
357
455
  .finally(() => (recapturing = null));
358
456
  return recapturing;
359
457
  }
360
458
 
361
- /** Closes the background tab recaptureAfterReload opened, unless the user switched to it, and forgets it. */
459
+ /** Closes the background tab, unless the user switched to it, and forgets it. */
362
460
  async function closeHelperTab(tabId) {
363
461
  const tab = await chrome.tabs.get(tabId).catch(() => null);
364
462
  if (tab && !tab.active) await chrome.tabs.remove(tabId).catch(() => {});
365
- await chrome.storage.session.remove(HELPER_TAB_KEY);
463
+ if ((await helperTabId()) === tabId) await chrome.storage.session.remove(HELPER_TAB_KEY);
366
464
  }
367
465
 
368
466
  /**
369
- * A worker suspended while recaptureAfterReload waited never closed its background tab (Teams
370
- * there may sit on a sign-in page): the next worker closes it when it wakes.
467
+ * A worker suspended while its background tab was open never closed it (Teams there may sit on
468
+ * a sign-in page): the next worker closes it when it wakes.
371
469
  */
372
470
  async function closeLeftoverHelperTab() {
373
- if (recapturing) return; // this worker's own run closes it
374
- const { [HELPER_TAB_KEY]: tabId } = await chrome.storage.session.get(HELPER_TAB_KEY);
471
+ if (helperRun) return; // this worker's own run closes it
472
+ const tabId = await helperTabId();
375
473
  if (tabId != null) await closeHelperTab(tabId);
376
474
  }
377
475
 
@@ -573,7 +671,7 @@ async function api(service, path, { method = "GET", body, raw = false, withLocat
573
671
  // Opening a tab or waiting for a session can take a minute; a withdrawn request stops waiting.
574
672
  let tab = await guarded(findTeamsTab(cap ? new URL(cap.base).origin : null, ctx), ctx);
575
673
  if (!cap) {
576
- cap = await guarded(refreshSession(service, tab, { quickWaitMs: service === "substrate" ? 2_000 : 4_000 }), ctx);
674
+ cap = await refreshSession(service, tab, { quickWaitMs: service === "substrate" ? 2_000 : 4_000 }, ctx);
577
675
  if (!cap) throw new Error(SERVICE_HELP[service]);
578
676
  }
579
677
  const urlFor = (c) => teams.serviceUrl(path, c.base);
@@ -586,9 +684,9 @@ async function api(service, path, { method = "GET", body, raw = false, withLocat
586
684
  // The session (maybe the account) is changing: lists read with it are read again.
587
685
  dropList();
588
686
  meetingSessionsCache.clear();
589
- cap = await guarded(refreshSession(service, tab, { quickWaitMs: 0 }), ctx);
687
+ cap = await refreshSession(service, tab, { quickWaitMs: 0, rejected: cap.headers }, ctx);
590
688
  if (!cap) throw new Error(SERVICE_HELP[service]);
591
- // The tab reloaded (or was closed meanwhile): look the tabs up again.
689
+ // The tab may have been closed meanwhile: look the tabs up again.
592
690
  if (ctx) ctx.tabs = null;
593
691
  tab = await guarded(findTab(), ctx);
594
692
  await onCapture?.(cap);
@@ -1000,7 +1098,7 @@ async function fetchMessagePages(id, { limit, olderThan, includeSystem, threadId
1000
1098
 
1001
1099
  export const handlers = {
1002
1100
  async status() {
1003
- const tabs = await chrome.tabs.query({ url: TEAMS_URLS });
1101
+ const tabs = await userTeamsTabs(await chrome.tabs.query({ url: TEAMS_URLS }));
1004
1102
  const sessions = {};
1005
1103
  for (const s of ["chatsvc", "csa", "mt", "substrate"]) {
1006
1104
  const cap = await getCapture(s);
@@ -2,7 +2,7 @@
2
2
  "manifest_version": 3,
3
3
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvoz9Wexl4ZqY9YtEyBZsu/Qi5Ft5EjNUNB8b30wgt3AR8TjXI5UumcPQFBIm7ZfvBsjgrh6tBJlygsgFbZ5cB1EiI+WSz/2Wcqwz4eowKMXXPvGuDGrO+2O2zbSpTG19/MwTljI+g0TLfn8Vkoqd8z9MskKk+vCZjjV0Jk8QjVEdHypgM7H8zTuUM06SO12IIZMdeE3IURzf35zbjlfPPkJiDWoo3wB9nxAvLd57xrQhPUB/lGtCJk9mS3SY+/VwOlG5kJ9WS/RCHXcs5Qs7huIlKIatmFz7YiducvTR3DKBbjqbMTyqHzXkmkUmJRqzsYtgtKcz0C0cjFOt6uNdhwIDAQAB",
4
4
  "name": "mcp-teams bridge",
5
- "version": "0.3.30",
5
+ "version": "0.3.32",
6
6
  "description": "Lets AI assistants (via the mcp-teams MCP server) read and search Microsoft Teams chats, channels and meeting transcripts and, with your explicit confirmation, post messages.",
7
7
  "minimum_chrome_version": "116",
8
8
  "icons": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-teams",
3
- "version": "0.3.30",
3
+ "version": "0.3.32",
4
4
  "description": "MCP server that lets AI assistants work with Microsoft Teams (web) through a Chrome/Edge extension bridge",
5
5
  "keywords": ["mcp", "model-context-protocol", "teams", "microsoft-teams", "microsoft-365", "chat", "claude", "chrome-extension"],
6
6
  "repository": {