@chrischall/microsoft-teams-mcp 0.5.0 → 0.6.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
@@ -20542,10 +20542,10 @@ var init_v4 = __esm({
20542
20542
  }
20543
20543
  });
20544
20544
 
20545
- // node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs
20545
+ // node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs
20546
20546
  var LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, PROTOCOL_VERSION_META_KEY, CLIENT_INFO_META_KEY, SERVER_INFO_META_KEY, CLIENT_CAPABILITIES_META_KEY, SUBSCRIPTION_ID_META_KEY, LOG_LEVEL_META_KEY, JSONRPC_VERSION, JSONValueSchema, JSONObjectSchema, JSONArraySchema, ProgressTokenSchema, CursorSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultMetaObjectSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, DiscoverRequestSchema, DiscoverResultSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, SubscriptionFilterSchema, SubscriptionsListenRequestParamsSchema, SubscriptionsListenRequestSchema, SubscriptionsAcknowledgedNotificationParamsSchema, SubscriptionsAcknowledgedNotificationSchema, SubscriptionsListenResultMetaSchema, SubscriptionsListenResultSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, TaskCreationParamsSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, SafeUrlSchema, OAuthProtectedResourceMetadataSchema, OAuthMetadataSchema, OpenIdProviderMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, OAuthTokensSchema, IdJagTokenExchangeResponseSchema, OAuthErrorResponseSchema, OptionalSafeUrlSchema, OAuthClientMetadataSchema, OAuthClientInformationSchema, OAuthClientInformationFullSchema, OAuthClientRegistrationErrorSchema, OAuthTokenRevocationRequestSchema;
20547
20547
  var init_auth_BNDyLTqp = __esm({
20548
- "node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs"() {
20548
+ "node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs"() {
20549
20549
  init_v4();
20550
20550
  LATEST_PROTOCOL_VERSION = "2025-11-25";
20551
20551
  SUPPORTED_PROTOCOL_VERSIONS = [
@@ -21489,9 +21489,9 @@ var init_auth_BNDyLTqp = __esm({
21489
21489
  }
21490
21490
  });
21491
21491
 
21492
- // node_modules/@modelcontextprotocol/core/dist/internal.mjs
21492
+ // node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/internal.mjs
21493
21493
  var init_internal = __esm({
21494
- "node_modules/@modelcontextprotocol/core/dist/internal.mjs"() {
21494
+ "node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/internal.mjs"() {
21495
21495
  init_auth_BNDyLTqp();
21496
21496
  }
21497
21497
  });
@@ -23727,11 +23727,11 @@ function assertCompleteRequestResourceTemplate(request) {
23727
23727
  function scanXMcpHeaderDeclarations(inputSchema) {
23728
23728
  const declarations = [];
23729
23729
  const seenLower = /* @__PURE__ */ new Map();
23730
- const visit2 = (node2, path, reachable) => {
23730
+ const visit2 = (node2, path, reachable2) => {
23731
23731
  if (node2 === null || typeof node2 !== "object") return void 0;
23732
23732
  const schema = node2;
23733
23733
  if (X_MCP_HEADER_KEY in schema) {
23734
- if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
23734
+ if (!reachable2 || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
23735
23735
  const raw = schema[X_MCP_HEADER_KEY];
23736
23736
  if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`;
23737
23737
  if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
@@ -23749,7 +23749,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
23749
23749
  }
23750
23750
  const properties = schema.properties;
23751
23751
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
23752
- const fault$1 = visit2(child, [...path, key], reachable);
23752
+ const fault$1 = visit2(child, [...path, key], reachable2);
23753
23753
  if (fault$1 !== void 0) return fault$1;
23754
23754
  }
23755
23755
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -37080,7 +37080,7 @@ var init_version = __esm({
37080
37080
  "src/version.ts"() {
37081
37081
  "use strict";
37082
37082
  PACKAGE_NAME = "microsoft-teams-mcp";
37083
- VERSION = "0.5.0";
37083
+ VERSION = "0.6.0";
37084
37084
  }
37085
37085
  });
37086
37086
 
@@ -48618,6 +48618,11 @@ function localIsoTime(iso, timeZone) {
48618
48618
  const abs = Math.abs(offsetMin);
48619
48619
  return `${pad(get("year"), 4)}-${pad(get("month"))}-${pad(get("day"))}T${pad(get("hour"))}:${pad(get("minute"))}:${pad(get("second"))}.${pad(millis, 3)}${sign2}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
48620
48620
  }
48621
+ function changedMs(m) {
48622
+ const v = Number(m.version);
48623
+ const id = Number(m.id);
48624
+ return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
48625
+ }
48621
48626
  function normaliseMessage(m, meMri, opts = {}) {
48622
48627
  const props = m.properties ?? {};
48623
48628
  const mri = senderMri(m.from);
@@ -48676,6 +48681,94 @@ function hasRealTitle(s) {
48676
48681
  return s.participants === void 0;
48677
48682
  }
48678
48683
 
48684
+ // src/network-error.ts
48685
+ init_dist2();
48686
+ var MAX_CAUSE_DEPTH = 5;
48687
+ var DNS_CODES = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "EAI_FAIL", "EAI_NONAME"]);
48688
+ var CONNECT_CODES = /* @__PURE__ */ new Set([
48689
+ "ECONNREFUSED",
48690
+ "ECONNRESET",
48691
+ "ETIMEDOUT",
48692
+ "ENETUNREACH",
48693
+ "EHOSTUNREACH",
48694
+ "EPIPE",
48695
+ "UND_ERR_CONNECT_TIMEOUT",
48696
+ "UND_ERR_SOCKET",
48697
+ "UND_ERR_HEADERS_TIMEOUT"
48698
+ ]);
48699
+ var CERT_CODES = /* @__PURE__ */ new Set([
48700
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
48701
+ "UNABLE_TO_GET_ISSUER_CERT",
48702
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
48703
+ "SELF_SIGNED_CERT_IN_CHAIN",
48704
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
48705
+ "CERT_HAS_EXPIRED",
48706
+ "CERT_NOT_YET_VALID",
48707
+ "ERR_TLS_CERT_ALTNAME_INVALID"
48708
+ ]);
48709
+ function codeOf(e) {
48710
+ if (e === null || typeof e !== "object") return void 0;
48711
+ const code2 = e.code;
48712
+ return typeof code2 === "string" && code2 !== "" ? code2 : void 0;
48713
+ }
48714
+ function causes(err) {
48715
+ const out = [];
48716
+ let at = err;
48717
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== void 0 && at !== null; depth++) {
48718
+ out.push(at);
48719
+ if (at instanceof AggregateError) out.push(...at.errors);
48720
+ at = at.cause;
48721
+ }
48722
+ return out;
48723
+ }
48724
+ function transportCauseCode(err) {
48725
+ for (const e of causes(err)) {
48726
+ const code2 = codeOf(e);
48727
+ if (code2 !== void 0) return code2;
48728
+ }
48729
+ return void 0;
48730
+ }
48731
+ function causeMessage(err) {
48732
+ const chain = causes(err).slice(1);
48733
+ for (let i = chain.length - 1; i >= 0; i--) {
48734
+ const e = chain[i];
48735
+ if (e instanceof Error && e.message !== "") return e.message;
48736
+ }
48737
+ return void 0;
48738
+ }
48739
+ function isFetchFailed(err) {
48740
+ return err instanceof TypeError && err.message === "fetch failed";
48741
+ }
48742
+ function hintFor(code2, host) {
48743
+ if (code2 !== void 0 && DNS_CODES.has(code2)) {
48744
+ return `This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`;
48745
+ }
48746
+ if (code2 !== void 0 && CERT_CODES.has(code2)) {
48747
+ return `Node did not trust the TLS certificate ${host} presented. On a corporate network this is usually TLS inspection: export your proxy's root CA as PEM and start this server with NODE_EXTRA_CA_CERTS=/path/to/ca.pem (Node does not read the system keychain). If the certificate is expired or not yet valid, also check the machine's clock.`;
48748
+ }
48749
+ if (code2 !== void 0 && CONNECT_CODES.has(code2)) {
48750
+ return `The connection to ${host} was refused, reset or timed out before Teams answered \u2014 usually a firewall, or a network that only lets traffic out through a proxy. Node's fetch ignores proxy settings unless told: start this server with HTTPS_PROXY=<your proxy URL> and NODE_USE_ENV_PROXY=1 (Node 22.21+ / 24.5+), or allow the host through the firewall.`;
48751
+ }
48752
+ return `No response from ${host}. Check this machine can reach it (VPN, proxy, firewall); \`curl -sI https://${host}/\` from the same machine is a quick test.`;
48753
+ }
48754
+ function describeTransportFailure(err, url2, service) {
48755
+ if (!isFetchFailed(err)) return void 0;
48756
+ let host;
48757
+ try {
48758
+ host = new URL(url2).hostname;
48759
+ } catch {
48760
+ host = "(unknown host)";
48761
+ }
48762
+ const code2 = transportCauseCode(err);
48763
+ const detail = [code2, causeMessage(err)].filter((s) => s !== void 0);
48764
+ const why = detail.length > 0 ? ` (${[...new Set(detail)].join(": ")})` : "";
48765
+ return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
48766
+ kind: "transport",
48767
+ hint: hintFor(code2, host),
48768
+ cause: err
48769
+ });
48770
+ }
48771
+
48679
48772
  // src/chatsvc.ts
48680
48773
  async function captureTokenLazily() {
48681
48774
  const mod = await Promise.resolve().then(() => (init_auth_fetchproxy(), auth_fetchproxy_exports));
@@ -48696,6 +48789,16 @@ var MAX_MESSAGE_PAGES = 20;
48696
48789
  var DEFAULT_MESSAGE_PAGE_SIZE = 200;
48697
48790
  var MAX_IMAGE_BYTES = 5 * 1024 * 1024;
48698
48791
  var IMAGE_HOST_SUFFIX2 = ".asm.skype.com";
48792
+ var IMAGE_GATEWAY_HOST = "us-prod.asyncgw.teams.microsoft.com";
48793
+ function serviceFor(url2) {
48794
+ try {
48795
+ const host = new URL(url2).hostname;
48796
+ if (host.endsWith(IMAGE_HOST_SUFFIX2)) return "Teams' image store";
48797
+ return host === IMAGE_GATEWAY_HOST ? "the Teams image gateway" : "the Teams chat service";
48798
+ } catch {
48799
+ return "the Teams chat service";
48800
+ }
48801
+ }
48699
48802
  function outcomeUnknown(method, e, hint) {
48700
48803
  if (e instanceof RequestTimeoutError) {
48701
48804
  return new WriteOutcomeUnknownError("Teams", method, { timeoutMs: e.timeoutMs, cause: e, hint });
@@ -48827,16 +48930,17 @@ var ChatServiceClient = class {
48827
48930
  }
48828
48931
  /**
48829
48932
  * A conversation's messages, newest first, paging back until `stopAt`
48830
- * accepts a message, `max` are collected, the pages run out, or 20 pages
48831
- * have been read.
48933
+ * accepts a message, `max` are collected, the pages run out, or `maxPages`
48934
+ * (default 20) have been read.
48832
48935
  */
48833
48936
  async getMessages(id, opts) {
48834
48937
  this.#requireConfigured();
48835
48938
  const out = [];
48836
48939
  if (!(opts.max > 0)) return out;
48940
+ const seen = /* @__PURE__ */ new Set();
48837
48941
  let url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
48838
48942
  for (let page = 0; url2 !== void 0; page++) {
48839
- if (page >= MAX_MESSAGE_PAGES) {
48943
+ if (page >= (opts.maxPages ?? MAX_MESSAGE_PAGES)) {
48840
48944
  opts.onCapped?.();
48841
48945
  break;
48842
48946
  }
@@ -48845,6 +48949,8 @@ var ChatServiceClient = class {
48845
48949
  if (msgs.length === 0) break;
48846
48950
  let stopped = false;
48847
48951
  for (const m of msgs) {
48952
+ if (seen.has(m.id)) continue;
48953
+ seen.add(m.id);
48848
48954
  if (opts.stopAt?.(m)) {
48849
48955
  stopped = true;
48850
48956
  continue;
@@ -48964,6 +49070,23 @@ var ChatServiceClient = class {
48964
49070
  hint: `Only https images on *${IMAGE_HOST_SUFFIX2} (Teams' own image store) are fetched.`
48965
49071
  });
48966
49072
  }
49073
+ try {
49074
+ return await this.#getImage(target);
49075
+ } catch (e) {
49076
+ if (errorKindOf(e) !== "transport") throw e;
49077
+ const viaGateway = new URL(target.pathname + target.search, `https://${IMAGE_GATEWAY_HOST}`);
49078
+ try {
49079
+ return await this.#getImage(viaGateway);
49080
+ } catch (e2) {
49081
+ if (errorKindOf(e2) !== "transport") throw e2;
49082
+ throw new McpToolError(
49083
+ `${e.message} The Teams gateway was tried too: ${e2.message}`,
49084
+ { kind: "transport", hint: e.hint, cause: e }
49085
+ );
49086
+ }
49087
+ }
49088
+ }
49089
+ async #getImage(target) {
48967
49090
  const { status, headers, body } = await this.#send(target.toString(), "bytes", MAX_IMAGE_BYTES);
48968
49091
  this.#checkStatus(status);
48969
49092
  const mimeType = (headers.get("content-type") ?? "application/octet-stream").split(";")[0].trim();
@@ -49047,7 +49170,8 @@ var ChatServiceClient = class {
49047
49170
  try {
49048
49171
  r = await fetchBounded(url2, init, opts);
49049
49172
  } catch (e) {
49050
- throw write ? outcomeUnknown(method, e, write.hint) : e;
49173
+ if (write) throw outcomeUnknown(method, e, write.hint);
49174
+ throw describeTransportFailure(e, url2, serviceFor(url2)) ?? e;
49051
49175
  }
49052
49176
  body = r.body;
49053
49177
  return r.res;
@@ -49213,6 +49337,13 @@ async function captureSharePointTokenLazily(host) {
49213
49337
  var UNKNOWN_TOKEN_TTL_MS2 = 10 * 60 * 1e3;
49214
49338
  var RECAPTURE_SENTINEL2 = "fetchproxy:recapture";
49215
49339
  var REQUEST_TIMEOUT_MS2 = 6e4;
49340
+ async function reachable(url2, run) {
49341
+ try {
49342
+ return await run();
49343
+ } catch (e) {
49344
+ throw describeTransportFailure(e, url2, "SharePoint") ?? e;
49345
+ }
49346
+ }
49216
49347
  function toBearerTokens2(accessToken) {
49217
49348
  let expiresAt;
49218
49349
  try {
@@ -49324,18 +49455,21 @@ var SharePointClient = class {
49324
49455
  async #getDriveItem(captureHost, url2) {
49325
49456
  let body = "";
49326
49457
  const res = await this.#managerFor(captureHost).withAuth(async (token) => {
49327
- const r = await fetchBounded(
49458
+ const r = await reachable(
49328
49459
  url2,
49329
- {
49330
- method: "GET",
49331
- headers: {
49332
- authorization: `Bearer ${token}`,
49333
- accept: "application/json",
49334
- behavioroverride: "redirectAs404"
49460
+ () => fetchBounded(
49461
+ url2,
49462
+ {
49463
+ method: "GET",
49464
+ headers: {
49465
+ authorization: `Bearer ${token}`,
49466
+ accept: "application/json",
49467
+ behavioroverride: "redirectAs404"
49468
+ },
49469
+ redirect: "error"
49335
49470
  },
49336
- redirect: "error"
49337
- },
49338
- { read: "text", service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
49471
+ { read: "text", service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
49472
+ )
49339
49473
  );
49340
49474
  body = r.body;
49341
49475
  return r.res;
@@ -49375,10 +49509,13 @@ var SharePointClient = class {
49375
49509
  hint: "SharePoint download links are expected to be https."
49376
49510
  });
49377
49511
  }
49378
- const r = await fetchBounded(
49512
+ const r = await reachable(
49379
49513
  target.toString(),
49380
- { method: "GET", headers: { accept: "*/*" }, redirect: "follow" },
49381
- { read: "bytes", maxBytes, service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
49514
+ () => fetchBounded(
49515
+ target.toString(),
49516
+ { method: "GET", headers: { accept: "*/*" }, redirect: "follow" },
49517
+ { read: "bytes", maxBytes, service: "SharePoint", timeoutMs: REQUEST_TIMEOUT_MS2, fetchImpl: this.#fetchImpl }
49518
+ )
49382
49519
  );
49383
49520
  this.#checkStatus(r.status);
49384
49521
  const mimeType = (r.headers.get("content-type") ?? "application/octet-stream").split(";")[0].trim();
@@ -49628,26 +49765,31 @@ var SubstrateClient = class {
49628
49765
  if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS) throw failed.error;
49629
49766
  let text = "";
49630
49767
  const res = await this.#manager.withAuth(async (token) => {
49631
- const r = await fetchBounded(
49632
- SUBSTRATE_QUERY_URL,
49633
- {
49634
- method: "POST",
49635
- headers: {
49636
- authorization: `Bearer ${token}`,
49637
- "content-type": "application/json",
49638
- accept: "application/json"
49768
+ let r;
49769
+ try {
49770
+ r = await fetchBounded(
49771
+ SUBSTRATE_QUERY_URL,
49772
+ {
49773
+ method: "POST",
49774
+ headers: {
49775
+ authorization: `Bearer ${token}`,
49776
+ "content-type": "application/json",
49777
+ accept: "application/json"
49778
+ },
49779
+ body: JSON.stringify(buildQueryBody(req)),
49780
+ redirect: "error"
49639
49781
  },
49640
- body: JSON.stringify(buildQueryBody(req)),
49641
- redirect: "error"
49642
- },
49643
- {
49644
- read: "text",
49645
- maxBytes: MAX_RESPONSE_BYTES,
49646
- service: "Substrate",
49647
- timeoutMs: REQUEST_TIMEOUT_MS3,
49648
- fetchImpl: this.#fetchImpl
49649
- }
49650
- );
49782
+ {
49783
+ read: "text",
49784
+ maxBytes: MAX_RESPONSE_BYTES,
49785
+ service: "Substrate",
49786
+ timeoutMs: REQUEST_TIMEOUT_MS3,
49787
+ fetchImpl: this.#fetchImpl
49788
+ }
49789
+ );
49790
+ } catch (e) {
49791
+ throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, "Substrate search") ?? e;
49792
+ }
49651
49793
  text = r.body;
49652
49794
  return r.res;
49653
49795
  });
@@ -50306,6 +50448,10 @@ function compactMessage(m) {
50306
50448
  ...m.subject !== void 0 ? { subject: m.subject } : {}
50307
50449
  };
50308
50450
  }
50451
+ function formatFlatMessage(m, format) {
50452
+ if (format === "full") return m;
50453
+ return { ...compactMessage(m), ...m.replyTo !== void 0 ? { replyTo: m.replyTo } : {} };
50454
+ }
50309
50455
  var isMissing = (root) => "missing" in root;
50310
50456
  var isOutside = (root) => "outside_window" in root;
50311
50457
  function newestTime(messages) {
@@ -50359,6 +50505,85 @@ function formatBody(kind, messages, format, roots = NO_ROOTS) {
50359
50505
  return channel ? { threads: groupThreads(messages, roots) } : { messages: [...messages] };
50360
50506
  }
50361
50507
 
50508
+ // src/tools/from.ts
50509
+ init_zod();
50510
+ init_dist2();
50511
+ var FROM_MAX_RAW = 2e4;
50512
+ var FROM_MAX_PAGES = 100;
50513
+ var fromArg = external_exports.string().min(1).optional().describe(
50514
+ "Page oldest first from here: a UTC time (ISO 8601, e.g. 2026-10-01T00:00:00Z; one with no zone is read as UTC) or a previous result's next_from, unchanged. Returns messages that arrived at or after it, oldest first, up to limit, with next_from (pass it back as from for the next page \u2014 also once has_more is false, to pick up what arrives later) and has_more."
50515
+ );
50516
+ var FROM_DESCRIPTION = `from pages oldest first for ingestion and backfill: messages that arrived at or after a UTC time (or a previous result's next_from), oldest first, at most limit; next_from (always returned, with next_from_time) resumes after the last message returned and has_more says whether more are already waiting. Pass an old from and keep passing next_from to backfill; once has_more is false the same next_from picks up what arrives later. Delivery is at-least-once: dedupe on message id. Teams pages newest first, so a from call reads everything since from (up to ${FROM_MAX_RAW} raw messages per conversation, past which it never skips silently: it says what it could not read): the further back from is, the slower the call. `;
50517
+ function badFrom(from) {
50518
+ return new McpToolError(`"${from}" is not a from position.`, {
50519
+ hint: "Pass a UTC time such as 2026-10-01T00:00:00Z, or a previous result's next_from unchanged."
50520
+ });
50521
+ }
50522
+ function decodeFrom(from) {
50523
+ if (/^[A-Za-z0-9_-]+$/.test(from)) {
50524
+ let parsed;
50525
+ try {
50526
+ parsed = JSON.parse(Buffer.from(from, "base64url").toString("utf8"));
50527
+ } catch {
50528
+ parsed = void 0;
50529
+ }
50530
+ if (parsed !== void 0) {
50531
+ const { t: t2, s } = parsed ?? {};
50532
+ const seen = s === void 0 ? [] : s;
50533
+ if (typeof t2 === "number" && Number.isFinite(t2) && t2 >= 0 && Array.isArray(seen) && seen.every((k) => typeof k === "string")) {
50534
+ return { t: t2, seen };
50535
+ }
50536
+ throw badFrom(from);
50537
+ }
50538
+ }
50539
+ if (!/^\d{4}-\d{2}-\d{2}/.test(from)) throw badFrom(from);
50540
+ const zoned = /T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(from) ? `${from}Z` : from;
50541
+ const t = Date.parse(zoned);
50542
+ if (Number.isNaN(t)) throw badFrom(from);
50543
+ return { t, seen: [] };
50544
+ }
50545
+ function encodeFrom({ t, seen }) {
50546
+ return Buffer.from(JSON.stringify(seen.length > 0 ? { t, s: seen } : { t }), "utf8").toString("base64url");
50547
+ }
50548
+ function takePage(items, pos, limit, ceiling) {
50549
+ const seen = new Set(pos.seen);
50550
+ const pending = items.filter((i) => i.ms > pos.t || i.ms === pos.t && !seen.has(i.key)).sort((a, b) => a.ms - b.ms || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
50551
+ const page = pending.slice(0, limit);
50552
+ const last = page.at(-1);
50553
+ let next = pos;
50554
+ if (last !== void 0) {
50555
+ const t = Math.max(pos.t, ceiling !== void 0 ? Math.min(last.ms, ceiling) : last.ms);
50556
+ const atT = page.filter((i) => i.ms === t).map((i) => i.key);
50557
+ next = { t, seen: t === pos.t ? [...pos.seen, ...atT] : atT };
50558
+ }
50559
+ return { page: page.map((i) => i.item), has_more: pending.length > page.length, remaining: pending.length - page.length, next };
50560
+ }
50561
+ function fromReport(pos, next, hasMore) {
50562
+ return {
50563
+ from_time: new Date(pos.t).toISOString(),
50564
+ has_more: hasMore,
50565
+ next_from: encodeFrom(next),
50566
+ next_from_time: new Date(next.t).toISOString()
50567
+ };
50568
+ }
50569
+ async function readFrom(chatsvc, id, boundary) {
50570
+ let capped = false;
50571
+ const messages = await chatsvc.getMessages(id, {
50572
+ stopAt: (m) => changedMs(m) < boundary,
50573
+ max: FROM_MAX_RAW,
50574
+ maxPages: FROM_MAX_PAGES,
50575
+ onCapped: () => capped = true
50576
+ });
50577
+ if (!capped) return { messages };
50578
+ return { messages, reachedMs: Math.min(...messages.map(changedMs)) };
50579
+ }
50580
+ function tooBusy(boundary, reachedMs) {
50581
+ return {
50582
+ error: `More than ${FROM_MAX_RAW} messages changed in this conversation since ${new Date(boundary).toISOString()}: a read reached back only to ${new Date(reachedMs).toISOString()}, as Teams pages newest first.`,
50583
+ hint: "Pass a later from."
50584
+ };
50585
+ }
50586
+
50362
50587
  // src/tools/roots.ts
50363
50588
  init_dist2();
50364
50589
  var MAX_ROOT_FETCHES = 25;
@@ -50826,7 +51051,37 @@ async function resolveListed(chatsvc, raw, me, conversation, verb) {
50826
51051
  }
50827
51052
  var MAX_CONVERSATIONS = 20;
50828
51053
  var READ_CONCURRENCY = 4;
50829
- async function readOne(chatsvc, raw, me, summary, { unreadOnly, since, afterMessageId, limit, timeZone, format, roots }) {
51054
+ async function readOneFrom(chatsvc, raw, me, summary, pos, { unreadOnly, limit, timeZone, format, roots }) {
51055
+ const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
51056
+ const horizon = readHorizon(conv);
51057
+ const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
51058
+ const boundary = unreadOnly ? Math.max(pos.t, horizon + 1) : pos.t;
51059
+ const { messages: fetched, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
51060
+ if (reachedMs !== void 0) {
51061
+ const { error: error62, hint } = tooBusy(boundary, reachedMs);
51062
+ throw new McpToolError(error62, { hint });
51063
+ }
51064
+ const { page, has_more, next } = takePage(
51065
+ fetched.filter(wanted).map((m) => ({ ms: arrivalMs(m), key: m.id, item: m })),
51066
+ pos,
51067
+ limit
51068
+ );
51069
+ const messages = page.map((m) => normaliseMessage(m, me, { timeZone }));
51070
+ const outsideRoots = summary.kind === "channel" ? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone }) : void 0;
51071
+ return {
51072
+ summary,
51073
+ conv,
51074
+ newest: newestId(page),
51075
+ result: {
51076
+ conversation: formatConversation(summary, format),
51077
+ ...formatBody(summary.kind, messages, format, outsideRoots),
51078
+ ...fromReport(pos, next, has_more)
51079
+ }
51080
+ };
51081
+ }
51082
+ async function readOne(chatsvc, raw, me, summary, opts) {
51083
+ if (opts.from !== void 0) return readOneFrom(chatsvc, raw, me, summary, opts.from, opts);
51084
+ const { unreadOnly, since, afterMessageId, limit, timeZone, format, roots } = opts;
50830
51085
  const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
50831
51086
  const horizon = readHorizon(conv);
50832
51087
  const cutoff = since !== void 0 ? Date.parse(since) : void 0;
@@ -50935,7 +51190,7 @@ function registerConversationTools(server, { chatsvc }) {
50935
51190
  "teams_read_conversation",
50936
51191
  {
50937
51192
  title: "Read a Teams chat or channel",
50938
- description: `Read the messages of any chat or channel the signed-in user is in, by id (from teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in Teams. "48:notes" (or the name "notes" / "self") is the user's own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, each root post with its replies. A root older than the window is fetched and marked outside_window: true (it is context, not counted or cursored); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. unread_only returns just the messages the user has not read; since stops at a time; limit keeps the newest (truncated says when more exist; unread_count_scope "window" says unread_count only covers what limit/since/after_message_id let through). after_message_id returns only messages newer than that id; next_cursor is the newest returned message id (or after_message_id when nothing is new) \u2014 pass it back as after_message_id to read only what arrived since. after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then { conversations: [...], errors, fetched_at }, one single-read result per conversation (the other arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ... } object a single read returns, and one that cannot be resolved or read is listed in errors while the rest still come back. ` + MARK_READ_DESCRIPTION + "With mark_read the read marker of each conversation read moves up to the newest message returned (never backwards; outside_window roots do not count) and its result says marked_read; one whose limit or since cut off unread messages older than those returned is not marked (marked_read: { skipped, hint }), while a limit that cut only already-read messages does not stop it; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. " + CONFIRM_INJECTION_RULE + " Attachments are listed per message (images by ref, files by name) and fetched with teams_get_attachment. A name that matches several conversations is not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each with id, title, kind, team, lastActivity and match_reason), hint} and no messages \u2014 read again with one candidate's id. " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
51193
+ description: `Read the messages of any chat or channel the signed-in user is in, by id (from teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in Teams. "48:notes" (or the name "notes" / "self") is the user's own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, each root post with its replies. A root older than the window is fetched and marked outside_window: true (it is context, not counted or cursored); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. unread_only returns just the messages the user has not read; since stops at a time; limit keeps the newest (truncated says when more exist; unread_count_scope "window" says unread_count only covers what limit/since/after_message_id let through). after_message_id returns only messages newer than that id; next_cursor is the newest returned message id (or after_message_id when nothing is new) \u2014 pass it back as after_message_id to read only what arrived since. after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then { conversations: [...], errors, fetched_at }, one single-read result per conversation (the other arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ... } object a single read returns, and one that cannot be resolved or read is listed in errors while the rest still come back. ` + FROM_DESCRIPTION + "With from, limit keeps the OLDEST messages, unread_only pages only unread ones, and since, after_message_id and mark_read cannot be used; the result carries from_time, has_more, next_from and next_from_time in place of unread_count and next_cursor. " + MARK_READ_DESCRIPTION + "With mark_read the read marker of each conversation read moves up to the newest message returned (never backwards; outside_window roots do not count) and its result says marked_read; one whose limit or since cut off unread messages older than those returned is not marked (marked_read: { skipped, hint }), while a limit that cut only already-read messages does not stop it; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. " + CONFIRM_INJECTION_RULE + " Attachments are listed per message (images by ref, files by name) and fetched with teams_get_attachment. A name that matches several conversations is not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each with id, title, kind, team, lastActivity and match_reason), hint} and no messages \u2014 read again with one candidate's id. " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
50939
51194
  // A write only with mark_read, but a write: it moves the user's read marker (never backwards, so a repeat is a no-op).
50940
51195
  annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
50941
51196
  inputSchema: {
@@ -50945,20 +51200,30 @@ function registerConversationTools(server, { chatsvc }) {
50945
51200
  unread_only: external_exports.boolean().optional().describe("Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set."),
50946
51201
  since: sinceArg,
50947
51202
  after_message_id: afterMessageIdArg,
50948
- limit: limitArg(MAX_MESSAGES, "messages"),
51203
+ from: fromArg,
51204
+ limit: limitArg(MAX_MESSAGES, "messages", "newest first kept; with from, oldest first kept"),
50949
51205
  tz: tzArg,
50950
51206
  format: formatArg,
50951
51207
  mark_read: markReadArg,
50952
51208
  confirmToken: confirmTokenParam
50953
51209
  }
50954
51210
  },
50955
- async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
51211
+ async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, confirmToken }, ctx) => {
50956
51212
  try {
50957
51213
  assertMarkReadFormat(mark_read, format);
51214
+ if (from !== void 0) {
51215
+ const clash = since !== void 0 ? "since" : after_message_id !== void 0 ? "after_message_id" : mark_read ? "mark_read" : void 0;
51216
+ if (clash !== void 0) {
51217
+ throw new McpToolError(`from cannot be combined with ${clash}.`, {
51218
+ hint: "from is its own position: pass a previous next_from to go on. To mark what was paged read, use teams_mark_read."
51219
+ });
51220
+ }
51221
+ }
50958
51222
  const opts = {
50959
51223
  unreadOnly: unread_only ?? false,
50960
51224
  since,
50961
51225
  afterMessageId: after_message_id,
51226
+ from: from !== void 0 ? decodeFrom(from) : void 0,
50962
51227
  limit: limit ?? DEFAULT_LIMIT,
50963
51228
  timeZone: resolveTimeZone(tz),
50964
51229
  format: format ?? "full",
@@ -51013,6 +51278,7 @@ var MAX_PER_CONVERSATION = 200;
51013
51278
  var DEFAULT_PER_CONVERSATION = 50;
51014
51279
  var MAX_CONVERSATIONS2 = 50;
51015
51280
  var DEFAULT_CONVERSATIONS = 20;
51281
+ var MAX_FROM_MESSAGES = 500;
51016
51282
  var MAX_RAW_MESSAGES2 = 4e3;
51017
51283
  var ROOT_CONVERSATION_CONCURRENCY = 4;
51018
51284
  var KIND_FILTERS = {
@@ -51028,12 +51294,77 @@ var TRUNCATED_SKIP = {
51028
51294
  function byLastActivityDesc2(a, b) {
51029
51295
  return (b.lastActivity ?? "").localeCompare(a.lastActivity ?? "");
51030
51296
  }
51297
+ async function unreadFrom(chatsvc, raw, me, candidates, pos, { limit, timeZone, format }) {
51298
+ const byId = new Map(raw.map((c) => [c.id, c]));
51299
+ const toRead = candidates.filter((s) => (lastChangeMs(byId.get(s.id) ?? { id: s.id }) ?? Infinity) >= pos.t);
51300
+ const results = await mapWithConcurrency(toRead, CONFIRM_CONCURRENCY, async (summary) => {
51301
+ const horizon = readHorizon(byId.get(summary.id) ?? { id: summary.id });
51302
+ try {
51303
+ const boundary = Math.max(pos.t, horizon + 1);
51304
+ const { messages, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
51305
+ const known = (m) => reachedMs === void 0 || arrivalMs(m) > reachedMs;
51306
+ return { kind: "read", messages: messages.filter((m) => isUnread(m, horizon, me) && known(m)), boundary, reachedMs };
51307
+ } catch (error62) {
51308
+ return isUnreachable(error62) ? { kind: "unreachable" } : { kind: "failed", error: error62 };
51309
+ }
51310
+ });
51311
+ let skippedUnreachable = 0;
51312
+ let anyRead = false;
51313
+ const items = [];
51314
+ const failed = [];
51315
+ const tooDeep = [];
51316
+ results.forEach((r, i) => {
51317
+ const summary = toRead[i];
51318
+ if (r.kind === "unreachable") skippedUnreachable++;
51319
+ else if (r.kind === "failed") failed.push({ summary, error: r.error });
51320
+ else {
51321
+ anyRead = true;
51322
+ if (r.reachedMs !== void 0) tooDeep.push({ summary, boundary: r.boundary, reachedMs: r.reachedMs });
51323
+ for (const m of r.messages) items.push({ ms: arrivalMs(m), key: `${summary.id}/${m.id}`, item: { summary, m } });
51324
+ }
51325
+ });
51326
+ if (failed.length > 0 && !anyRead) throw failed[0].error;
51327
+ const listed = Math.max(pos.t, ...raw.map((c) => lastChangeMs(c) ?? 0));
51328
+ const { page, has_more, remaining, next } = takePage(items, pos, limit, failed.length > 0 ? pos.t : listed);
51329
+ const shown = [...new Map(page.map(({ summary }) => [summary.id, summary])).values()];
51330
+ const titled = await enrichTitles(chatsvc, raw, me, [
51331
+ ...shown,
51332
+ ...failed.map((f) => f.summary),
51333
+ ...tooDeep.map((d) => d.summary)
51334
+ ]);
51335
+ const titledDeep = titled.slice(shown.length + failed.length);
51336
+ return {
51337
+ total_unread: page.length + remaining,
51338
+ messages: page.map(({ summary, m }) => ({
51339
+ conversation_id: summary.id,
51340
+ ...formatFlatMessage(normaliseMessage(m, me, { timeZone }), format)
51341
+ })),
51342
+ conversations: titled.slice(0, shown.length).map((s) => formatConversation(confirmedSummary(s, true), format)),
51343
+ ...fromReport(pos, next, has_more),
51344
+ skipped_unreachable: skippedUnreachable,
51345
+ ...failed.length > 0 ? {
51346
+ errors: failed.map((f, i) => ({
51347
+ conversation: titled[shown.length + i],
51348
+ error: wrapApiError(f.error, "read this conversation").message
51349
+ }))
51350
+ } : {},
51351
+ ...tooDeep.length > 0 ? {
51352
+ incomplete: tooDeep.map((d, i) => ({
51353
+ conversation: titledDeep[i],
51354
+ unread_not_read_from: new Date(d.boundary).toISOString(),
51355
+ unread_not_read_until: new Date(d.reachedMs).toISOString(),
51356
+ ...tooBusy(d.boundary, d.reachedMs)
51357
+ }))
51358
+ } : {}
51359
+ };
51360
+ }
51361
+ var NOT_WITH_FROM = ["since_days", "cursors", "per_conversation_limit", "max_conversations", "mark_read", "older_unread"];
51031
51362
  function registerUnreadTools(server, { chatsvc }) {
51032
51363
  server.registerTool(
51033
51364
  "teams_get_unread",
51034
51365
  {
51035
51366
  title: "Get unread Teams messages",
51036
- description: `Get every unread message across all the chats and channels the signed-in user is in (or those matching kinds / query), grouped by conversation, most recent activity first. Each conversation comes with its summary (id, kind, title, team) and only the messages the user has not read, oldest first; a channel's are grouped as threads under their root post. A root the user already read is fetched and marked outside_window: true (it is context, not unread or counted); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. Exact, as in Teams: every conversation with activity past its read marker (or never opened) is read past the marker and kept only if it holds a real message from someone else, so a call recording, transcript or other system event never makes a conversation unread. Channels the user has hidden in Teams are left out (include_hidden adds them); one that is gone or no longer readable (404/403) is skipped and counted in skipped_unreachable. Only conversations whose newest unread message is from the last 14 days are returned by default (since_days widens or narrows it); older unread conversations \u2014 typically dormant channels \u2014 are not read past their marker and are counted in older_unread_skipped; older_unread: true also lists them in older_unread_conversations (id, kind, title, team, lastActivity, and unread_count only for those already read \u2014 unread_count_known: false otherwise). Chats the user muted in Teams (muted: true) are left out too and counted in muted_skipped, without being read; include_muted adds them. Unread conversations past max_conversations are listed by id, title and unread_count in more_unread_conversations; read one with teams_read_conversation. A conversation that could not be read is listed in errors and the rest still come back. total_unread covers every unread conversation found; total_unread_exact is false when a per-conversation limit truncated or a read failed. cursors ({ conversationId: messageId }) returns only unread messages newer than each conversation's cursor (one with none is left out, and total_unread counts only those). Each returned conversation carries next_cursor, its newest returned message id; next_cursors is the cursors passed in updated with every returned conversation's next_cursor (not those only in more_unread_conversations) \u2014 pass it back as cursors to get only what is new. ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + MARK_READ_DESCRIPTION + 'With mark_read each conversation returned with its messages (not more_unread_conversations) has its read marker moved up to its newest unread message returned (outside_window roots do not count) and carries marked_read (false with mark_read_warning when that move failed); one per_conversation_limit cut is not marked \u2014 marked_read: { skipped: "truncated", hint }; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. ' + CONFIRM_INJECTION_RULE + " " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names, and the last-message preview. " + MATCH_REASON_DESCRIPTION + "Message times are UTC (ISO 8601); " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
51367
+ description: `Get every unread message across all the chats and channels the signed-in user is in (or those matching kinds / query), grouped by conversation, most recent activity first. Each conversation comes with its summary (id, kind, title, team) and only the messages the user has not read, oldest first; a channel's are grouped as threads under their root post. A root the user already read is fetched and marked outside_window: true (it is context, not unread or counted); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. Exact, as in Teams: every conversation with activity past its read marker (or never opened) is read past the marker and kept only if it holds a real message from someone else, so a call recording, transcript or other system event never makes a conversation unread. Channels the user has hidden in Teams are left out (include_hidden adds them); one that is gone or no longer readable (404/403) is skipped and counted in skipped_unreachable. Only conversations whose newest unread message is from the last 14 days are returned by default (since_days widens or narrows it); older unread conversations \u2014 typically dormant channels \u2014 are not read past their marker and are counted in older_unread_skipped; older_unread: true also lists them in older_unread_conversations (id, kind, title, team, lastActivity, and unread_count only for those already read \u2014 unread_count_known: false otherwise). Chats the user muted in Teams (muted: true) are left out too and counted in muted_skipped, without being read; include_muted adds them. Unread conversations past max_conversations are listed by id, title and unread_count in more_unread_conversations; read one with teams_read_conversation. A conversation that could not be read is listed in errors and the rest still come back. total_unread covers every unread conversation found; total_unread_exact is false when a per-conversation limit truncated or a read failed. cursors ({ conversationId: messageId }) returns only unread messages newer than each conversation's cursor (one with none is left out, and total_unread counts only those). Each returned conversation carries next_cursor, its newest returned message id; next_cursors is the cursors passed in updated with every returned conversation's next_cursor (not those only in more_unread_conversations) \u2014 pass it back as cursors to get only what is new. ` + CURSOR_NO_CACHE_DESCRIPTION + FROM_DESCRIPTION + "With from the result is one list across every conversation instead: messages (each with its conversation_id; a channel reply keeps replyTo), oldest first, at most limit; conversations (the summary of each one on the page); total_unread (every unread message past from, this page and later ones); from_time, has_more, next_from, next_from_time; skipped_unreachable, muted_skipped and errors. next_from does not move while a read failed (call again). A conversation with more messages since from than a read can reach is listed in incomplete instead (unread_not_read_from / unread_not_read_until name the stretch not read; what arrived after it is returned) and does not hold next_from. from takes the place of since_days, cursors, per_conversation_limit, max_conversations, older_unread and mark_read, and format summary does not apply. " + FORMAT_DESCRIPTION + MARK_READ_DESCRIPTION + 'With mark_read each conversation returned with its messages (not more_unread_conversations) has its read marker moved up to its newest unread message returned (outside_window roots do not count) and carries marked_read (false with mark_read_warning when that move failed); one per_conversation_limit cut is not marked \u2014 marked_read: { skipped: "truncated", hint }; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. ' + CONFIRM_INJECTION_RULE + " " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names, and the last-message preview. " + MATCH_REASON_DESCRIPTION + "Message times are UTC (ISO 8601); " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
51037
51368
  // A write only with mark_read, but a write: it moves the user's read markers (never backwards, so a repeat is a no-op).
51038
51369
  annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
51039
51370
  inputSchema: {
@@ -51056,6 +51387,10 @@ function registerUnreadTools(server, { chatsvc }) {
51056
51387
  `Maximum unread conversations returned with their messages, most recent activity first (default ${DEFAULT_CONVERSATIONS}, max ${MAX_CONVERSATIONS2}); the rest are listed in more_unread_conversations.`
51057
51388
  ),
51058
51389
  cursors: cursorsArg,
51390
+ from: fromArg,
51391
+ limit: external_exports.number().int().min(1).max(MAX_FROM_MESSAGES).optional().describe(
51392
+ `With from only: maximum messages returned across every conversation, oldest first (default ${DEFAULT_LIMIT}, max ${MAX_FROM_MESSAGES}).`
51393
+ ),
51059
51394
  tz: tzArg,
51060
51395
  format: formatArg,
51061
51396
  mark_read: markReadArg,
@@ -51072,6 +51407,8 @@ function registerUnreadTools(server, { chatsvc }) {
51072
51407
  per_conversation_limit,
51073
51408
  max_conversations,
51074
51409
  cursors,
51410
+ from,
51411
+ limit,
51075
51412
  tz,
51076
51413
  format,
51077
51414
  mark_read,
@@ -51079,6 +51416,21 @@ function registerUnreadTools(server, { chatsvc }) {
51079
51416
  }, ctx) => {
51080
51417
  try {
51081
51418
  assertMarkReadFormat(mark_read, format);
51419
+ if (from === void 0 && limit !== void 0) {
51420
+ throw new McpToolError("limit applies only with from.", {
51421
+ hint: "Without from, use per_conversation_limit and max_conversations."
51422
+ });
51423
+ }
51424
+ if (from !== void 0) {
51425
+ const args = { since_days, cursors, per_conversation_limit, max_conversations, mark_read, older_unread };
51426
+ const clash = NOT_WITH_FROM.find((k) => args[k] !== void 0 && args[k] !== false);
51427
+ if (clash !== void 0 || format === "summary") {
51428
+ throw new McpToolError(`from cannot be combined with ${clash ?? "format summary"}.`, {
51429
+ hint: "from pages one oldest-first list across every conversation: pass a previous next_from to go on, and use teams_mark_read to mark what was paged read."
51430
+ });
51431
+ }
51432
+ }
51433
+ const pos = from !== void 0 ? decodeFrom(from) : void 0;
51082
51434
  const timeZone = resolveTimeZone(tz);
51083
51435
  const fetched_at = (/* @__PURE__ */ new Date()).toISOString();
51084
51436
  const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
@@ -51090,6 +51442,14 @@ function registerUnreadTools(server, { chatsvc }) {
51090
51442
  const mutedSkipped = include_muted ? 0 : candidates.filter((s) => s.muted).length;
51091
51443
  if (!include_muted) candidates = candidates.filter((s) => !s.muted);
51092
51444
  candidates.sort(byLastActivityDesc2);
51445
+ if (pos !== void 0) {
51446
+ const page = await unreadFrom(chatsvc, raw, me, candidates, pos, {
51447
+ limit: limit ?? DEFAULT_LIMIT,
51448
+ timeZone,
51449
+ format: format === "compact" ? "compact" : "full"
51450
+ });
51451
+ return untrustedResult2({ ...page, muted_skipped: mutedSkipped, fetched_at });
51452
+ }
51093
51453
  const perLimit = per_conversation_limit ?? DEFAULT_PER_CONVERSATION;
51094
51454
  const outcome = await confirmUnreadCandidates(
51095
51455
  chatsvc,
@@ -51220,11 +51580,6 @@ function decodeChangesCursor(cursor) {
51220
51580
  if (Number.isNaN(t)) throw badCursor(cursor);
51221
51581
  return t;
51222
51582
  }
51223
- function changedMs(m) {
51224
- const v = Number(m.version);
51225
- const id = Number(m.id);
51226
- return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
51227
- }
51228
51583
  async function readChanges(chatsvc, summary, t, me) {
51229
51584
  let capped = false;
51230
51585
  const fetched = await chatsvc.getMessages(summary.id, {
@@ -51472,6 +51827,9 @@ function degradeHint(err, host) {
51472
51827
  if (errorKindOf(err) === "no_credential") {
51473
51828
  return "SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.";
51474
51829
  }
51830
+ if (errorKindOf(err) === "transport" && err instanceof McpToolError) {
51831
+ return err.hint !== void 0 ? `${err.message} ${err.hint}` : err.message;
51832
+ }
51475
51833
  if (err instanceof McpToolError && err.hint !== void 0) return err.hint;
51476
51834
  return `Couldn't mint a SharePoint token for ${host} \u2014 open the shared file once in a signed-in Teams tab (that browser request is where the token is captured from), then retry.`;
51477
51835
  }