mcp-teams 0.3.30 → 0.3.31

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,9 +157,11 @@ 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.
161
163
  */
162
- function waitForCapture(service, since, timeoutMs) {
164
+ function waitForCapture(service, since, timeoutMs, rejected = null) {
163
165
  const key = `capture:${service}`;
164
166
  return new Promise((resolve) => {
165
167
  let done = false;
@@ -173,7 +175,7 @@ function waitForCapture(service, since, timeoutMs) {
173
175
  };
174
176
  const check = async () => {
175
177
  const cap = await getCapture(service);
176
- if (cap && cap.at > since) finish(cap);
178
+ if (cap && cap.at > since && !(rejected && sameHeaders(cap.headers, rejected))) finish(cap);
177
179
  };
178
180
  const onChanged = (changes, area) => area === "session" && changes[key]?.newValue && check();
179
181
  const onSeen = (s) => s === service && check();
@@ -236,9 +238,23 @@ function knownTab(ctx, tab) {
236
238
  return tab;
237
239
  }
238
240
 
239
- /** The Teams tab to run requests in: one on the origin of the service's capture, else any. */
241
+ /**
242
+ * The user's Teams tabs among `tabs`: never the background tab opened to recapture a session while
243
+ * it is recorded (it closes soon, and a request running there would fail with it). Once the user
244
+ * switched to it (it opens inactive, so active means they did), it is kept, so it counts like
245
+ * any other at once, before the worker forgets it.
246
+ */
247
+ async function userTeamsTabs(tabs) {
248
+ const helper = await helperTabId();
249
+ return tabs.filter((t) => TEAMS_TAB.test(t.url ?? "") && (t.id !== helper || t.active));
250
+ }
251
+
252
+ /**
253
+ * The Teams tab to run requests in: one on the origin of the service's capture, else any. With
254
+ * only the helper open, it opens one as with none (the helper is about to close).
255
+ */
240
256
  async function findTeamsTab(origin, ctx = null) {
241
- const tabs = (await openTabs(ctx)).filter((t) => TEAMS_TAB.test(t.url ?? ""));
257
+ const tabs = await userTeamsTabs(await openTabs(ctx));
242
258
  if (!tabs.length) return knownTab(ctx, await openTeamsTab());
243
259
  const sameOrigin = tabs.filter((t) => origin && t.url?.startsWith(origin));
244
260
  const pool = sameOrigin.length ? sameOrigin : tabs;
@@ -247,7 +263,7 @@ async function findTeamsTab(origin, ctx = null) {
247
263
 
248
264
  /** For list_teams and list_chats: with no Teams tab open, say so now rather than open one and wait. */
249
265
  async function requireTeamsTab(ctx) {
250
- const tabs = (await openTabs(ctx)).filter((t) => TEAMS_TAB.test(t.url ?? ""));
266
+ const tabs = await userTeamsTabs(await openTabs(ctx));
251
267
  if (!tabs.length) throw new Error("There is no Teams tab open. Open Teams in your browser, sign in, then try again.");
252
268
  }
253
269
 
@@ -285,93 +301,146 @@ async function waitForTabLoaded(tabId, timeoutMs = 30_000) {
285
301
  if (await waitForTab(tabId, (t) => t.status === "complete", timeoutMs)) await sleep(SETTLE_MS);
286
302
  }
287
303
 
288
- const refreshing = new Map(); // service -> Promise<capture|null>, so parallel calls reload once
304
+ const refreshing = new Map(); // service -> Promise<capture|null>, so parallel calls for a service wait once
289
305
 
290
306
  /**
291
307
  * 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).
308
+ * Teams' next own request to the service brings a fresh one; if none comes within
309
+ * `quickWaitMs`, Teams is opened in a background tab (recaptureInHelperTab), whose requests
310
+ * bring the session. The user's own Teams tab is never reloaded (a call or meeting there would
311
+ * drop): null when the session didn't come back (the caller fails with SERVICE_HELP).
312
+ * Search (substrate) gets no background tab: Teams signs in to it only once its search box was
313
+ * used, so a tab that just loaded wouldn't bring it. Nor does a user's tab that is still loading:
314
+ * it calls its services by itself, so the call waits for that (at most LOADING_TAB_WAIT_MS).
315
+ * `rejected`: the headers of a session Teams refused (401), which doesn't count as a fresh one.
295
316
  */
296
- function refreshSession(service, tab, { quickWaitMs = 4_000 } = {}) {
317
+ function refreshSession(service, tab, { quickWaitMs = 4_000, rejected = null } = {}) {
297
318
  if (!refreshing.has(service)) {
298
319
  const since = Date.now();
299
320
  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;
321
+ const current = await chrome.tabs.get(tab.id).catch(() => null);
322
+ if (current?.status === "loading") return waitForCapture(service, since, LOADING_TAB_WAIT_MS, rejected);
323
+ const quick = quickWaitMs ? await waitForCapture(service, since, quickWaitMs, rejected) : null;
308
324
  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;
325
+ if (service === "substrate") return null;
326
+ return recaptureInHelperTab(service, teamsOrigin(tab), since, rejected);
316
327
  })().finally(() => refreshing.delete(service));
317
328
  refreshing.set(service, p);
318
329
  }
319
330
  return refreshing.get(service);
320
331
  }
321
332
 
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.
333
+ const teamsOrigin = (tab) => {
334
+ const url = tab?.url || tab?.pendingUrl;
335
+ return TEAMS_TAB.test(url ?? "") ? new URL(url).origin : new URL(DEFAULT_TEAMS_URL).origin;
336
+ };
337
+
338
+ // After a reload: how long Teams' own requests get to bring the session back. Then, as after any
339
+ // missing or rejected session, how long Teams in the background tab gets to sign in.
324
340
  const RECAPTURE_GRACE_MS = 15_000;
325
341
  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.
342
+ // A call that joins the background tab late still waits at least this long (the tab stays open for it).
343
+ const RECAPTURE_JOIN_MIN_MS = 20_000;
344
+ // How long a call waits for a user's Teams tab that is still loading to bring the session.
345
+ const LOADING_TAB_WAIT_MS = 30_000;
346
+ let recapturing = null; // Promise of recaptureAfterReload while it runs, so a second report of the reload starts none
347
+ // The background tab (one at a time), kept in chrome.storage.session so a later worker can close it.
329
348
  const HELPER_TAB_KEY = "recaptureHelperTab";
349
+ // The background tab's run while it is open: { since, waits (Promise<capture|null>[]), tabGone, done, closing }.
350
+ let helperRun = null;
351
+
352
+ /**
353
+ * Opens Teams (`origin`) in a background tab, where it signs in and calls its services as on any
354
+ * load, and waits until `service` is captured there (other credentials than `rejected`), at most
355
+ * RECAPTURE_WAIT_MS from when the tab was opened, or RECAPTURE_JOIN_MIN_MS for a call that joins
356
+ * late: the capture, or null. One tab at a time: a call for another service while it is open
357
+ * waits on the same tab, which closes once every wait asked of it ended (unless the user switched
358
+ * to it), or as soon as the user closes it. It never reloads or scripts the user's own Teams tab.
359
+ */
360
+ function recaptureInHelperTab(service, origin, since = Date.now(), rejected = null) {
361
+ if (!helperRun || helperRun.closing) {
362
+ const run = { since: Date.now(), waits: [], closing: false };
363
+ let tabClosed;
364
+ run.tabGone = new Promise((r) => (tabClosed = r));
365
+ let tabId = null;
366
+ let closed = false;
367
+ const onRemoved = (id) => id === tabId && tabClosed();
368
+ const previous = helperRun?.done;
369
+ run.done = (async () => {
370
+ await previous; // a run still closing its tab finishes first: one background tab at a time
371
+ chrome.tabs.onRemoved.addListener(onRemoved);
372
+ const tab = await chrome.tabs.create({ url: `${origin}/`, active: false });
373
+ tabId = tab.id;
374
+ await chrome.storage.session.set({ [HELPER_TAB_KEY]: tab.id });
375
+ // Until every wait settled, including those that joined meanwhile, or the user closed the tab.
376
+ for (let n = -1; n !== run.waits.length; ) {
377
+ n = run.waits.length;
378
+ await Promise.race([Promise.all(run.waits), run.tabGone]);
379
+ }
380
+ run.closing = true;
381
+ closed = true;
382
+ await closeHelperTab(tab.id);
383
+ })()
384
+ .catch(() => {})
385
+ .finally(async () => {
386
+ run.closing = true;
387
+ chrome.tabs.onRemoved.removeListener(onRemoved);
388
+ tabClosed();
389
+ // Something failed after the tab was opened (e.g. recording it): it isn't left open.
390
+ if (tabId !== null && !closed) await closeHelperTab(tabId).catch(() => {});
391
+ if (helperRun === run) helperRun = null;
392
+ });
393
+ helperRun = run;
394
+ }
395
+ const run = helperRun;
396
+ const left = Math.max(run.since + RECAPTURE_WAIT_MS - Date.now(), RECAPTURE_JOIN_MIN_MS);
397
+ const wait = Promise.race([waitForCapture(service, since, left, rejected), run.tabGone.then(() => null)]);
398
+ run.waits.push(wait);
399
+ return wait;
400
+ }
401
+
402
+ /** The id of that background tab while it is recorded, else null. */
403
+ async function helperTabId() {
404
+ const { [HELPER_TAB_KEY]: tabId } = await chrome.storage.session.get(HELPER_TAB_KEY);
405
+ return tabId ?? null;
406
+ }
330
407
 
331
408
  /**
332
409
  * Chrome clears chrome.storage.session when the extension is reloaded or updated, so the
333
410
  * 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.
411
+ * again for a long time. Unless Teams does so within RECAPTURE_GRACE_MS, this gets the chat
412
+ * session back through the background tab (recaptureInHelperTab). Nothing is done without a
413
+ * Teams tab that has loaded and is awake: one still loading calls its services itself, and a
414
+ * discarded or unloaded one isn't woken.
342
415
  */
343
416
  function recaptureAfterReload() {
344
- recoveryRan = true;
345
417
  recapturing ??= (async () => {
346
418
  const since = Date.now();
347
419
  if (await getCapture("chatsvc")) return;
348
420
  const awake = (await chrome.tabs.query({ url: TEAMS_URLS })).filter((t) => TEAMS_TAB.test(t.url ?? "") && !t.discarded && t.status === "complete");
349
421
  if (!awake.length) return;
350
422
  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);
423
+ await recaptureInHelperTab("chatsvc", teamsOrigin(awake[0]), since);
355
424
  })()
356
425
  .catch(() => {})
357
426
  .finally(() => (recapturing = null));
358
427
  return recapturing;
359
428
  }
360
429
 
361
- /** Closes the background tab recaptureAfterReload opened, unless the user switched to it, and forgets it. */
430
+ /** Closes the background tab, unless the user switched to it, and forgets it. */
362
431
  async function closeHelperTab(tabId) {
363
432
  const tab = await chrome.tabs.get(tabId).catch(() => null);
364
433
  if (tab && !tab.active) await chrome.tabs.remove(tabId).catch(() => {});
365
- await chrome.storage.session.remove(HELPER_TAB_KEY);
434
+ if ((await helperTabId()) === tabId) await chrome.storage.session.remove(HELPER_TAB_KEY);
366
435
  }
367
436
 
368
437
  /**
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.
438
+ * A worker suspended while its background tab was open never closed it (Teams there may sit on
439
+ * a sign-in page): the next worker closes it when it wakes.
371
440
  */
372
441
  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);
442
+ if (helperRun) return; // this worker's own run closes it
443
+ const tabId = await helperTabId();
375
444
  if (tabId != null) await closeHelperTab(tabId);
376
445
  }
377
446
 
@@ -586,9 +655,9 @@ async function api(service, path, { method = "GET", body, raw = false, withLocat
586
655
  // The session (maybe the account) is changing: lists read with it are read again.
587
656
  dropList();
588
657
  meetingSessionsCache.clear();
589
- cap = await guarded(refreshSession(service, tab, { quickWaitMs: 0 }), ctx);
658
+ cap = await guarded(refreshSession(service, tab, { quickWaitMs: 0, rejected: cap.headers }), ctx);
590
659
  if (!cap) throw new Error(SERVICE_HELP[service]);
591
- // The tab reloaded (or was closed meanwhile): look the tabs up again.
660
+ // The tab may have been closed meanwhile: look the tabs up again.
592
661
  if (ctx) ctx.tabs = null;
593
662
  tab = await guarded(findTab(), ctx);
594
663
  await onCapture?.(cap);
@@ -1000,7 +1069,7 @@ async function fetchMessagePages(id, { limit, olderThan, includeSystem, threadId
1000
1069
 
1001
1070
  export const handlers = {
1002
1071
  async status() {
1003
- const tabs = await chrome.tabs.query({ url: TEAMS_URLS });
1072
+ const tabs = await userTeamsTabs(await chrome.tabs.query({ url: TEAMS_URLS }));
1004
1073
  const sessions = {};
1005
1074
  for (const s of ["chatsvc", "csa", "mt", "substrate"]) {
1006
1075
  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.31",
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.31",
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": {