mcp-teams 0.3.31 → 0.3.33

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
@@ -108,7 +108,7 @@ Every AI session starts its own mcp-teams server, and they share the one extensi
108
108
  | `port` | `TEAMS_MCP_PORT` | `47393` (also set it in the extension popup) |
109
109
  | `autoSendTo` | — | `[]`: every send shows the confirmation window |
110
110
 
111
- `autoSendTo` is a list of your own email addresses (or UPNs), compared without regard to case or surrounding spaces, e.g. `"autoSendTo": ["you@example.com"]`. With it, `send_message` posts without the confirmation window when the message goes to you alone: your notes-to-self chat, a chat whose only member is you, or `to` with just your own address. The extension decides this itself after resolving the target: it looks up your profile and posts without asking only if one of your own addresses is on the list. Anything else (other people, group chats you are in, meetings, channels, a chat or profile it can't look up) shows the window as usual. The result then says `autoSent: true`. A value that isn't a list of email addresses stops the server with an error. Restart the AI session after changing it.
111
+ `autoSendTo` is a list of your own email addresses (or UPNs), compared without regard to case or surrounding spaces, e.g. `"autoSendTo": ["you@example.com"]`. With it, `send_message` posts without the confirmation window when the message goes to you alone: your notes-to-self chat, a chat whose only member is you, or `to` with just your own address. The extension decides this itself after resolving the target: it looks up your profile and posts without asking only if one of your own addresses is on the list. Anything else (other people, group chats you are in, meetings, channels, a chat or profile it can't look up) shows the window as usual. The result then says `autoSent: true`. A send that began before Teams had shown who is signed in never goes without the window. It shows the window only when the lookups for the send reveal the account. Otherwise it is refused ("Teams hasn't shown who is signed in yet"): reload the Teams tab and send again. This includes every `to` send in that case, as it looks nothing up first. A value that isn't a list of email addresses stops the server with an error. Restart the AI session after changing it.
112
112
 
113
113
  ## Security notes
114
114
 
@@ -159,10 +159,11 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
159
159
  * Waits until Teams sends the service a session after `since` (a new one, or the stored one
160
160
  * again); null on timeout. Listens for the capture instead of asking for it. `rejected`: the
161
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.
162
+ * doesn't count, only one with other credentials. `signal`: aborting it ends the wait (null).
163
163
  */
164
- function waitForCapture(service, since, timeoutMs, rejected = null) {
164
+ function waitForCapture(service, since, timeoutMs, rejected = null, signal = null) {
165
165
  const key = `capture:${service}`;
166
+ if (signal?.aborted) return Promise.resolve(null);
166
167
  return new Promise((resolve) => {
167
168
  let done = false;
168
169
  const finish = (cap) => {
@@ -171,8 +172,11 @@ function waitForCapture(service, since, timeoutMs, rejected = null) {
171
172
  clearTimeout(timer);
172
173
  chrome.storage.onChanged.removeListener(onChanged);
173
174
  captureSeen.delete(onSeen);
175
+ signal?.removeEventListener("abort", onAbort);
174
176
  resolve(cap);
175
177
  };
178
+ const onAbort = () => finish(null);
179
+ signal?.addEventListener("abort", onAbort);
176
180
  const check = async () => {
177
181
  const cap = await getCapture(service);
178
182
  if (cap && cap.at > since && !(rejected && sameHeaders(cap.headers, rejected))) finish(cap);
@@ -301,7 +305,8 @@ async function waitForTabLoaded(tabId, timeoutMs = 30_000) {
301
305
  if (await waitForTab(tabId, (t) => t.status === "complete", timeoutMs)) await sleep(SETTLE_MS);
302
306
  }
303
307
 
304
- const refreshing = new Map(); // service -> Promise<capture|null>, so parallel calls for a service wait once
308
+ // service -> { promise (capture|null), waiting (calls), kept, stop }, so parallel calls for a service wait once
309
+ const refreshing = new Map();
305
310
 
306
311
  /**
307
312
  * A captured token is lost when the extension reloads and expires after about an hour.
@@ -313,21 +318,43 @@ const refreshing = new Map(); // service -> Promise<capture|null>, so parallel c
313
318
  * used, so a tab that just loaded wouldn't bring it. Nor does a user's tab that is still loading:
314
319
  * it calls its services by itself, so the call waits for that (at most LOADING_TAB_WAIT_MS).
315
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).
316
324
  */
317
- function refreshSession(service, tab, { quickWaitMs = 4_000, rejected = null } = {}) {
318
- 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) {
319
329
  const since = Date.now();
320
- const p = (async () => {
330
+ const stop = new AbortController();
331
+ const { signal } = stop;
332
+ entry = { waiting: 0, kept: false, stop };
333
+ const self = entry;
334
+ entry.promise = (async () => {
321
335
  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;
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;
324
338
  if (quick) return quick;
325
- if (service === "substrate") return null;
326
- return recaptureInHelperTab(service, teamsOrigin(tab), since, rejected);
327
- })().finally(() => refreshing.delete(service));
328
- 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;
329
347
  }
330
- 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);
331
358
  }
332
359
 
333
360
  const teamsOrigin = (tab) => {
@@ -356,8 +383,10 @@ let helperRun = null;
356
383
  * late: the capture, or null. One tab at a time: a call for another service while it is open
357
384
  * waits on the same tab, which closes once every wait asked of it ended (unless the user switched
358
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.
359
388
  */
360
- function recaptureInHelperTab(service, origin, since = Date.now(), rejected = null) {
389
+ function recaptureInHelperTab(service, origin, since = Date.now(), rejected = null, signal = null) {
361
390
  if (!helperRun || helperRun.closing) {
362
391
  const run = { since: Date.now(), waits: [], closing: false };
363
392
  let tabClosed;
@@ -394,7 +423,7 @@ function recaptureInHelperTab(service, origin, since = Date.now(), rejected = nu
394
423
  }
395
424
  const run = helperRun;
396
425
  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)]);
426
+ const wait = Promise.race([waitForCapture(service, since, left, rejected, signal), run.tabGone.then(() => null)]);
398
427
  run.waits.push(wait);
399
428
  return wait;
400
429
  }
@@ -642,7 +671,7 @@ async function api(service, path, { method = "GET", body, raw = false, withLocat
642
671
  // Opening a tab or waiting for a session can take a minute; a withdrawn request stops waiting.
643
672
  let tab = await guarded(findTeamsTab(cap ? new URL(cap.base).origin : null, ctx), ctx);
644
673
  if (!cap) {
645
- 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);
646
675
  if (!cap) throw new Error(SERVICE_HELP[service]);
647
676
  }
648
677
  const urlFor = (c) => teams.serviceUrl(path, c.base);
@@ -655,7 +684,7 @@ async function api(service, path, { method = "GET", body, raw = false, withLocat
655
684
  // The session (maybe the account) is changing: lists read with it are read again.
656
685
  dropList();
657
686
  meetingSessionsCache.clear();
658
- cap = await guarded(refreshSession(service, tab, { quickWaitMs: 0, rejected: cap.headers }), ctx);
687
+ cap = await refreshSession(service, tab, { quickWaitMs: 0, rejected: cap.headers }, ctx);
659
688
  if (!cap) throw new Error(SERVICE_HELP[service]);
660
689
  // The tab may have been closed meanwhile: look the tabs up again.
661
690
  if (ctx) ctx.tabs = null;
@@ -700,11 +729,14 @@ async function myMri() {
700
729
  */
701
730
  const accountKey = (cap) => (cap ? `${cap.base}\n${cap.oid ?? ""}` : null);
702
731
 
732
+ let accountSwitches = 0; // bumped by forgetAccount: a send sees that a switch landed while it looked things up
733
+
703
734
  /**
704
735
  * The user switched Teams to another account or tenant: forget what the previous one saw.
705
736
  * (Throttle gates stay: they are Teams' limits per service and base, not anyone's data.)
706
737
  */
707
738
  function forgetAccount() {
739
+ accountSwitches++;
708
740
  dropList();
709
741
  names.clear();
710
742
  transcripts.clear();
@@ -1331,6 +1363,7 @@ export const handlers = {
1331
1363
  async requestSend({ conversation, to, title, text, threadId, subject, autoSendTo }, ctx) {
1332
1364
  if (!String(text ?? "").trim()) throw new Error("The message is empty.");
1333
1365
  // Who the window (or an auto-send) is for: taken before anything is looked up for it.
1366
+ const switches = accountSwitches;
1334
1367
  const account = await signedInAccount();
1335
1368
  // The server's allowlist (config autoSendTo) only permits; whether this send goes without the
1336
1369
  // window is decided below from the target as resolved here (see sendsToMeAlone, isMeAlone).
@@ -1338,8 +1371,8 @@ export const handlers = {
1338
1371
  if (to?.length) {
1339
1372
  if (conversation) throw new Error("Give either a conversation or people (to), not both.");
1340
1373
  if (threadId || subject) throw new Error("reply_to and subject are for channels; a new chat takes people and an optional title.");
1341
- const me = await myMri();
1342
- if (!me) throw new Error("Teams hasn't shown who is signed in yet. Reload the Teams tab and try again.");
1374
+ if (!account) throw new Error(NOT_SHOWN);
1375
+ const me = `8:orgid:${account}`;
1343
1376
  if (allow.length && !title && (await sendsToMeAlone(to, me, allow, ctx))) {
1344
1377
  return sendWithoutConfirming({ conversation: NOTES_TO_SELF, text: String(text) }, ctx, account);
1345
1378
  }
@@ -1360,8 +1393,15 @@ export const handlers = {
1360
1393
  replyingTo = root ? teams.parseMessage(root) : { id: threadId };
1361
1394
  }
1362
1395
  const request = { conversation: conv, text: String(text), threadId: threadId ?? null, subject: subject ?? null, replyingTo };
1363
- if (allow.length && !threadId && !subject && (await isMeAlone(conv, allow, ctx))) return sendWithoutConfirming(request, ctx, account);
1364
- return askUserToConfirm(request, ctx, account);
1396
+ // Without an account known from the start, the decision to send goes to the user (the window).
1397
+ if (account && allow.length && !threadId && !subject && (await isMeAlone(conv, allow, ctx))) return sendWithoutConfirming(request, ctx, account);
1398
+ if (account) return askUserToConfirm(request, ctx, account);
1399
+ // A cold start: the lookups may have shown who is signed in. The window rests on that account,
1400
+ // unless a switch landed since the send began, when they may have been another account's.
1401
+ const shown = await signedInAccount();
1402
+ if (switches !== accountSwitches) return { sent: false, reason: ACCOUNT_CHANGED_BEFORE };
1403
+ if (!shown) throw new Error(NOT_SHOWN);
1404
+ return askUserToConfirm(request, ctx, shown);
1365
1405
  },
1366
1406
  };
1367
1407
 
@@ -1369,7 +1409,7 @@ export const handlers = {
1369
1409
  * Creates a chat with these members and me (called only after the user clicked Send).
1370
1410
  * A 1:1 chat that already exists on Teams' side comes back as that chat.
1371
1411
  */
1372
- async function createChat({ members, title }, account = null) {
1412
+ async function createChat({ members, title }, account) {
1373
1413
  const me = await myMri();
1374
1414
  const oneOnOne = members.length === 1;
1375
1415
  const body = {
@@ -1396,16 +1436,16 @@ async function createChat({ members, title }, account = null) {
1396
1436
  }
1397
1437
 
1398
1438
  /**
1399
- * An onCapture check for a post confirmed as `account` (an oid, or null when Teams hadn't shown
1400
- * who was signed in): fails before anything is sent when the session it would go out with is
1439
+ * An onCapture check for a post confirmed as `account` (an oid; requestSend goes no further
1440
+ * without one): fails before anything is sent when the session it would go out with is
1401
1441
  * another account's (Teams switched since the click).
1402
1442
  */
1403
1443
  const asConfirmed = (account) => async (cap) => {
1404
- if (account && (cap.oid ?? (await signedInAccount())) !== account) throw Object.assign(new Error(ACCOUNT_CHANGED), { accountChanged: true });
1444
+ if ((cap.oid ?? (await signedInAccount())) !== account) throw Object.assign(new Error(ACCOUNT_CHANGED), { accountChanged: true });
1405
1445
  };
1406
1446
 
1407
1447
  /** Posts a confirmed message; `account`: who confirmed it (see asConfirmed). */
1408
- async function sendMessage({ conversation, newChat, people, text, threadId, subject }, account = null) {
1448
+ async function sendMessage({ conversation, newChat, people, text, threadId, subject }, account) {
1409
1449
  if (newChat) {
1410
1450
  let id;
1411
1451
  try {
@@ -1519,11 +1559,11 @@ async function isMeAlone(conv, allow, ctx) {
1519
1559
  * Posts without the window (see above). Once started, the post runs to the end, as after a click.
1520
1560
  * `account`: who it was judged to reach alone; as after a click, it isn't posted as another (3.3).
1521
1561
  */
1522
- async function sendWithoutConfirming(request, ctx, account = null) {
1562
+ async function sendWithoutConfirming(request, ctx, account) {
1523
1563
  if (ctx?.cancelled) return WITHDRAWN;
1524
1564
  autoSending++;
1525
1565
  try {
1526
- if (account && (await signedInAccount()) !== account) return { sent: false, autoSent: true, reason: ACCOUNT_CHANGED };
1566
+ if ((await signedInAccount()) !== account) return { sent: false, autoSent: true, reason: ACCOUNT_CHANGED };
1527
1567
  return { ...(await sendMessage(request, account)), autoSent: true, note: AUTO_SENT_NOTE };
1528
1568
  } catch (err) {
1529
1569
  return { sent: false, autoSent: true, reason: sendFailure(err) };
@@ -1546,6 +1586,8 @@ export function pendingSendCount() {
1546
1586
  }
1547
1587
 
1548
1588
  const ACCOUNT_CHANGED = "The signed-in Teams account changed since this was confirmed; nothing was sent.";
1589
+ const ACCOUNT_CHANGED_BEFORE = "The signed-in Teams account changed while this send was being prepared; nothing was sent. Check who is signed in, then try again.";
1590
+ const NOT_SHOWN = "Teams hasn't shown who is signed in yet. Reload the Teams tab and try again.";
1549
1591
  const CHAT_CREATED_ACCOUNT_CHANGED =
1550
1592
  "The chat was created, but no message was sent: the signed-in Teams account changed while it was being sent. Check with list_chats (as the account that confirmed it) before trying again.";
1551
1593
 
@@ -1569,7 +1611,7 @@ const WITHDRAWN = {
1569
1611
  * the AI was told the send failed. Once the user clicked Send, the post runs to the end
1570
1612
  * and its outcome is the answer.
1571
1613
  */
1572
- async function askUserToConfirm(request, ctx, account = null) {
1614
+ async function askUserToConfirm(request, ctx, account) {
1573
1615
  if (ctx?.cancelled) return WITHDRAWN;
1574
1616
  const id = crypto.randomUUID();
1575
1617
  const win = await chrome.windows.create({
@@ -1637,7 +1679,7 @@ function onConfirmMessage(msg, sender, sendResponse) {
1637
1679
  // From here on the post runs to the end: a withdrawal no longer closes the window.
1638
1680
  p.sending = true;
1639
1681
  // Confirmed as one account, clicked after Teams switched to another: its session would post it.
1640
- if (p.account && (await signedInAccount()) !== p.account) {
1682
+ if ((await signedInAccount()) !== p.account) {
1641
1683
  p.finish({ sent: false, reason: ACCOUNT_CHANGED }, true);
1642
1684
  return sendResponse({ ok: false, error: ACCOUNT_CHANGED });
1643
1685
  }
@@ -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.31",
5
+ "version": "0.3.33",
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.31",
3
+ "version": "0.3.33",
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": {