@chrischall/microsoft-teams-mcp 0.8.7 → 0.10.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/bundle.js CHANGED
@@ -37090,11 +37090,11 @@ async function confirmWrite(ctx, options) {
37090
37090
  }
37091
37091
  const query = request?.query ? Object.fromEntries(Object.entries(request.query).filter(([, v]) => v !== void 0)) : void 0;
37092
37092
  const hasQuery = query !== void 0 && Object.keys(query).length > 0;
37093
- const shown2 = willSend !== void 0 ? willSend : request?.body !== void 0 ? request.body : payload;
37093
+ const shown3 = willSend !== void 0 ? willSend : request?.body !== void 0 ? request.body : payload;
37094
37094
  const preview = {
37095
37095
  ...summary === void 0 ? {} : { action: summary },
37096
37096
  ...request === void 0 ? {} : { method: request.method, path: request.path },
37097
- ...shown2 === void 0 ? {} : { willSend: shown2 },
37097
+ ...shown3 === void 0 ? {} : { willSend: shown3 },
37098
37098
  ...hasQuery ? { willSendQuery: query } : {},
37099
37099
  ...extra
37100
37100
  };
@@ -38523,7 +38523,7 @@ var init_version = __esm({
38523
38523
  "src/version.ts"() {
38524
38524
  "use strict";
38525
38525
  PACKAGE_NAME = "microsoft-teams-mcp";
38526
- VERSION = "0.8.7";
38526
+ VERSION = "0.10.0";
38527
38527
  }
38528
38528
  });
38529
38529
 
@@ -43636,7 +43636,7 @@ var require_websocket = __commonJS({
43636
43636
  BINARY_TYPES,
43637
43637
  CLOSE_TIMEOUT,
43638
43638
  EMPTY_BUFFER,
43639
- GUID,
43639
+ GUID: GUID3,
43640
43640
  kForOnEventAttribute,
43641
43641
  kListener,
43642
43642
  kStatusCode,
@@ -44312,7 +44312,7 @@ var require_websocket = __commonJS({
44312
44312
  abortHandshake(websocket, socket, "Invalid Upgrade header");
44313
44313
  return;
44314
44314
  }
44315
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
44315
+ const digest = createHash5("sha1").update(key + GUID3).digest("base64");
44316
44316
  if (res.headers["sec-websocket-accept"] !== digest) {
44317
44317
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
44318
44318
  return;
@@ -44691,7 +44691,7 @@ var require_websocket_server = __commonJS({
44691
44691
  var PerMessageDeflate2 = require_permessage_deflate();
44692
44692
  var subprotocol2 = require_subprotocol();
44693
44693
  var WebSocket2 = require_websocket();
44694
- var { CLOSE_TIMEOUT, GUID, kWebSocket } = require_constants();
44694
+ var { CLOSE_TIMEOUT, GUID: GUID3, kWebSocket } = require_constants();
44695
44695
  var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
44696
44696
  var RUNNING = 0;
44697
44697
  var CLOSING = 1;
@@ -44993,7 +44993,7 @@ var require_websocket_server = __commonJS({
44993
44993
  );
44994
44994
  }
44995
44995
  if (this._state > RUNNING) return abortHandshake(socket, 503);
44996
- const digest = createHash5("sha1").update(key + GUID).digest("base64");
44996
+ const digest = createHash5("sha1").update(key + GUID3).digest("base64");
44997
44997
  const headers = [
44998
44998
  "HTTP/1.1 101 Switching Protocols",
44999
44999
  "Upgrade: websocket",
@@ -49916,27 +49916,25 @@ function createSharePointTokenCache(env = process.env) {
49916
49916
  validate: validateMap
49917
49917
  });
49918
49918
  return {
49919
- forHost(host) {
49919
+ shared() {
49920
49920
  return {
49921
49921
  load() {
49922
- return file2.load()?.[host] ?? null;
49922
+ const map2 = file2.load();
49923
+ if (!map2) return null;
49924
+ if (map2[SHARED_KEY]) return map2[SHARED_KEY];
49925
+ const legacy = Object.values(map2).sort((a, b) => (b.expiresAt ?? 0) - (a.expiresAt ?? 0));
49926
+ return legacy[0] ?? null;
49923
49927
  },
49924
49928
  save(tokens) {
49925
49929
  try {
49926
- const map2 = file2.load() ?? {};
49927
- map2[host] = tokens;
49928
- file2.save(map2);
49930
+ file2.save({ [SHARED_KEY]: tokens });
49929
49931
  } catch (err) {
49930
49932
  reportCacheWriteFailure(err);
49931
49933
  }
49932
49934
  },
49933
49935
  clear() {
49934
49936
  try {
49935
- const map2 = file2.load();
49936
- if (map2 && host in map2) {
49937
- delete map2[host];
49938
- file2.save(map2);
49939
- }
49937
+ if (file2.load()) file2.save({});
49940
49938
  } catch (err) {
49941
49939
  reportCacheWriteFailure(err);
49942
49940
  }
@@ -49945,12 +49943,14 @@ function createSharePointTokenCache(env = process.env) {
49945
49943
  }
49946
49944
  };
49947
49945
  }
49946
+ var SHARED_KEY;
49948
49947
  var init_sharepoint_token_cache = __esm({
49949
49948
  "src/sharepoint-token-cache.ts"() {
49950
49949
  "use strict";
49951
49950
  init_session();
49952
49951
  init_dist2();
49953
49952
  init_token_cache();
49953
+ SHARED_KEY = "*";
49954
49954
  }
49955
49955
  });
49956
49956
 
@@ -49997,9 +49997,8 @@ function rememberSharePointHost(host, env = process.env) {
49997
49997
  reportCacheWriteFailure(err);
49998
49998
  }
49999
49999
  }
50000
- function withBridgeScope(opts, env, extraSharePointHost) {
50001
- const hosts = knownSharePointHosts(env);
50002
- if (extraSharePointHost !== void 0) hosts.push(extraSharePointHost);
50000
+ function withBridgeScope(opts, env, extraSharePointHosts = []) {
50001
+ const hosts = [...knownSharePointHosts(env), ...extraSharePointHosts];
50003
50002
  return {
50004
50003
  ...opts,
50005
50004
  domains: [...BRIDGE_TRUST_DOMAINS],
@@ -50073,7 +50072,7 @@ var init_auth_fetchproxy = __esm({
50073
50072
  DEFAULT_WS_PORT = 37149;
50074
50073
  TRUST_DOMAINS = [...BRIDGE_TRUST_DOMAINS];
50075
50074
  createCaptureTransport = (opts) => createFetchproxyTransport(opts);
50076
- bridgeScopedTransport = (env, sharePointHost) => (opts) => createCaptureTransport(withBridgeScope(opts, env, sharePointHost));
50075
+ bridgeScopedTransport = (env, sharePointHosts = []) => (opts) => createCaptureTransport(withBridgeScope(opts, env, sharePointHosts));
50077
50076
  }
50078
50077
  });
50079
50078
 
@@ -50091,38 +50090,70 @@ function captureHostFor(fileHost) {
50091
50090
  const m = /^([a-z0-9][a-z0-9-]*)\.sharepoint\.com$/.exec(h);
50092
50091
  return m ? `${m[1]}-my.sharepoint.com` : h;
50093
50092
  }
50094
- async function captureSharePointTokenViaFetchproxy(host, env = process.env) {
50095
- if (!isSharePointHost(host)) {
50093
+ async function captureSharePointTokenViaFetchproxy(hosts, env = process.env) {
50094
+ const list = [...new Set((typeof hosts === "string" ? [hosts] : [...hosts]).map((h) => h.toLowerCase()))];
50095
+ const bad = list.find((h) => !isSharePointHost(h));
50096
+ if (list.length === 0 || bad !== void 0) {
50096
50097
  throw new Error(
50097
- `refusing to capture a SharePoint token for ${JSON.stringify(host)}: not a *.sharepoint.com host`
50098
+ `refusing to capture a SharePoint token for ${JSON.stringify(bad ?? "")}: not a *.sharepoint.com host`
50098
50099
  );
50099
50100
  }
50100
- const token = await captureBearerHeader({
50101
- // The one request we capture from: any call the browser makes to this
50102
- // OneDrive host (the caller resolves it from the file's host via
50103
- // `captureHostFor`). A concrete host, never a wildcard — see the module note.
50104
- captures: [sharePointCaptureDecl(host)],
50105
- // The one bridge scope (`bridge-scope.ts`), with this host's capture added
50106
- // to the remembered ones so the hello asks for exactly what it is about to
50107
- // read.
50108
- domains: SHAREPOINT_TRUST_DOMAINS,
50109
- // Read per capture, not at import: see `capture-window.ts`.
50110
- windowMs: captureWindowMs(env),
50111
- port: getWsPort(),
50112
- serverName: PACKAGE_NAME,
50113
- version: VERSION,
50114
- what: `a SharePoint token for ${host}`,
50115
- guidance: `Reload your signed-in Teams tab and retry while it loads \u2014 that makes the page call ${host} with the SharePoint token we capture. Opening a file does not reliably do this.`,
50116
- createTransport: bridgeScopedTransport(env, host)
50117
- });
50118
- rememberSharePointHost(host, env);
50101
+ const label = list.join(" or ");
50102
+ let refused = false;
50103
+ const scoped = bridgeScopedTransport(env, list);
50104
+ let token;
50105
+ try {
50106
+ token = await captureBearerHeader({
50107
+ // Any call the browser makes to one of these hosts. Concrete hosts, never
50108
+ // a wildcard — see the module note.
50109
+ captures: list.map(sharePointCaptureDecl),
50110
+ // The one bridge scope (`bridge-scope.ts`), with these hosts' captures
50111
+ // added to the remembered ones so the hello asks for exactly what it is
50112
+ // about to read.
50113
+ domains: SHAREPOINT_TRUST_DOMAINS,
50114
+ // Read per capture, not at import: see `capture-window.ts`.
50115
+ windowMs: captureWindowMs(env),
50116
+ port: getWsPort(),
50117
+ serverName: PACKAGE_NAME,
50118
+ version: VERSION,
50119
+ what: `a SharePoint token for ${label}`,
50120
+ guidance: `Reload your signed-in Teams tab and retry while it loads \u2014 that makes the page call ${label} with the SharePoint token we capture.`,
50121
+ createTransport: (opts) => noteScopeRefusal(scoped(opts), () => refused = true)
50122
+ });
50123
+ } catch (err) {
50124
+ if (!refused) throw err;
50125
+ throw new McpToolError(`The ContextMint Bridge has not yet allowed a SharePoint token capture from ${label}.`, {
50126
+ hint: `Open the ContextMint Bridge extension popup and approve the pending scope update for ${PACKAGE_NAME}, which adds ${label} (no need to remove or re-pair it). Then retry, and reload your Teams tab while it waits.`,
50127
+ cause: err
50128
+ });
50129
+ }
50130
+ for (const h of list) rememberSharePointHost(h, env);
50119
50131
  return token;
50120
50132
  }
50133
+ function noteScopeRefusal(transport, onRefused) {
50134
+ const server = transport.server;
50135
+ const capture = server.captureRequestHeader.bind(server);
50136
+ return {
50137
+ start: () => transport.start(),
50138
+ close: () => transport.close(),
50139
+ server: {
50140
+ captureRequestHeader: async (...args) => {
50141
+ try {
50142
+ return await capture(...args);
50143
+ } catch (err) {
50144
+ if (err instanceof Error && err.name === "FetchproxyScopeError") onRefused();
50145
+ throw err;
50146
+ }
50147
+ }
50148
+ }
50149
+ };
50150
+ }
50121
50151
  var SHAREPOINT_TRUST_DOMAINS;
50122
50152
  var init_sharepoint_auth = __esm({
50123
50153
  "src/sharepoint-auth.ts"() {
50124
50154
  "use strict";
50125
50155
  init_fetchproxy();
50156
+ init_dist2();
50126
50157
  init_capture_window();
50127
50158
  init_auth_fetchproxy();
50128
50159
  init_bridge_scope();
@@ -50730,6 +50761,8 @@ function outcomeUnknown(method, e, hint) {
50730
50761
  }
50731
50762
  var SEND_OUTCOME_HINT = "The message may already have been posted \u2014 check the conversation (teams_list_messages) before retrying; do not resend blindly.";
50732
50763
  var REACTION_OUTCOME_HINT = "The reaction change may already have been applied \u2014 check the message (teams_list_messages) before retrying.";
50764
+ var THREAD_OUTCOME_HINT = "The change to the chat may already have been applied \u2014 check the chat (its name and members) before retrying.";
50765
+ var CREATE_OUTCOME_HINT = "A chat may already have been created \u2014 check teams_list_conversations before retrying; a blind retry would create a second chat (and a chat cannot be deleted).";
50733
50766
  var HORIZON_OUTCOME_HINT = "The read marker may already have moved \u2014 check the conversation (teams_list_messages) before retrying; moving it again to the same message is harmless.";
50734
50767
  var ChatServiceClient = class {
50735
50768
  #baseUrl;
@@ -50825,13 +50858,16 @@ var ChatServiceClient = class {
50825
50858
  async listConversations() {
50826
50859
  this.#requireConfigured();
50827
50860
  const out = [];
50861
+ const seen = /* @__PURE__ */ new Set();
50828
50862
  let url2 = `${this.#baseUrl}/users/ME/conversations?view=msnp24Equivalent&pageSize=200`;
50829
50863
  for (let page = 0; url2 !== void 0 && page < MAX_CONVERSATION_PAGES; page++) {
50830
50864
  const body = await this.#getJson(url2);
50831
50865
  const convs = body.conversations ?? [];
50832
50866
  if (convs.length === 0) break;
50833
50867
  for (const c of convs) {
50834
- if (typeof c?.id === "string" && (!c.id.startsWith("48:") || c.id === SELF_CHAT)) out.push(c);
50868
+ if (typeof c?.id !== "string" || c.id.startsWith("48:") && c.id !== SELF_CHAT || seen.has(c.id)) continue;
50869
+ seen.add(c.id);
50870
+ out.push(c);
50835
50871
  }
50836
50872
  url2 = this.#nextLink(body);
50837
50873
  }
@@ -50957,6 +50993,90 @@ var ChatServiceClient = class {
50957
50993
  const { status } = await this.#send(url2, "text", void 0, { method: "PUT", body, hint: HORIZON_OUTCOME_HINT });
50958
50994
  this.#checkWriteStatus("PUT", status, HORIZON_OUTCOME_HINT);
50959
50995
  }
50996
+ /**
50997
+ * A chat thread's topic and members (`GET /threads/{id}?view=msnp24Equivalent`,
50998
+ * verified live 2026-11-09). Members are MRIs and roles only.
50999
+ */
51000
+ async getThread(id) {
51001
+ this.#requireConfigured();
51002
+ return this.#getJson(`${this.#threadUrl(id)}?view=msnp24Equivalent`);
51003
+ }
51004
+ /**
51005
+ * Rename a group chat: `PUT /threads/{id}/properties?name=topic` with
51006
+ * `{ topic }` (verified live 2026-11-09: 200, `{}`). Teams posts a notice in
51007
+ * the chat. A lost answer is a `WriteOutcomeUnknownError`.
51008
+ */
51009
+ async setTopic(id, topic) {
51010
+ await this.#writeThread("PUT", `${this.#threadUrl(id)}/properties?name=topic`, { topic });
51011
+ }
51012
+ /**
51013
+ * Add someone to a group chat: `PUT /threads/{id}/members/{mri}` with
51014
+ * `{ role }` (verified live 2026-11-09). Repeating it is harmless.
51015
+ */
51016
+ async addMember(id, mri, role = "User") {
51017
+ await this.#writeThread("PUT", `${this.#threadUrl(id)}/members/${encodeURIComponent(mri)}`, { role });
51018
+ }
51019
+ /** Remove someone from a group chat: `DELETE /threads/{id}/members/{mri}`, no body (verified live 2026-11-09). */
51020
+ async removeMember(id, mri) {
51021
+ await this.#writeThread("DELETE", `${this.#threadUrl(id)}/members/${encodeURIComponent(mri)}`);
51022
+ }
51023
+ /**
51024
+ * Start a group chat: `POST /threads` with every member as `Admin` (Teams
51025
+ * makes every group-chat member Admin) and `{ threadType: "chat" }` plus the
51026
+ * topic when there is one (verified live 2026-11-09: 201, `{}`, and the new
51027
+ * id in `Location`). The signed-in user is always the first member.
51028
+ *
51029
+ * Not idempotent: an answer lost after sending (a timeout, a dropped
51030
+ * connection, a 5xx) is a `WriteOutcomeUnknownError` — the chat may exist,
51031
+ * and a retry would make a second one. A success without a readable
51032
+ * `Location` is an error too: the chat was probably made, its id unknown.
51033
+ */
51034
+ async createGroupChat(memberMris, topic) {
51035
+ this.#requireConfigured();
51036
+ const me = await this.meMri();
51037
+ const others = memberMris.filter((m) => m.toLowerCase() !== me.toLowerCase());
51038
+ const body = {
51039
+ members: [me, ...others].map((id2) => ({ id: id2, role: "Admin" })),
51040
+ properties: {
51041
+ threadType: "chat",
51042
+ ...topic ? { topic } : {},
51043
+ fixedRoster: false,
51044
+ uniquerosterthread: false
51045
+ }
51046
+ };
51047
+ const { status, headers } = await this.#send(`${this.#baseUrl}/threads`, "text", void 0, {
51048
+ method: "POST",
51049
+ body,
51050
+ hint: CREATE_OUTCOME_HINT
51051
+ });
51052
+ this.#checkWriteStatus("POST", status, CREATE_OUTCOME_HINT);
51053
+ const raw = /\/threads\/([^/?#]+)\/?(?:[?#].*)?$/.exec(headers.get("location") ?? "")?.[1];
51054
+ let id;
51055
+ try {
51056
+ id = raw !== void 0 ? decodeURIComponent(raw) : void 0;
51057
+ } catch {
51058
+ id = void 0;
51059
+ }
51060
+ if (!id) {
51061
+ throw new McpToolError(
51062
+ `Teams answered HTTP ${status} to creating the group chat, so it was probably created, but its id was not returned.`,
51063
+ {
51064
+ status,
51065
+ kind: "http",
51066
+ hint: "Find the new chat in teams_list_conversations (it has no messages yet) before trying again \u2014 do not retry blindly."
51067
+ }
51068
+ );
51069
+ }
51070
+ return { id };
51071
+ }
51072
+ #threadUrl(id) {
51073
+ return `${this.#baseUrl}/threads/${encodeURIComponent(id)}`;
51074
+ }
51075
+ async #writeThread(method, url2, body) {
51076
+ this.#requireConfigured();
51077
+ const { status } = await this.#send(url2, "text", void 0, { method, body, hint: THREAD_OUTCOME_HINT });
51078
+ this.#checkWriteStatus(method, status, THREAD_OUTCOME_HINT);
51079
+ }
50960
51080
  /**
50961
51081
  * Download an inline image (`<img src>` in a message body).
50962
51082
  *
@@ -51064,6 +51184,7 @@ var ChatServiceClient = class {
51064
51184
  async #send(url2, read, maxBytes, write) {
51065
51185
  let body = "";
51066
51186
  const method = write?.method ?? "GET";
51187
+ const payload = write?.body !== void 0 ? JSON.stringify(write.body) : void 0;
51067
51188
  const res = await this.#tokenManager().withAuth(async (token) => {
51068
51189
  const init = {
51069
51190
  method,
@@ -51073,9 +51194,9 @@ var ChatServiceClient = class {
51073
51194
  // a redirect to a sign-in page instead of a status we can act on.
51074
51195
  behavioroverride: "redirectAs404",
51075
51196
  accept: read === "text" ? "application/json" : "*/*",
51076
- ...write ? { "content-type": "application/json" } : {}
51197
+ ...payload !== void 0 ? { "content-type": "application/json" } : {}
51077
51198
  },
51078
- ...write ? { body: JSON.stringify(write.body) } : {},
51199
+ ...payload !== void 0 ? { body: payload } : {},
51079
51200
  // Never let a redirect carry the bearer somewhere we did not vet.
51080
51201
  redirect: "error"
51081
51202
  };
@@ -51183,9 +51304,10 @@ var ChatServiceClient = class {
51183
51304
  init_dist2();
51184
51305
  init_session();
51185
51306
  init_sharepoint_token_cache();
51186
- async function captureSharePointTokenLazily(host) {
51307
+ init_bridge_scope();
51308
+ async function captureSharePointTokenLazily(hosts) {
51187
51309
  const mod = await Promise.resolve().then(() => (init_sharepoint_auth(), sharepoint_auth_exports));
51188
- return mod.captureSharePointTokenViaFetchproxy(host);
51310
+ return mod.captureSharePointTokenViaFetchproxy(hosts);
51189
51311
  }
51190
51312
  var REQUEST_TIMEOUT_MS2 = 6e4;
51191
51313
  async function reachable(url2, run) {
@@ -51198,6 +51320,7 @@ async function reachable(url2, run) {
51198
51320
  var SharePointClient = class {
51199
51321
  #env;
51200
51322
  #capture;
51323
+ #knownHosts;
51201
51324
  #fetchImpl;
51202
51325
  #cache;
51203
51326
  /**
@@ -51205,11 +51328,14 @@ var SharePointClient = class {
51205
51328
  * still boots (and answers `tools/list`) with no credential present.
51206
51329
  */
51207
51330
  #configError = null;
51208
- /** One `TokenManager` per SharePoint host — SP tokens are host-scoped. */
51209
- #managers = /* @__PURE__ */ new Map();
51331
+ /** The one `TokenManager`: one SharePoint token serves every host of the tenant. */
51332
+ #manager = null;
51333
+ /** The capture host of the file being fetched — where a first-ever capture looks. */
51334
+ #fileCaptureHost = "";
51210
51335
  constructor(opts = {}) {
51211
51336
  this.#env = opts.env ?? process.env;
51212
51337
  this.#capture = opts.captureToken ?? captureSharePointTokenLazily;
51338
+ this.#knownHosts = opts.knownHosts ?? (() => knownSharePointHosts(this.#env));
51213
51339
  this.#fetchImpl = opts.fetchImpl ?? ((input2, init) => fetch(input2, init));
51214
51340
  this.#cache = createSharePointTokenCache(this.#env);
51215
51341
  if (parseBoolEnv("TEAMS_DISABLE_FETCHPROXY", { env: this.#env })) {
@@ -51250,10 +51376,10 @@ var SharePointClient = class {
51250
51376
  });
51251
51377
  }
51252
51378
  const { captureHostFor: captureHostFor2 } = await Promise.resolve().then(() => (init_sharepoint_auth(), sharepoint_auth_exports));
51253
- const captureHost = captureHostFor2(host);
51379
+ this.#fileCaptureHost = captureHostFor2(host);
51254
51380
  const share = `u!${Buffer.from(objectUrl, "utf8").toString("base64url")}`;
51255
51381
  const driveItemUrl = `https://${host}/_api/v2.1/shares/${share}/driveItem?$select=id,size,@content.downloadUrl`;
51256
- const meta3 = await this.#getDriveItem(captureHost, driveItemUrl);
51382
+ const meta3 = await this.#getDriveItem(driveItemUrl);
51257
51383
  if (typeof meta3.size === "number" && meta3.size > maxBytes) {
51258
51384
  const mb = (n) => `${Math.round(n / (1024 * 1024))} MB`;
51259
51385
  throw new McpToolError(`The file is ${mb(meta3.size)}, larger than the ${mb(maxBytes)} download limit.`, {
@@ -51273,16 +51399,23 @@ var SharePointClient = class {
51273
51399
  #requireConfigured() {
51274
51400
  if (this.#configError) throw this.#configError;
51275
51401
  }
51276
- /** The `TokenManager` for `host`, created (and cached) on first use. */
51277
- #managerFor(host) {
51278
- const existing = this.#managers.get(host);
51279
- if (existing) return existing;
51280
- const mgr = createCapturedTokenManager({
51281
- capture: () => this.#capture(host),
51282
- persistence: this.#cache?.forHost(host) ?? null
51402
+ /**
51403
+ * Where to capture the token from: the hosts the bridge has already granted
51404
+ * (any of them yields a token every host accepts), or this file's OneDrive
51405
+ * host when none has been. Declaring a new host when a granted one would do
51406
+ * only widens the bridge scope, which the extension refuses until approved.
51407
+ */
51408
+ #captureHosts() {
51409
+ const known = this.#knownHosts();
51410
+ return known.length > 0 ? known : [this.#fileCaptureHost];
51411
+ }
51412
+ /** The one `TokenManager`, created on first use. */
51413
+ #tokens() {
51414
+ this.#manager ??= createCapturedTokenManager({
51415
+ capture: () => this.#capture(this.#captureHosts()),
51416
+ persistence: this.#cache?.shared() ?? null
51283
51417
  });
51284
- this.#managers.set(host, mgr);
51285
- return mgr;
51418
+ return this.#manager;
51286
51419
  }
51287
51420
  /**
51288
51421
  * The authed driveItem GET, with chatsvc's discipline: `behavioroverride:
@@ -51291,9 +51424,9 @@ var SharePointClient = class {
51291
51424
  * `TokenManager.withAuth` supplies the token and, on a 401, re-captures once
51292
51425
  * and replays once — so a 401 that reaches here is the second one.
51293
51426
  */
51294
- async #getDriveItem(captureHost, url2) {
51427
+ async #getDriveItem(url2) {
51295
51428
  let body = "";
51296
- const res = await this.#managerFor(captureHost).withAuth(async (token) => {
51429
+ const res = await this.#tokens().withAuth(async (token) => {
51297
51430
  const r = await reachable(
51298
51431
  url2,
51299
51432
  () => fetchBounded(
@@ -51318,7 +51451,7 @@ var SharePointClient = class {
51318
51451
  throw new McpToolError("SharePoint refused access to the file (403).", {
51319
51452
  status,
51320
51453
  kind: "http",
51321
- hint: "Your account cannot open this file, or it is on a SharePoint host your captured token does not cover. Open it once in Teams, then retry."
51454
+ hint: "Your account cannot open this file. Ask whoever shared it to give you access, then retry."
51322
51455
  });
51323
51456
  }
51324
51457
  if (status === 404) {
@@ -51439,6 +51572,9 @@ function createSubstrateTokenCache(env = process.env) {
51439
51572
 
51440
51573
  // src/substrate.ts
51441
51574
  var SUBSTRATE_QUERY_URL = "https://substrate.office.com/searchservice/api/v2/query";
51575
+ var SUBSTRATE_SUGGESTIONS_URL = "https://substrate.office.com/search/api/v1/suggestions?scenario=powerbar";
51576
+ var DEFAULT_SUGGESTIONS = 10;
51577
+ var MAX_SUGGESTIONS = 25;
51442
51578
  var CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1e3;
51443
51579
  var REQUEST_TIMEOUT_MS3 = 3e4;
51444
51580
  var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
@@ -51545,6 +51681,55 @@ function parseQueryResponse(body) {
51545
51681
  unmapped
51546
51682
  };
51547
51683
  }
51684
+ function buildSuggestionsBody(text, size) {
51685
+ return {
51686
+ EntityRequests: [{ EntityType: "People", Query: { QueryString: text }, Size: size }],
51687
+ Cvid: crypto.randomUUID(),
51688
+ LogicalId: crypto.randomUUID(),
51689
+ Scenario: { Name: "powerbar" }
51690
+ };
51691
+ }
51692
+ var GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
51693
+ var ORGID_MRI = /^8:orgid:\S+$/i;
51694
+ function mapSuggestion(raw) {
51695
+ const r = obj(raw);
51696
+ if (r === void 0) return void 0;
51697
+ const subtype = str(r.PeopleSubtype);
51698
+ if (subtype !== void 0 && subtype !== "OrganizationUser") return void 0;
51699
+ const mriField = str(r.MRI)?.trim();
51700
+ const oid = str(r.ExternalDirectoryObjectId)?.trim();
51701
+ const mri = mriField !== void 0 && ORGID_MRI.test(mriField) ? mriField : oid !== void 0 && GUID.test(oid) ? `8:orgid:${oid.toLowerCase()}` : void 0;
51702
+ if (mri === void 0) return void 0;
51703
+ const email3 = Array.isArray(r.EmailAddresses) ? r.EmailAddresses.map(str).find((e) => e !== void 0) : void 0;
51704
+ const upn = str(r.UserPrincipalName);
51705
+ const name = str(r.DisplayName)?.trim() ?? email3 ?? upn ?? mri;
51706
+ const jobTitle = str(r.JobTitle);
51707
+ const department = str(r.Department);
51708
+ return {
51709
+ mri,
51710
+ name,
51711
+ ...email3 !== void 0 ? { email: email3 } : {},
51712
+ ...upn !== void 0 ? { upn } : {},
51713
+ ...jobTitle !== void 0 ? { jobTitle } : {},
51714
+ ...department !== void 0 ? { department } : {}
51715
+ };
51716
+ }
51717
+ function parseSuggestionsResponse(body) {
51718
+ const groups = obj(body)?.Groups;
51719
+ if (!Array.isArray(groups)) return [];
51720
+ const byMri = /* @__PURE__ */ new Map();
51721
+ for (const g of groups) {
51722
+ const group = obj(g);
51723
+ if (group?.Type !== "People" || !Array.isArray(group.Suggestions)) continue;
51724
+ for (const raw of group.Suggestions) {
51725
+ const p = mapSuggestion(raw);
51726
+ if (p !== void 0 && !byMri.has(p.mri.toLowerCase())) byMri.set(p.mri.toLowerCase(), p);
51727
+ }
51728
+ }
51729
+ return [...byMri.values()];
51730
+ }
51731
+ var SEARCH = { url: SUBSTRATE_QUERY_URL, service: "Substrate search", plural: "searches" };
51732
+ var PEOPLE = { url: SUBSTRATE_SUGGESTIONS_URL, service: "Substrate people lookup", plural: "people lookups" };
51548
51733
  var SubstrateClient = class {
51549
51734
  #fetchImpl;
51550
51735
  #configError = null;
@@ -51584,15 +51769,35 @@ var SubstrateClient = class {
51584
51769
  return this.#configError === null;
51585
51770
  }
51586
51771
  async searchMessages(req, opts = {}) {
51772
+ return parseQueryResponse(await this.#post(SEARCH, buildQueryBody(req), opts.force === true));
51773
+ }
51774
+ /**
51775
+ * People in the directory matching `text` (a name, part of one, or an
51776
+ * address), as Teams' search box suggests them — only those who can be a
51777
+ * chat member (see {@link parseSuggestionsResponse}). Blank text asks nothing.
51778
+ */
51779
+ async suggestPeople(text, opts = {}) {
51780
+ const q = text.trim();
51781
+ if (q === "") return [];
51782
+ const size = Math.min(Math.max(1, Math.floor(opts.size ?? DEFAULT_SUGGESTIONS)), MAX_SUGGESTIONS);
51783
+ return parseSuggestionsResponse(await this.#post(PEOPLE, buildSuggestionsBody(q, size), opts.force === true));
51784
+ }
51785
+ /**
51786
+ * POST `body` to Substrate with the captured token and return the parsed
51787
+ * JSON: the config error, the capture cooldown (unless `force`), one
51788
+ * re-capture on a 401, a bounded read, no redirects, and the status mapped
51789
+ * to an `McpToolError` — the body is never echoed.
51790
+ */
51791
+ async #post(lookup, body, force) {
51587
51792
  if (this.#configError) throw this.#configError;
51588
51793
  const failed = this.#captureFailure;
51589
- if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS) throw failed.error;
51794
+ if (!force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS) throw failed.error;
51590
51795
  let text = "";
51591
51796
  const res = await this.#manager.withAuth(async (token) => {
51592
51797
  let r;
51593
51798
  try {
51594
51799
  r = await fetchBounded(
51595
- SUBSTRATE_QUERY_URL,
51800
+ lookup.url,
51596
51801
  {
51597
51802
  method: "POST",
51598
51803
  headers: {
@@ -51600,7 +51805,7 @@ var SubstrateClient = class {
51600
51805
  "content-type": "application/json",
51601
51806
  accept: "application/json"
51602
51807
  },
51603
- body: JSON.stringify(buildQueryBody(req)),
51808
+ body: JSON.stringify(body),
51604
51809
  redirect: "error"
51605
51810
  },
51606
51811
  {
@@ -51612,25 +51817,25 @@ var SubstrateClient = class {
51612
51817
  }
51613
51818
  );
51614
51819
  } catch (e) {
51615
- throw describeTransportFailure2(e, SUBSTRATE_QUERY_URL, "Substrate search") ?? e;
51820
+ throw describeTransportFailure2(e, lookup.url, lookup.service) ?? e;
51616
51821
  }
51617
51822
  text = r.body;
51618
51823
  return r.res;
51619
51824
  });
51620
51825
  try {
51621
- checkStatus(res.status);
51826
+ checkStatus(res.status, lookup);
51622
51827
  } catch (error62) {
51623
51828
  if (res.status === 401) this.#captureFailure = { at: Date.now(), error: error62 };
51624
51829
  throw error62;
51625
51830
  }
51626
51831
  try {
51627
- return parseQueryResponse(JSON.parse(text));
51832
+ return JSON.parse(text);
51628
51833
  } catch {
51629
51834
  throw new McpToolError("Substrate returned a response that is not JSON.", { status: res.status, kind: "http" });
51630
51835
  }
51631
51836
  }
51632
51837
  };
51633
- function checkStatus(status) {
51838
+ function checkStatus(status, lookup) {
51634
51839
  if (status >= 200 && status < 300) return;
51635
51840
  if (status === 401) {
51636
51841
  throw new McpToolError("Substrate rejected the search token (401) even after a fresh capture.", {
@@ -51640,9 +51845,13 @@ function checkStatus(status) {
51640
51845
  });
51641
51846
  }
51642
51847
  if (status === 429) {
51643
- throw new McpToolError("Substrate is rate-limiting searches (429).", { status, kind: "http", hint: "Wait a minute before retrying." });
51848
+ throw new McpToolError(`Substrate is rate-limiting ${lookup.plural} (429).`, {
51849
+ status,
51850
+ kind: "http",
51851
+ hint: "Wait a minute before retrying."
51852
+ });
51644
51853
  }
51645
- throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
51854
+ throw new McpToolError(`${lookup.service} returned HTTP ${status}.`, {
51646
51855
  status,
51647
51856
  kind: "http",
51648
51857
  ...status >= 500 ? { hint: "A Substrate-side failure; retry shortly." } : {}
@@ -52594,10 +52803,10 @@ function renderMessageHtml(text, mentions) {
52594
52803
  let at = 0;
52595
52804
  const out = [];
52596
52805
  placed.forEach((p, n) => {
52597
- const shown2 = text.slice(p.start, p.end).replace(/^@/, "");
52806
+ const shown3 = text.slice(p.start, p.end).replace(/^@/, "");
52598
52807
  html += renderPlain(text.slice(at, p.start));
52599
- html += `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown2)}</span>`;
52600
- out.push({ itemid: String(n), mri: p.mri, displayName: shown2 });
52808
+ html += `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown3)}</span>`;
52809
+ out.push({ itemid: String(n), mri: p.mri, displayName: shown3 });
52601
52810
  at = p.end;
52602
52811
  });
52603
52812
  html += renderPlain(text.slice(at));
@@ -53207,25 +53416,25 @@ async function unreadFrom(chatsvc, raw, me, candidates, pos, { limit, timeZone,
53207
53416
  if (failed.length > 0 && !anyRead) throw failed[0].error;
53208
53417
  const listed = Math.max(pos.t, ...raw.map((c) => lastChangeMs(c) ?? 0));
53209
53418
  const { page, has_more, remaining, next } = takePage(items, pos, limit, failed.length > 0 ? pos.t : listed);
53210
- const shown2 = [...new Map(page.map(({ summary }) => [summary.id, summary])).values()];
53419
+ const shown3 = [...new Map(page.map(({ summary }) => [summary.id, summary])).values()];
53211
53420
  const titled = await enrichTitles(chatsvc, raw, me, [
53212
- ...shown2,
53421
+ ...shown3,
53213
53422
  ...failed.map((f) => f.summary),
53214
53423
  ...tooDeep.map((d) => d.summary)
53215
53424
  ]);
53216
- const titledDeep = titled.slice(shown2.length + failed.length);
53425
+ const titledDeep = titled.slice(shown3.length + failed.length);
53217
53426
  return {
53218
53427
  total_unread: page.length + remaining,
53219
53428
  messages: page.map(({ summary, m }) => ({
53220
53429
  conversation_id: summary.id,
53221
53430
  ...formatFlatMessage(normaliseMessage(m, me, { timeZone }), format)
53222
53431
  })),
53223
- conversations: titled.slice(0, shown2.length).map((s) => formatConversation(confirmedSummary(s, true), format)),
53432
+ conversations: titled.slice(0, shown3.length).map((s) => formatConversation(confirmedSummary(s, true), format)),
53224
53433
  ...fromReport(pos, next, has_more),
53225
53434
  skipped_unreachable: skippedUnreachable,
53226
53435
  ...failed.length > 0 ? {
53227
53436
  errors: failed.map((f, i) => ({
53228
- conversation: titled[shown2.length + i],
53437
+ conversation: titled[shown3.length + i],
53229
53438
  error: wrapApiError(f.error, "read this conversation").message
53230
53439
  }))
53231
53440
  } : {},
@@ -53369,17 +53578,17 @@ function registerUnreadTools(server, { chatsvc }) {
53369
53578
  marks = await applyMarks(chatsvc, plans);
53370
53579
  }
53371
53580
  const budget = rootBudget();
53372
- const shown2 = returned.map(({ summary, read }) => ({
53581
+ const shown3 = returned.map(({ summary, read }) => ({
53373
53582
  summary,
53374
53583
  read,
53375
53584
  messages: oldestFirst(read.messages).map((m) => normaliseMessage(m, me, { timeZone }))
53376
53585
  }));
53377
53586
  const roots = await mapWithConcurrency(
53378
- shown2,
53587
+ shown3,
53379
53588
  ROOT_CONVERSATION_CONCURRENCY,
53380
53589
  ({ summary, messages }) => summary.kind === "channel" ? fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget, timeZone }) : Promise.resolve(void 0)
53381
53590
  );
53382
- const conversations = shown2.map(({ summary, read, messages }, i) => ({
53591
+ const conversations = shown3.map(({ summary, read, messages }, i) => ({
53383
53592
  conversation: formatConversation(confirmedSummary(summary, true), format ?? "full"),
53384
53593
  unread_count: messages.length,
53385
53594
  ...formatBody(summary.kind, messages, format ?? "full", roots[i]),
@@ -53505,8 +53714,8 @@ function briefLine(title, time3, status) {
53505
53714
  const flat = title.replace(/\s+/g, " ").trim() || "(untitled)";
53506
53715
  const escaped = flat.startsWith("-- ") || flat.startsWith("\\") ? `\\${flat}` : flat;
53507
53716
  const room = BRIEF_MAX - tail.length;
53508
- const shown2 = escaped.length > room ? `${escaped.slice(0, Math.max(room - 1, 0)).trimEnd()}\u2026` : escaped;
53509
- return `${shown2}${tail}`;
53717
+ const shown3 = escaped.length > room ? `${escaped.slice(0, Math.max(room - 1, 0)).trimEnd()}\u2026` : escaped;
53718
+ return `${shown3}${tail}`;
53510
53719
  }
53511
53720
  var BRIEF_NOTE = `Conversation titles below are set by other people in Microsoft Teams. ${UNTRUSTED_CONTENT_RULE}`;
53512
53721
  function briefResult(lines, failed) {
@@ -53576,15 +53785,15 @@ function registerChangesTools(server, { chatsvc }) {
53576
53785
  const listed = Math.max(t, ...[...lastChange.values()].map((n) => n ?? 0));
53577
53786
  const next = failed.length > 0 ? t : Math.min(maxSeen, listed);
53578
53787
  const cap = limit ?? DEFAULT_LIMIT;
53579
- const shown2 = changed.slice(0, cap);
53788
+ const shown3 = changed.slice(0, cap);
53580
53789
  const rest = changed.slice(cap);
53581
53790
  const titled = await enrichTitles(chatsvc, raw, me, [
53582
- ...shown2.map((c) => c.summary),
53791
+ ...shown3.map((c) => c.summary),
53583
53792
  ...rest.map((c) => c.summary),
53584
53793
  ...failed.map((f) => f.summary)
53585
53794
  ]);
53586
53795
  const after_message_id = String(Math.floor(t));
53587
- const conversations = shown2.map(({ read }, i) => ({
53796
+ const conversations = shown3.map(({ read }, i) => ({
53588
53797
  conversation: titled[i],
53589
53798
  new_message_count: read.count,
53590
53799
  new_from_others_count: read.fromOthers,
@@ -53594,9 +53803,9 @@ function registerChangesTools(server, { chatsvc }) {
53594
53803
  ...read.truncated ? { truncated: true } : {}
53595
53804
  }));
53596
53805
  const more = rest.map(({ read }, i) => ({
53597
- id: titled[shown2.length + i].id,
53598
- title: titled[shown2.length + i].title,
53599
- ...participantsOf(titled[shown2.length + i]),
53806
+ id: titled[shown3.length + i].id,
53807
+ title: titled[shown3.length + i].title,
53808
+ ...participantsOf(titled[shown3.length + i]),
53600
53809
  new_message_count: read.count,
53601
53810
  after_message_id
53602
53811
  }));
@@ -55045,22 +55254,27 @@ function registerExportTools(server, deps2, opts = {}) {
55045
55254
  // src/tools/attachment.ts
55046
55255
  var MAX_RAW_MESSAGES4 = 4e3;
55047
55256
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
55048
- var FILE_HINT = "A shared file is downloaded from SharePoint and returned as its contents (an image as an image, anything else as an embedded resource; over 10 MiB as a download link, or a saved file on a local install). The first file from a given SharePoint host may need your Teams tab reloaded to mint a short-lived token; a file your account cannot open comes back as metadata and its link.";
55257
+ var FILE_HINT = "A shared file is downloaded from SharePoint and returned as its contents (an image as an image, anything else as an embedded resource; over 10 MiB, or with save, as a download link or a saved file on a local install). The first download may need your Teams tab reloaded to capture a SharePoint token; a file your account cannot open comes back as metadata and its link.";
55049
55258
  function registerAttachmentTools(server, { chatsvc, sharepoint }) {
55050
55259
  server.registerTool(
55051
55260
  "teams_get_attachment",
55052
55261
  {
55053
55262
  title: "Get a Teams message attachment",
55054
- description: `Fetch one attachment of a Teams chat or channel message, as listed by teams_list_messages / teams_list_unread_messages. An inline image (attachments.images[].ref) is returned as the image itself. A shared file (attachments.files[].name) is downloaded from SharePoint and returned as its contents: an image as the image, anything else as an embedded resource carrying the bytes. Anything over 10 MiB comes back instead as a signed, expiring download link (downloadUrl) on a hosted install, or saved to a fresh file (path) under ${EXPORT_OUTPUT_ENV}, else ~/Downloads/${EXPORT_SERVER_NAME}, on a local one; the caption's via says which. The first file from a given SharePoint host in a session may need your Teams tab reloaded to mint a short-lived token; a file your account cannot open, or one that could not be fetched, comes back as metadata and its open link instead of failing. Its caption names the conversation beside its id: title (as teams_list_conversations names it \u2014 an untitled group chat by its participants, a 1:1 by the other person) and participants. Does not mark anything read.` + UNTRUSTED_DESCRIPTION_SUFFIX2,
55263
+ description: `Fetch one attachment of a Teams chat or channel message, as listed by teams_list_messages / teams_list_unread_messages. ref names it: an inline image's ref (attachments.images[].ref) or a shared file's name (attachments.files[].name), matched ignoring case and, for a file, with or without its extension. An inline image is returned as the image itself. A shared file is downloaded from SharePoint and returned as its contents: an image as the image, anything else as an embedded resource carrying the bytes. Anything over 10 MiB comes back instead as a signed, expiring download link (downloadUrl) on a hosted install, or saved to a fresh file (path) under ${EXPORT_OUTPUT_ENV}, else ~/Downloads/${EXPORT_SERVER_NAME}, on a local one; the caption's via says which. save: true does the same for any size \u2014 use it when the user wants the file itself rather than its contents read here. The first download may need your Teams tab reloaded to capture a short-lived SharePoint token, which then serves every SharePoint host; a file your account cannot open, or one that could not be fetched, comes back as metadata and its open link instead of failing. Its caption names the conversation beside its id: title (as teams_list_conversations names it \u2014 an untitled group chat by its participants, a 1:1 by the other person) and participants. Does not mark anything read.` + UNTRUSTED_DESCRIPTION_SUFFIX2,
55055
55264
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
55056
55265
  _meta: workMeta("other", { aliases: ["attachment", "image", "file", "screenshot"] }),
55057
55266
  inputSchema: {
55058
55267
  conversation: external_exports.string().min(1).describe("The conversation id the message is in (from teams_list_messages or teams_list_unread_messages)."),
55059
55268
  message_id: external_exports.string().min(1).describe("The message id, exactly as a message listing returned it."),
55060
- ref: external_exports.string().min(1).describe("An inline image's ref (attachments.images[].ref) or a shared file's name (attachments.files[].name).")
55269
+ ref: external_exports.string().min(1).describe(
55270
+ "An inline image's ref (attachments.images[].ref) or a shared file's name (attachments.files[].name). Case is ignored, and a file may be named without its extension."
55271
+ ),
55272
+ save: external_exports.boolean().optional().describe(
55273
+ `Save the attachment to a fresh file under ${EXPORT_OUTPUT_ENV} (else ~/Downloads/${EXPORT_SERVER_NAME}) and return its path instead of its contents; a hosted install returns a download link instead. Default false.`
55274
+ )
55061
55275
  }
55062
55276
  },
55063
- async ({ conversation, message_id, ref }) => {
55277
+ async ({ conversation, message_id, ref, save = false }) => {
55064
55278
  try {
55065
55279
  const target = Number(message_id);
55066
55280
  const stopAt = Number.isFinite(target) && target > 0 ? (m) => Number(m.id) < target : void 0;
@@ -55073,15 +55287,16 @@ function registerAttachmentTools(server, { chatsvc, sharepoint }) {
55073
55287
  }
55074
55288
  const message = normaliseMessage(raw, "");
55075
55289
  const naming = nameConversations(chatsvc, [conversation]).then((names) => nameFields(names.get(conversation)));
55076
- const image = message.attachments.images.find((i) => i.ref === ref);
55077
- if (image !== void 0) {
55290
+ const found = findAttachment(message, ref, message_id);
55291
+ if (found.kind === "image") {
55292
+ const image = found.image;
55078
55293
  const { mimeType, data } = await chatsvc.fetchImage(image.url);
55079
55294
  if (!mimeType.startsWith("image/")) {
55080
- throw new McpToolError(`The attachment ${ref} is not an image (the image store returned ${mimeType}).`);
55295
+ throw new McpToolError(`The attachment ${image.ref} is not an image (the image store returned ${mimeType}).`);
55081
55296
  }
55082
- const delivered = await deliver(data, imageFileName(ref, mimeType), mimeType);
55297
+ const delivered = await deliver(data, imageFileName(image.ref, mimeType), mimeType, save);
55083
55298
  const caption = untrustedResult2({
55084
- ref,
55299
+ ref: image.ref,
55085
55300
  message_id,
55086
55301
  conversation,
55087
55302
  ...await naming,
@@ -55093,21 +55308,14 @@ function registerAttachmentTools(server, { chatsvc, sharepoint }) {
55093
55308
  });
55094
55309
  return { content: [...delivered.content, ...caption.content] };
55095
55310
  }
55096
- const file2 = message.attachments.files.find((f) => f.name === ref);
55097
- if (file2 !== void 0) {
55098
- return downloadSharedFile(sharepoint, file2, message, { conversation, message_id }, naming);
55099
- }
55100
- const { images, files } = message.attachments;
55101
- throw new McpToolError(`Message ${message_id} has no attachment "${ref}".`, {
55102
- hint: `It has ${images.length} inline image(s) and ${files.length} shared file(s); pass an image ref or a file name exactly as teams_list_messages listed it.`
55103
- });
55311
+ return downloadSharedFile(sharepoint, found.file, message, { conversation, message_id }, naming, save);
55104
55312
  } catch (err) {
55105
55313
  throw wrapApiError(err, "get the attachment");
55106
55314
  }
55107
55315
  }
55108
55316
  );
55109
55317
  }
55110
- async function downloadSharedFile(sharepoint, file2, message, ids, naming) {
55318
+ async function downloadSharedFile(sharepoint, file2, message, ids, naming, save) {
55111
55319
  if (file2.url === void 0) {
55112
55320
  return untrustedResult2({ ...file2, content_available: false, hint: FILE_HINT });
55113
55321
  }
@@ -55119,7 +55327,7 @@ async function downloadSharedFile(sharepoint, file2, message, ids, naming) {
55119
55327
  }
55120
55328
  let delivered;
55121
55329
  try {
55122
- delivered = await deliver(downloaded.data, file2.name, downloaded.mimeType);
55330
+ delivered = await deliver(downloaded.data, file2.name, downloaded.mimeType, save);
55123
55331
  } catch (err) {
55124
55332
  if (err instanceof McpToolError && file2.openUrl !== void 0) {
55125
55333
  throw new McpToolError(err.message, {
@@ -55153,12 +55361,46 @@ async function downloadSharedFile(sharepoint, file2, message, ids, naming) {
55153
55361
  );
55154
55362
  return { content: [...content, ...caption.content] };
55155
55363
  }
55156
- function deliver(bytes, fileName, mimeType) {
55364
+ function withoutExtension(name) {
55365
+ const dot = name.lastIndexOf(".");
55366
+ return dot > 0 ? name.slice(0, dot) : name;
55367
+ }
55368
+ function findAttachment(message, ref, messageId2) {
55369
+ const { images, files } = message.attachments;
55370
+ const all = [
55371
+ ...images.map((image) => ({ kind: "image", image })),
55372
+ ...files.map((file2) => ({ kind: "file", file: file2 }))
55373
+ ];
55374
+ const nameOf = (a) => a.kind === "image" ? a.image.ref : a.file.name;
55375
+ const lower = ref.toLowerCase();
55376
+ const rules = [
55377
+ (a) => nameOf(a) === ref,
55378
+ (a) => nameOf(a).toLowerCase() === lower,
55379
+ (a) => a.kind === "file" && withoutExtension(a.file.name).toLowerCase() === lower
55380
+ ];
55381
+ for (const rule of rules) {
55382
+ const hits = all.filter(rule);
55383
+ if (hits.length === 1) return hits[0];
55384
+ if (hits.length > 1) {
55385
+ throw new McpToolError(`"${ref}" matches ${hits.length} attachments of message ${messageId2}.`, {
55386
+ hint: `Pass one of them exactly: ${hits.map((h) => JSON.stringify(nameOf(h))).join(", ")}.`
55387
+ });
55388
+ }
55389
+ }
55390
+ const names = files.map((f) => JSON.stringify(f.name));
55391
+ throw new McpToolError(`Message ${messageId2} has no attachment "${ref}".`, {
55392
+ hint: `It has ${images.length} inline image(s) and ${files.length} shared file(s)` + (names.length > 0 ? ` (${names.join(", ")})` : "") + "; pass an image ref or a file name as teams_list_messages listed it."
55393
+ });
55394
+ }
55395
+ function deliver(bytes, fileName, mimeType, save) {
55157
55396
  return deliverFile({
55158
55397
  bytes,
55159
55398
  fileName,
55160
55399
  mimeType,
55161
55400
  keyPrefix: "attachments",
55401
+ // `save` asks for a file rather than the contents; on a hosted install
55402
+ // deliverFile turns the disk route into a link, saying why in `note`.
55403
+ ...save ? { prefer: "disk" } : {},
55162
55404
  ...isHostedEnv() ? {} : { disk: { dir: downloadDir() } }
55163
55405
  });
55164
55406
  }
@@ -55192,7 +55434,7 @@ function hostOf2(url2) {
55192
55434
  }
55193
55435
  function degradeHint(err, host) {
55194
55436
  if (errorStatusOf(err) === 403) {
55195
- return `Your account cannot open this file, or it is on a SharePoint host (${host}) your captured token does not cover. Open it once in a signed-in Teams tab, then retry.`;
55437
+ return `Your account cannot open this file on ${host}. Ask whoever shared it to give you access, then retry.`;
55196
55438
  }
55197
55439
  if (errorKindOf(err) === "no_credential") {
55198
55440
  return "SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.";
@@ -55208,12 +55450,173 @@ function degradeHint(err, host) {
55208
55450
  // src/tools/send.ts
55209
55451
  init_zod();
55210
55452
  init_dist2();
55211
- var TOOL2 = "teams_send_message";
55453
+
55454
+ // src/tools/people.ts
55455
+ init_dist2();
55456
+ var MRI = /^\d+:\S+$/;
55457
+ var GUID2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
55212
55458
  var RECENT_MESSAGES = 200;
55213
- var READBACK_MESSAGES = 50;
55214
55459
  var MAX_CANDIDATES2 = 10;
55460
+ function personMri(input2) {
55461
+ const s = input2.trim();
55462
+ if (MRI.test(s)) return s;
55463
+ if (GUID2.test(s)) return `8:orgid:${s.toLowerCase()}`;
55464
+ return void 0;
55465
+ }
55466
+ function normaliseName(name) {
55467
+ const s = name.trim().toLowerCase().replace(/\s+/g, " ");
55468
+ const m = /^([^,]+),\s*([^,]+)$/.exec(s);
55469
+ return m ? `${m[2].trim()} ${m[1].trim()}` : s;
55470
+ }
55471
+ async function recentSenders(chatsvc, conversationId) {
55472
+ const out = /* @__PURE__ */ new Map();
55473
+ for (const m of await chatsvc.getMessages(conversationId, { max: RECENT_MESSAGES })) {
55474
+ const mri = senderMri(m.from);
55475
+ const name = m.imdisplayname?.trim();
55476
+ if (isUserMessage(m) && mri !== void 0 && name && !out.has(mri)) out.set(mri, name);
55477
+ }
55478
+ return out;
55479
+ }
55480
+ async function knownPeople(chatsvc, me, conversationId) {
55481
+ const byMri = /* @__PURE__ */ new Map();
55482
+ const add = (mri, name) => {
55483
+ const key = mri.toLowerCase();
55484
+ if (name.trim() && !byMri.has(key)) byMri.set(key, { mri, name: name.trim() });
55485
+ };
55486
+ try {
55487
+ const raw = await chatsvc.listConversations();
55488
+ const oneOnOnes = summariseAll(raw, me).filter((s) => s.kind === "oneOnOne");
55489
+ for (const s of await enrichTitles(chatsvc, raw, me, oneOnOnes)) {
55490
+ const peer = oneOnOnePeerMri(s.id, me);
55491
+ const name = s.participants?.[0];
55492
+ if (peer !== void 0 && name !== void 0) add(peer, name);
55493
+ }
55494
+ } catch {
55495
+ }
55496
+ if (conversationId === void 0) return [...byMri.values()];
55497
+ try {
55498
+ for (const [mri, name] of await recentSenders(chatsvc, conversationId)) add(mri, name);
55499
+ } catch {
55500
+ }
55501
+ return [...byMri.values()];
55502
+ }
55503
+ function knownName(mri, known) {
55504
+ const key = mri.toLowerCase();
55505
+ return known.find((k) => k.mri.toLowerCase() === key)?.name;
55506
+ }
55507
+ function isEmail(input2) {
55508
+ return /^[^@\s]+@[^@\s]+$/.test(input2.trim());
55509
+ }
55510
+ function candidateList(people) {
55511
+ return people.slice(0, MAX_CANDIDATES2).map((k) => {
55512
+ const email3 = k.email ?? k.upn;
55513
+ return `${JSON.stringify(k.name)}${email3 !== void 0 ? ` <${email3}>` : ""} (${k.mri})`;
55514
+ }).join("; ");
55515
+ }
55516
+ function matchKnown(person, known) {
55517
+ const q = normaliseName(person);
55518
+ const raw = person.trim().toLowerCase();
55519
+ const exact = known.filter((k) => normaliseName(k.name) === q);
55520
+ const found = exact.length > 0 ? exact : known.filter((k) => normaliseName(k.name).includes(q) || k.name.toLowerCase().includes(raw));
55521
+ if (found.length === 1) return found[0];
55522
+ if (found.length > 1) {
55523
+ throw new McpToolError(
55524
+ `"${person}" matches ${found.length} people: ${candidateList(found)}. ${THIRD_PARTY_NAMES_NOTE}`,
55525
+ { hint: "Pass the MRI (8:orgid:\u2026) of the one you mean." }
55526
+ );
55527
+ }
55528
+ return void 0;
55529
+ }
55530
+ var PASS_ID = "Pass the person's email address or MRI (8:orgid:\u2026) instead.";
55531
+ function directoryFailed(person, err, email3) {
55532
+ const message = err instanceof Error ? err.message : String(err);
55533
+ const own2 = err instanceof McpToolError ? err.hint : void 0;
55534
+ const remedy = own2 ?? "Run any search in the Teams search box of a signed-in Teams tab while retrying (that is what lets this server capture the token it searches the directory with).";
55535
+ const lead = email3 ? `Could not look up "${person}" because` : `No one in your chats is called "${person}", and`;
55536
+ return new McpToolError(`${lead} the directory could not be searched: ${message}`, {
55537
+ hint: `${remedy} Or pass the person's MRI (8:orgid:\u2026) instead.`,
55538
+ ...err instanceof McpToolError && err.kind !== void 0 ? { kind: err.kind } : {},
55539
+ cause: err
55540
+ });
55541
+ }
55542
+ function fromDirectory(person, p) {
55543
+ const email3 = p.email ?? p.upn;
55544
+ return { person, mri: p.mri, name: p.name, source: "directory", ...email3 !== void 0 ? { email: email3 } : {} };
55545
+ }
55546
+ function pickByEmail(person, found) {
55547
+ const want = person.trim().toLowerCase();
55548
+ const hits = found.filter((p) => p.email?.toLowerCase() === want || p.upn?.toLowerCase() === want);
55549
+ if (hits.length === 1) return fromDirectory(person, hits[0]);
55550
+ if (hits.length > 1) {
55551
+ throw new McpToolError(
55552
+ `"${person}" is the address of ${hits.length} people in the directory: ${candidateList(hits)}. ${THIRD_PARTY_NAMES_NOTE}`,
55553
+ { hint: "Pass the MRI (8:orgid:\u2026) of the one you mean." }
55554
+ );
55555
+ }
55556
+ throw new McpToolError(`No one in your organisation's directory has the address "${person}".`, {
55557
+ hint: "Check the address, or pass the person's name or MRI (8:orgid:\u2026) instead. Only people in your organisation (not distribution lists or personal contacts) are found there."
55558
+ });
55559
+ }
55560
+ function pickByName(person, found) {
55561
+ const q = normaliseName(person);
55562
+ const exact = found.filter((p) => normaliseName(p.name) === q);
55563
+ if (exact.length === 1) return fromDirectory(person, exact[0]);
55564
+ if (exact.length > 1) {
55565
+ throw new McpToolError(
55566
+ `"${person}" matches ${exact.length} people in the directory: ${candidateList(exact)}. ${THIRD_PARTY_NAMES_NOTE}`,
55567
+ { hint: "Pass the email address or MRI (8:orgid:\u2026) of the one you mean." }
55568
+ );
55569
+ }
55570
+ if (found.length === 1 && ` ${normaliseName(found[0].name)} `.includes(` ${q} `)) return fromDirectory(person, found[0]);
55571
+ if (found.length > 0) {
55572
+ throw new McpToolError(
55573
+ `No one in your chats is called "${person}", and no one in the directory is called exactly that; it suggested: ${candidateList(found)}. ${THIRD_PARTY_NAMES_NOTE}`,
55574
+ { hint: "If one of them is who you mean, pass their email address or MRI (8:orgid:\u2026)." }
55575
+ );
55576
+ }
55577
+ throw new McpToolError(`No one in your chats or your organisation's directory is called "${person}".`, {
55578
+ hint: `${PASS_ID} A name is matched among the other person of each of your 1:1 chats and (for an existing chat) its recent senders, then searched in your organisation's directory.`
55579
+ });
55580
+ }
55581
+ async function resolvePeople(inputs, known, directory) {
55582
+ const local = inputs.map((person) => {
55583
+ const direct = personMri(person);
55584
+ if (direct !== void 0) {
55585
+ const name = knownName(direct, known);
55586
+ return { person, mri: direct, ...name !== void 0 ? { name } : {}, source: "id" };
55587
+ }
55588
+ if (isEmail(person)) return { person, email: true };
55589
+ const k = matchKnown(person, known);
55590
+ return k !== void 0 ? { person, mri: k.mri, name: k.name, source: "chat" } : { person, email: false };
55591
+ });
55592
+ const asked = /* @__PURE__ */ new Map();
55593
+ const out = [];
55594
+ for (const r of local) {
55595
+ if ("mri" in r) {
55596
+ out.push(r);
55597
+ continue;
55598
+ }
55599
+ const text = r.person.trim();
55600
+ const key = r.email ? `@${text.toLowerCase()}` : normaliseName(text);
55601
+ let found = asked.get(key);
55602
+ if (found === void 0) {
55603
+ try {
55604
+ found = await directory.suggestPeople(text, { force: true });
55605
+ } catch (err) {
55606
+ throw directoryFailed(r.person, err, r.email);
55607
+ }
55608
+ asked.set(key, found);
55609
+ }
55610
+ out.push(r.email ? pickByEmail(r.person, found) : pickByName(r.person, found));
55611
+ }
55612
+ return out;
55613
+ }
55614
+
55615
+ // src/tools/send.ts
55616
+ var TOOL2 = "teams_send_message";
55617
+ var READBACK_MESSAGES = 50;
55618
+ var MAX_CANDIDATES3 = 10;
55215
55619
  var PREVIEW_CHARS3 = 200;
55216
- var MRI = /^\d+:\S+$/;
55217
55620
  var mentionArg = external_exports.object({
55218
55621
  name_in_text: external_exports.string().min(1).describe('How the person is named in text \u2014 its first "@name" (else "name") becomes the mention.'),
55219
55622
  person: external_exports.string().min(1).describe("Who to mention: an MRI (8:orgid:\u2026), or a display name matched among recent senders in this conversation.")
@@ -55229,15 +55632,6 @@ async function resolveTarget(chatsvc, conversation, me, verb = "post to") {
55229
55632
  const s = await resolveListed(chatsvc, raw, me, conversation, verb);
55230
55633
  return { id: s.id, title: s.title, kind: s.kind, ...s.participants !== void 0 ? { participants: s.participants } : {} };
55231
55634
  }
55232
- async function recentSenders(chatsvc, conversationId) {
55233
- const out = /* @__PURE__ */ new Map();
55234
- for (const m of await chatsvc.getMessages(conversationId, { max: RECENT_MESSAGES })) {
55235
- const mri = senderMri(m.from);
55236
- const name = m.imdisplayname?.trim();
55237
- if (isUserMessage(m) && mri !== void 0 && name && !out.has(mri)) out.set(mri, name);
55238
- }
55239
- return out;
55240
- }
55241
55635
  async function resolveMentions(chatsvc, conversationId, mentions) {
55242
55636
  if (mentions.length === 0) return [];
55243
55637
  const senders = mentions.every((m) => MRI.test(m.person.trim())) ? /* @__PURE__ */ new Map() : await recentSenders(chatsvc, conversationId);
@@ -55250,13 +55644,13 @@ async function resolveMentions(chatsvc, conversationId, mentions) {
55250
55644
  const found = exact.length > 0 ? exact : known.filter((k) => k.name.toLowerCase().includes(q));
55251
55645
  if (found.length === 1) return { target: { text: name_in_text, mri: found[0].mri }, person: found[0].name };
55252
55646
  if (found.length > 1) {
55253
- const named = found.slice(0, MAX_CANDIDATES2).map((k) => `${JSON.stringify(k.name)} (${k.mri})`).join("; ");
55647
+ const named = found.slice(0, MAX_CANDIDATES3).map((k) => `${JSON.stringify(k.name)} (${k.mri})`).join("; ");
55254
55648
  throw new McpToolError(
55255
55649
  `"${person}" matches ${found.length} people in this conversation: ${named}. ${THIRD_PARTY_NAMES_NOTE}`,
55256
55650
  { hint: "Pass the MRI of the one to mention as person." }
55257
55651
  );
55258
55652
  }
55259
- const some = known.slice(0, MAX_CANDIDATES2).map((k) => JSON.stringify(k.name)).join(", ");
55653
+ const some = known.slice(0, MAX_CANDIDATES3).map((k) => JSON.stringify(k.name)).join(", ");
55260
55654
  throw new McpToolError(`No recent sender in this conversation is called "${person}".`, {
55261
55655
  hint: (some ? `Recent senders: ${some}. ${THIRD_PARTY_NAMES_NOTE} ` : "") + "Pass an exact display name, or the person's MRI (8:orgid:\u2026) as person."
55262
55656
  });
@@ -55531,7 +55925,7 @@ function registerReactTools(server, { chatsvc }) {
55531
55925
  } catch {
55532
55926
  readBackFailed = true;
55533
55927
  }
55534
- const shown2 = remove ? "gone" : "present";
55928
+ const shown3 = remove ? "gone" : "present";
55535
55929
  if (unconfirmed !== void 0 && verified !== true) {
55536
55930
  const status = writeOutcomeStatus(unconfirmed);
55537
55931
  const why = unconfirmed.timedOut ? "it did not answer in time" : status !== void 0 ? `it answered HTTP ${status}` : "the connection dropped";
@@ -55541,18 +55935,18 @@ function registerReactTools(server, { chatsvc }) {
55541
55935
  message_id,
55542
55936
  reaction: key,
55543
55937
  verified,
55544
- warning: `Teams did not confirm this change (${why}), and reading the message back ${readBackFailed ? "failed" : verified === null ? "did not find it" : `did not show the reaction ${shown2}`} \u2014 check the message (teams_list_messages) before retrying.`
55938
+ warning: `Teams did not confirm this change (${why}), and reading the message back ${readBackFailed ? "failed" : verified === null ? "did not find it" : `did not show the reaction ${shown3}`} \u2014 check the message (teams_list_messages) before retrying.`
55545
55939
  });
55546
55940
  }
55547
55941
  let warning;
55548
55942
  if (unconfirmed !== void 0) {
55549
- warning = `Teams did not confirm this change, but reading the message back shows the reaction ${shown2}.`;
55943
+ warning = `Teams did not confirm this change, but reading the message back shows the reaction ${shown3}.`;
55550
55944
  } else if (readBackFailed) {
55551
55945
  warning = "Teams accepted the change, but reading the message back failed \u2014 check the message (teams_list_messages).";
55552
55946
  } else if (verified === null) {
55553
55947
  warning = "Teams accepted the change, but the message was not found on reading it back (it may have been deleted) \u2014 check the conversation (teams_list_messages).";
55554
55948
  } else if (!verified) {
55555
- warning = `Teams accepted the change, but reading the message back did not show the reaction ${shown2} \u2014 check the message (teams_list_messages); the key may not be one Teams knows.`;
55949
+ warning = `Teams accepted the change, but reading the message back did not show the reaction ${shown3} \u2014 check the message (teams_list_messages); the key may not be one Teams knows.`;
55556
55950
  }
55557
55951
  return untrustedResult2({
55558
55952
  status: remove ? "removed" : "reacted",
@@ -55569,6 +55963,430 @@ function registerReactTools(server, { chatsvc }) {
55569
55963
  );
55570
55964
  }
55571
55965
 
55966
+ // src/tools/group-chat.ts
55967
+ init_zod();
55968
+ init_dist2();
55969
+ var RENAME = "teams_rename_chat";
55970
+ var ADD = "teams_add_chat_members";
55971
+ var REMOVE = "teams_remove_chat_members";
55972
+ var CREATE = "teams_create_group_chat";
55973
+ var MAX_PEOPLE = 20;
55974
+ var KIND_LABELS = {
55975
+ oneOnOne: "a 1:1 chat",
55976
+ meeting: "a meeting chat",
55977
+ channel: "a channel",
55978
+ self: "your notes self-chat"
55979
+ };
55980
+ var conversationParam = external_exports.string().min(1).describe(
55981
+ "The group chat: its id (from teams_list_conversations), or a case-insensitive substring of its title or an untitled chat's participant names."
55982
+ );
55983
+ function peopleParamText(local) {
55984
+ return `each an MRI (8:orgid:\u2026), a bare Entra object id, an email address (looked up in your organisation's directory), or a display name ("Greg King" and "King, Greg" are the same) matched among ${local}, then \u2014 only if no one there matches \u2014 in the directory.`;
55985
+ }
55986
+ var peopleParam = external_exports.array(external_exports.string().trim().min(1)).min(1).max(MAX_PEOPLE).describe(`Who: ${peopleParamText("the other people of your 1:1 chats and recent senders in this chat")}`);
55987
+ function peopleSentence(local) {
55988
+ return `people are MRIs (8:orgid:\u2026), bare object ids, email addresses, or display names. A name is matched (ignoring case, in either "First Last" or "Last, First" order) among ${local} first; only when no one there matches is the organisation's directory searched, where the one person with exactly that name is taken (or the only suggestion, when the name is whole words of it). An email address is looked up in the directory and must be exactly one person's email or UPN. An ambiguous or unknown person refuses the whole call, listing candidates. The directory is searched with the same token as teams_search_messages: the first lookup may need the user to run any search in the Teams search box so it can be captured. `;
55989
+ }
55990
+ var PEOPLE_SENTENCE = peopleSentence(
55991
+ "the other person of each of the user's 1:1 chats and the chat's recent senders"
55992
+ );
55993
+ async function groupChat(chatsvc, conversation, me, doing) {
55994
+ const target = await resolveTarget(chatsvc, conversation, me, `change`);
55995
+ if (target.kind === "group") return target;
55996
+ const what = KIND_LABELS[target.kind] ?? `a ${target.kind}`;
55997
+ throw new McpToolError(
55998
+ `${JSON.stringify(target.title)} is ${what}, not a group chat: only a group chat can be ${doing}.`,
55999
+ {
56000
+ hint: target.kind === "oneOnOne" ? "A 1:1 cannot take more people or a name; start a group chat in Teams instead." : 'Pass a group chat (kind "group" in teams_list_conversations).'
56001
+ }
56002
+ );
56003
+ }
56004
+ function unconfirmedWhy2(e) {
56005
+ const status = writeOutcomeStatus(e);
56006
+ return e.timedOut ? "it did not answer in time" : status !== void 0 ? `it answered HTTP ${status}` : "the connection dropped";
56007
+ }
56008
+ function memberSet(thread) {
56009
+ return new Set((thread.members ?? []).map((m) => m.id.toLowerCase()));
56010
+ }
56011
+ function shown(p) {
56012
+ return {
56013
+ person: p.person,
56014
+ mri: p.mri,
56015
+ ...p.name !== void 0 ? { name: p.name } : {},
56016
+ source: p.source,
56017
+ ...p.email !== void 0 ? { email: p.email } : {}
56018
+ };
56019
+ }
56020
+ async function resolveFor(chatsvc, directory, me, conversationId, people) {
56021
+ const known = await knownPeople(chatsvc, me, conversationId);
56022
+ const seen = /* @__PURE__ */ new Set();
56023
+ return (await resolvePeople(people, known, directory)).filter((p) => {
56024
+ const key = p.mri.toLowerCase();
56025
+ if (seen.has(key)) return false;
56026
+ seen.add(key);
56027
+ return true;
56028
+ });
56029
+ }
56030
+ async function applyMemberChanges(chatsvc, threadId, people, write, done) {
56031
+ const outcomes = [];
56032
+ for (const p of people) {
56033
+ try {
56034
+ await write(p.mri);
56035
+ outcomes.push({ p });
56036
+ } catch (e) {
56037
+ if (e instanceof WriteOutcomeUnknownError) outcomes.push({ p, unconfirmed: e });
56038
+ else outcomes.push({ p, error: e instanceof Error ? e.message : String(e) });
56039
+ }
56040
+ }
56041
+ let members2;
56042
+ try {
56043
+ members2 = memberSet(await chatsvc.getThread(threadId));
56044
+ } catch {
56045
+ members2 = void 0;
56046
+ }
56047
+ const changed = (mri) => {
56048
+ const present = members2?.has(mri.toLowerCase());
56049
+ return present === void 0 ? null : done === "added" ? present : !present;
56050
+ };
56051
+ const notes = [];
56052
+ const results = outcomes.map(({ p, unconfirmed, error: error62 }) => {
56053
+ if (error62 !== void 0) return { ...shown(p), status: "failed", error: error62 };
56054
+ const verified = changed(p.mri);
56055
+ if (unconfirmed !== void 0 && verified !== true) {
56056
+ notes.push(
56057
+ `Teams did not confirm the change for ${p.mri} (${unconfirmedWhy2(unconfirmed)}), and reading the chat back ${verified === null ? "failed" : `did not show it ${done}`}.`
56058
+ );
56059
+ return { ...shown(p), status: "unknown", verified: verified ?? false };
56060
+ }
56061
+ if (unconfirmed !== void 0) {
56062
+ notes.push(`Teams did not confirm the change for ${p.mri}, but reading the chat back shows it ${done}.`);
56063
+ } else if (verified === false) {
56064
+ notes.push(`Teams accepted the change for ${p.mri}, but reading the chat back did not show it ${done}.`);
56065
+ }
56066
+ return { ...shown(p), status: done, verified };
56067
+ });
56068
+ if (members2 === void 0) notes.push("Teams accepted the changes, but reading the chat back failed.");
56069
+ if (results.some((r) => r.status === "failed")) notes.push("Some changes failed: see each person's error.");
56070
+ if (notes.length === 0) return { results };
56071
+ return {
56072
+ results,
56073
+ warning: `${notes.join(" ")} Check the chat before retrying \u2014 running this tool again is safe: anyone already ${done === "added" ? "in the chat is reported as already_member" : "gone is reported as not_member"} and not written again.`
56074
+ };
56075
+ }
56076
+ function registerGroupChatTools(server, { chatsvc, substrate }) {
56077
+ server.registerTool(
56078
+ RENAME,
56079
+ {
56080
+ title: "Rename a Teams group chat",
56081
+ description: `Rename a group chat (set its topic) as the signed-in user. conversation is the chat's id or name as for teams_list_messages; only group chats can be renamed \u2014 1:1s, meeting chats, channels and the self-chat (${SELF_CHAT}) are refused. Teams posts a notice in the chat that the user renamed it, so everyone in it sees the change. Renaming to the current name changes nothing and asks for no confirmation. The result says whether reading the chat back showed the new name (verified); status "unknown" means Teams did not confirm the change and the read-back did not show it \u2014 check the chat before retrying. ` + CONFIRM_FLOW_SENTENCE + " The preview shows the chat, its current name and the new one. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
56082
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
56083
+ _meta: workMeta("send", { aliases: ["rename chat", "rename", "chat name", "topic", "set topic"] }),
56084
+ inputSchema: {
56085
+ conversation: conversationParam,
56086
+ name: external_exports.string().trim().min(1).describe("The new name for the chat (surrounding spaces are trimmed)."),
56087
+ confirmToken: confirmTokenParam
56088
+ }
56089
+ },
56090
+ async ({ conversation, name, confirmToken }, ctx) => {
56091
+ try {
56092
+ const me = await chatsvc.meMri();
56093
+ const target = await groupChat(chatsvc, conversation, me, "renamed");
56094
+ const current = (await chatsvc.getThread(target.id)).properties?.topic ?? "";
56095
+ if (current === name) {
56096
+ return untrustedResult2({ status: "unchanged", conversation: target, name });
56097
+ }
56098
+ const path = `/threads/${encodeURIComponent(target.id)}/properties?name=topic`;
56099
+ const gate = await confirmWrite(ctx, {
56100
+ tool: RENAME,
56101
+ action: "chat.rename",
56102
+ message: "Review and confirm this group chat rename before it is made:",
56103
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
56104
+ summary: `Rename group chat ${JSON.stringify(target.title)} to ${JSON.stringify(name)}`,
56105
+ // The signed-in user, so an approval minted under one account never acts as another.
56106
+ account: me,
56107
+ target: target.id,
56108
+ request: { method: "PUT", path, body: { topic: name } },
56109
+ // The title and the current name are set by other people, so each is fenced.
56110
+ preview: {
56111
+ conversation: untrustedField(target),
56112
+ current_name: untrustedField(current),
56113
+ new_name: name,
56114
+ note: "Teams posts a notice in the chat that you renamed it."
56115
+ },
56116
+ confirmToken
56117
+ });
56118
+ if (gate) return gate;
56119
+ let unconfirmed;
56120
+ try {
56121
+ await chatsvc.setTopic(target.id, name);
56122
+ } catch (e) {
56123
+ if (!(e instanceof WriteOutcomeUnknownError)) throw e;
56124
+ unconfirmed = e;
56125
+ }
56126
+ let verified = false;
56127
+ try {
56128
+ verified = (await chatsvc.getThread(target.id)).properties?.topic === name;
56129
+ } catch {
56130
+ verified = null;
56131
+ }
56132
+ const base = { conversation: target, previous_name: current, name };
56133
+ if (unconfirmed !== void 0 && verified !== true) {
56134
+ return untrustedResult2({
56135
+ status: "unknown",
56136
+ ...base,
56137
+ verified: verified ?? false,
56138
+ warning: `Teams did not confirm this rename (${unconfirmedWhy2(unconfirmed)}), and reading the chat back ${verified === null ? "failed" : "did not show the new name"} \u2014 check the chat (teams_list_conversations) before retrying; renaming again to the same name is harmless.`
56139
+ });
56140
+ }
56141
+ let warning;
56142
+ if (unconfirmed !== void 0) {
56143
+ warning = "Teams did not confirm this rename, but reading the chat back shows the new name.";
56144
+ } else if (verified === null) {
56145
+ warning = "Teams accepted the rename, but reading the chat back failed \u2014 check the chat (teams_list_conversations).";
56146
+ } else if (!verified) {
56147
+ warning = "Teams accepted the rename, but reading the chat back did not show the new name \u2014 check the chat (teams_list_conversations).";
56148
+ }
56149
+ return untrustedResult2({ status: "renamed", ...base, verified, ...warning !== void 0 ? { warning } : {} });
56150
+ } catch (err) {
56151
+ throw wrapApiError(err, "rename the chat");
56152
+ }
56153
+ }
56154
+ );
56155
+ server.registerTool(
56156
+ ADD,
56157
+ {
56158
+ title: "Add people to a Teams group chat",
56159
+ description: `Add people to a group chat as the signed-in user, as ordinary members. conversation is the chat's id or name as for teams_list_messages; only group chats take people \u2014 1:1s, meeting chats, channels and the self-chat are refused. ${PEOPLE_SENTENCE}People already in the chat are reported as already_member and not written; if everyone is, nothing is asked or changed. Teams posts a notice in the chat for each person added, and they can read the chat's history as Teams allows. The result lists each person: added, already_member, unknown (Teams did not confirm and reading the chat back does not show them \u2014 check before retrying) or failed (with the error). ` + CONFIRM_FLOW_SENTENCE + " The preview shows the chat and exactly who would be added \u2014 each with their source (id, chat or directory) and, from the directory, their email \u2014 so the user can check it is the right person. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
56160
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
56161
+ _meta: workMeta("send", { aliases: ["add people", "add to chat", "invite", "add members", "members"] }),
56162
+ inputSchema: {
56163
+ conversation: conversationParam,
56164
+ people: peopleParam,
56165
+ confirmToken: confirmTokenParam
56166
+ }
56167
+ },
56168
+ async ({ conversation, people, confirmToken }, ctx) => {
56169
+ try {
56170
+ const me = await chatsvc.meMri();
56171
+ const target = await groupChat(chatsvc, conversation, me, "given more people");
56172
+ const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
56173
+ const members2 = memberSet(await chatsvc.getThread(target.id));
56174
+ const already = resolved.filter((p) => members2.has(p.mri.toLowerCase()));
56175
+ const toAdd = resolved.filter((p) => !members2.has(p.mri.toLowerCase()));
56176
+ const alreadyResults = already.map((p) => ({ ...shown(p), status: "already_member" }));
56177
+ if (toAdd.length === 0) {
56178
+ return untrustedResult2({ status: "unchanged", conversation: target, results: alreadyResults });
56179
+ }
56180
+ const gate = await confirmWrite(ctx, {
56181
+ tool: ADD,
56182
+ action: "chat.add_members",
56183
+ message: "Review and confirm who is added to this group chat:",
56184
+ summary: `Add ${toAdd.length} ${toAdd.length === 1 ? "person" : "people"} to group chat ${JSON.stringify(target.title)}`,
56185
+ account: me,
56186
+ target: target.id,
56187
+ request: {
56188
+ method: "PUT",
56189
+ path: `/threads/${encodeURIComponent(target.id)}/members`,
56190
+ body: { members: toAdd.map((p) => ({ id: p.mri, role: "User" })) }
56191
+ },
56192
+ // The title and the resolved names are set by other people, so each is fenced.
56193
+ preview: {
56194
+ conversation: untrustedField(target),
56195
+ add: untrustedField(toAdd.map(shown)),
56196
+ ...already.length > 0 ? { already_members: untrustedField(already.map(shown)) } : {},
56197
+ note: 'Sent as one PUT /threads/{id}/members/{mri} with {"role":"User"} per person. Teams posts a notice in the chat for each person added.'
56198
+ },
56199
+ confirmToken
56200
+ });
56201
+ if (gate) return gate;
56202
+ const { results, warning } = await applyMemberChanges(
56203
+ chatsvc,
56204
+ target.id,
56205
+ toAdd,
56206
+ (mri) => chatsvc.addMember(target.id, mri, "User"),
56207
+ "added"
56208
+ );
56209
+ return untrustedResult2({
56210
+ status: "done",
56211
+ conversation: target,
56212
+ results: orderAs(resolved, [...results, ...alreadyResults]),
56213
+ ...warning !== void 0 ? { warning } : {}
56214
+ });
56215
+ } catch (err) {
56216
+ throw wrapApiError(err, "add people to the chat");
56217
+ }
56218
+ }
56219
+ );
56220
+ server.registerTool(
56221
+ REMOVE,
56222
+ {
56223
+ title: "Remove people from a Teams group chat",
56224
+ description: `Remove people from a group chat as the signed-in user. conversation is the chat's id or name as for teams_list_messages; only group chats are changed \u2014 1:1s, meeting chats, channels and the self-chat are refused, and so is removing the signed-in user (leave the chat in Teams instead). ${PEOPLE_SENTENCE}People not in the chat are reported as not_member and not written; if no one is, nothing is asked or changed. Teams posts a notice in the chat for each person removed, and they lose access to it. The result lists each person: removed, not_member, unknown (Teams did not confirm and reading the chat back still shows them \u2014 check before retrying) or failed (with the error). ` + CONFIRM_FLOW_SENTENCE + " The preview shows the chat and exactly who would be removed \u2014 each with their source (id, chat or directory) and, from the directory, their email. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
56225
+ annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: true, openWorld: true }),
56226
+ _meta: workMeta("send", { aliases: ["remove people", "remove from chat", "kick", "remove members", "members"] }),
56227
+ inputSchema: {
56228
+ conversation: conversationParam,
56229
+ people: peopleParam,
56230
+ confirmToken: confirmTokenParam
56231
+ }
56232
+ },
56233
+ async ({ conversation, people, confirmToken }, ctx) => {
56234
+ try {
56235
+ const me = await chatsvc.meMri();
56236
+ const target = await groupChat(chatsvc, conversation, me, "changed");
56237
+ const resolved = await resolveFor(chatsvc, substrate, me, target.id, people);
56238
+ const self = resolved.find((p) => p.mri.toLowerCase() === me.toLowerCase());
56239
+ if (self !== void 0) {
56240
+ throw new McpToolError(`Refusing to remove you (the signed-in user, "${self.person}") from the chat.`, {
56241
+ hint: "To leave a group chat, use Leave in Teams. Remove the others by passing them without yourself."
56242
+ });
56243
+ }
56244
+ const members2 = memberSet(await chatsvc.getThread(target.id));
56245
+ const toRemove = resolved.filter((p) => members2.has(p.mri.toLowerCase()));
56246
+ const absent = resolved.filter((p) => !members2.has(p.mri.toLowerCase())).map((p) => ({ ...shown(p), status: "not_member" }));
56247
+ if (toRemove.length === 0) {
56248
+ return untrustedResult2({ status: "unchanged", conversation: target, results: absent });
56249
+ }
56250
+ const gate = await confirmWrite(ctx, {
56251
+ tool: REMOVE,
56252
+ action: "chat.remove_members",
56253
+ message: "Review and confirm who is removed from this group chat:",
56254
+ summary: `Remove ${toRemove.length} ${toRemove.length === 1 ? "person" : "people"} from group chat ` + JSON.stringify(target.title),
56255
+ account: me,
56256
+ target: target.id,
56257
+ request: {
56258
+ method: "DELETE",
56259
+ path: `/threads/${encodeURIComponent(target.id)}/members`,
56260
+ body: { members: toRemove.map((p) => p.mri) }
56261
+ },
56262
+ preview: {
56263
+ conversation: untrustedField(target),
56264
+ remove: untrustedField(toRemove.map(shown)),
56265
+ ...absent.length > 0 ? { not_members: untrustedField(absent.map(shown)) } : {},
56266
+ note: "Sent as one DELETE /threads/{id}/members/{mri} per person. Teams posts a notice in the chat for each person removed."
56267
+ },
56268
+ confirmToken
56269
+ });
56270
+ if (gate) return gate;
56271
+ const { results, warning } = await applyMemberChanges(
56272
+ chatsvc,
56273
+ target.id,
56274
+ toRemove,
56275
+ (mri) => chatsvc.removeMember(target.id, mri),
56276
+ "removed"
56277
+ );
56278
+ return untrustedResult2({
56279
+ status: "done",
56280
+ conversation: target,
56281
+ results: orderAs(resolved, [...results, ...absent]),
56282
+ ...warning !== void 0 ? { warning } : {}
56283
+ });
56284
+ } catch (err) {
56285
+ throw wrapApiError(err, "remove people from the chat");
56286
+ }
56287
+ }
56288
+ );
56289
+ server.registerTool(
56290
+ CREATE,
56291
+ {
56292
+ title: "Create a Teams group chat",
56293
+ description: "Start a new group chat as the signed-in user with 2\u201320 other people, optionally named (topic). The user is always included (listing them is ignored), as are duplicates; fewer than two other people is refused \u2014 one other person is a 1:1, which this tool does not create. " + peopleSentence("the other person of each of the user's 1:1 chats") + 'Everyone added sees the chat at once in their chat list, and it cannot be deleted afterwards \u2014 only left. No message is sent: post the first one with teams_send_message, passing the new conversation id. Not idempotent: every confirmed call makes a NEW chat. The result has the new conversation (id, title, kind "group"), the members and whether reading the chat back showed them all and the topic (verified); status "unknown" means Teams did not confirm the create \u2014 a chat may exist anyway, so check teams_list_conversations and do NOT retry blindly (that would make a second chat). ' + CONFIRM_FLOW_SENTENCE + " The preview shows the topic and exactly who would be in the chat \u2014 each with their source (id, chat or directory) and, from the directory, their email \u2014 so the user can check it is the right people. " + CONFIRM_INJECTION_RULE + UNTRUSTED_DESCRIPTION_SUFFIX2,
56294
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: false, openWorld: true }),
56295
+ _meta: workMeta("send", {
56296
+ aliases: ["create chat", "new group chat", "start a chat", "new chat", "group chat", "start group chat"]
56297
+ }),
56298
+ inputSchema: {
56299
+ people: external_exports.array(external_exports.string().trim().min(1)).min(2).max(MAX_PEOPLE).describe(
56300
+ `Who to start the chat with (2\u201320 others; you are added automatically): ` + peopleParamText("the other people of your 1:1 chats")
56301
+ ),
56302
+ topic: external_exports.string().optional().describe("A name for the chat (surrounding spaces are trimmed). Omit or leave empty for an untitled chat."),
56303
+ confirmToken: confirmTokenParam
56304
+ }
56305
+ },
56306
+ async ({ people, topic: rawTopic, confirmToken }, ctx) => {
56307
+ try {
56308
+ const me = await chatsvc.meMri();
56309
+ const topic = rawTopic?.trim() || void 0;
56310
+ const others = (await resolveFor(chatsvc, substrate, me, void 0, people)).filter(
56311
+ (p) => p.mri.toLowerCase() !== me.toLowerCase()
56312
+ );
56313
+ if (others.length < 2) {
56314
+ throw new McpToolError(
56315
+ `A group chat needs at least two other people besides you; ${others.length === 1 ? `only ${JSON.stringify(others[0].person)} is` : "no one else is"} left once you and duplicates are dropped. One other person is a 1:1 chat, which this tool does not create.`,
56316
+ {
56317
+ hint: "Add at least one more person, or to talk to one person use your 1:1 chat with them (teams_send_message, conversation set to their name)."
56318
+ }
56319
+ );
56320
+ }
56321
+ const members2 = others.map(shown);
56322
+ const allMris = [me, ...others.map((p) => p.mri)];
56323
+ const count = `you and ${others.length} other people`;
56324
+ const gate = await confirmWrite(ctx, {
56325
+ tool: CREATE,
56326
+ action: "chat.create",
56327
+ message: "Review and confirm this new group chat before it is created \u2014 it cannot be deleted afterwards:",
56328
+ // The topic is the caller's own text: JSON-quoted all the same, so it reads as one value.
56329
+ summary: `Create ${topic !== void 0 ? `group chat ${JSON.stringify(topic)}` : "an untitled group chat"} with ${count}`,
56330
+ account: me,
56331
+ target: "new group chat",
56332
+ request: { method: "POST", path: "/threads", body: { members: allMris, ...topic !== void 0 ? { topic } : {} } },
56333
+ // The resolved names are set by other people, so they are fenced.
56334
+ preview: {
56335
+ topic: topic ?? "(untitled)",
56336
+ members: untrustedField(members2),
56337
+ note: "Creates a NEW group chat with everyone as a member (Teams makes each one an Admin). Everyone added sees it at once; it cannot be deleted afterwards, only left. No message is sent."
56338
+ },
56339
+ confirmToken
56340
+ });
56341
+ if (gate) return gate;
56342
+ let id;
56343
+ try {
56344
+ ({ id } = await chatsvc.createGroupChat(others.map((p) => p.mri), topic));
56345
+ } catch (e) {
56346
+ if (!(e instanceof WriteOutcomeUnknownError)) throw e;
56347
+ return untrustedResult2({
56348
+ status: "unknown",
56349
+ ...topic !== void 0 ? { topic } : {},
56350
+ members: members2,
56351
+ warning: `Teams did not confirm creating the chat (${unconfirmedWhy2(e)}), so it may or may not exist. Check teams_list_conversations for a new group chat with these people (no messages yet) before doing anything else \u2014 do NOT retry blindly: if it was created, retrying makes a second chat, and chats cannot be deleted.`
56352
+ });
56353
+ }
56354
+ let warning;
56355
+ let verified;
56356
+ try {
56357
+ const thread = await chatsvc.getThread(id);
56358
+ const present = memberSet(thread);
56359
+ const missing = allMris.filter((m) => !present.has(m.toLowerCase()));
56360
+ const shownTopic = thread.properties?.topic || void 0;
56361
+ const notes = [];
56362
+ if (missing.length > 0) notes.push(`did not show ${missing.join(", ")} as a member`);
56363
+ if (shownTopic !== topic) notes.push(`showed the topic as ${JSON.stringify(shownTopic ?? "")}`);
56364
+ verified = notes.length === 0;
56365
+ if (!verified) {
56366
+ warning = `Teams created the chat, but reading it back ${notes.join(" and ")} \u2014 check it in Teams (do not create it again).`;
56367
+ }
56368
+ } catch {
56369
+ verified = null;
56370
+ warning = "Teams created the chat, but reading the chat back failed \u2014 check it in teams_list_conversations (do not create it again).";
56371
+ }
56372
+ return untrustedResult2({
56373
+ status: "created",
56374
+ conversation: { id, title: topic ?? UNTITLED_GROUP_TITLE, kind: "group" },
56375
+ ...topic !== void 0 ? { topic } : {},
56376
+ members: members2,
56377
+ verified,
56378
+ ...warning !== void 0 ? { warning } : {}
56379
+ });
56380
+ } catch (err) {
56381
+ throw wrapApiError(err, "create the group chat");
56382
+ }
56383
+ }
56384
+ );
56385
+ }
56386
+ function orderAs(people, results) {
56387
+ return people.map((p) => results.find((r) => r.mri === p.mri));
56388
+ }
56389
+
55572
56390
  // src/tools/activity.ts
55573
56391
  init_zod();
55574
56392
  init_dist2();
@@ -56021,7 +56839,7 @@ init_dist2();
56021
56839
  init_healthcheck();
56022
56840
  var HOST_LABEL = "teams.cloud.microsoft";
56023
56841
  var TITLE = "Verify the Teams chat-service token and API end-to-end";
56024
- var SHAREPOINT_NOTE = "Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on demand per SharePoint host and short-lived (~53 min). None is held until you open a file, and this healthcheck neither mints nor requires one.";
56842
+ var SHAREPOINT_NOTE = "Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on demand and short-lived; one token serves every SharePoint host. None is held until you download a file, and this healthcheck neither mints nor requires one.";
56025
56843
  var SUBSTRATE_NOTE = "Search (teams_search_messages) uses a separate Microsoft Substrate token for substrate.office.com, captured on demand when you run a search in a Teams tab (the bridge pairing must trust substrate.office.com). Without one, search falls back to a scan of recent conversations; this healthcheck neither mints nor requires one.";
56026
56844
  function registerHealthcheckTool(server, { chatsvc }) {
56027
56845
  server.registerTool(
@@ -56096,7 +56914,7 @@ init_dist2();
56096
56914
  var MAX_SCAN = 2e3;
56097
56915
  var MAX_INLINE_CHARS = 2e5;
56098
56916
  var MAX_OTHERS = 20;
56099
- function shown(r) {
56917
+ function shown2(r) {
56100
56918
  const { message_id, object_id: _objectId, has_transcript: _has, duration_seconds: _secs, ...rest } = r;
56101
56919
  return { recording_id: message_id, ...rest };
56102
56920
  }
@@ -56141,7 +56959,7 @@ function registerTranscriptTools(server, { chatsvc }) {
56141
56959
  }
56142
56960
  }
56143
56961
  const picked = chosen;
56144
- const others = recordings.filter((r) => r !== picked).slice(0, MAX_OTHERS).map(shown);
56962
+ const others = recordings.filter((r) => r !== picked).slice(0, MAX_OTHERS).map(shown2);
56145
56963
  let vtt;
56146
56964
  try {
56147
56965
  vtt = await chatsvc.fetchTranscript(picked.object_id);
@@ -56153,7 +56971,7 @@ function registerTranscriptTools(server, { chatsvc }) {
56153
56971
  const base = {
56154
56972
  conversation: summary.id,
56155
56973
  title: summary.title,
56156
- recording: shown(chosen),
56974
+ recording: shown2(chosen),
56157
56975
  speakers: transcriptSpeakers(cues),
56158
56976
  cue_count: cues.length,
56159
56977
  ...others.length > 0 ? { other_recordings: others } : {}
@@ -56238,6 +57056,7 @@ await runMcp({
56238
57056
  registerSendTools,
56239
57057
  registerReactTools,
56240
57058
  registerMarkReadTools,
57059
+ registerGroupChatTools,
56241
57060
  registerActivityTools,
56242
57061
  registerSearchTools,
56243
57062
  registerExportTools,