@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/chatsvc.js CHANGED
@@ -19,10 +19,11 @@
19
19
  * live facts" section of `docs/plans/2026-10-10-chatsvc-api.md` for the
20
20
  * response shapes the types below describe.
21
21
  */
22
- import { decodeJwtClaim, decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
22
+ import { decodeJwtClaim, decodeJwtExp, fetchBounded, errorKindOf, McpToolError, parseBoolEnv, readEnvVar, RequestTimeoutError, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
23
23
  import { TokenManager } from '@chrischall/mcp-utils/session';
24
24
  import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
25
25
  import { SELF_CHAT } from './model.js';
26
+ import { describeTransportFailure } from './network-error.js';
26
27
  /**
27
28
  * Load the bridge bootstrap lazily.
28
29
  *
@@ -79,6 +80,29 @@ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
79
80
  * host varies by region). The bearer is sent ONLY to hosts under this suffix.
80
81
  */
81
82
  const IMAGE_HOST_SUFFIX = '.asm.skype.com';
83
+ /**
84
+ * The Teams gateway in front of the same image store. Verified live
85
+ * 2026-10-12: `GET https://us-prod.asyncgw.teams.microsoft.com/v1/objects/<id>/views/imgo`
86
+ * with the chat-service bearer returns the identical bytes for objects of
87
+ * either region (`0-sin-…` and `0-eus-…`). Some networks reset every
88
+ * connection to `*.asm.skype.com` while allowing teams.microsoft.com, so an
89
+ * image the store cannot be REACHED at is retried here — never one the store
90
+ * answered. Only ever reached by rewriting a vetted `*.asm.skype.com` URL,
91
+ * never from a URL in message content.
92
+ */
93
+ const IMAGE_GATEWAY_HOST = 'us-prod.asyncgw.teams.microsoft.com';
94
+ /** What a transport failure calls the far side: the image store, or the chat service. */
95
+ function serviceFor(url) {
96
+ try {
97
+ const host = new URL(url).hostname;
98
+ if (host.endsWith(IMAGE_HOST_SUFFIX))
99
+ return "Teams' image store";
100
+ return host === IMAGE_GATEWAY_HOST ? 'the Teams image gateway' : 'the Teams chat service';
101
+ }
102
+ catch {
103
+ return 'the Teams chat service';
104
+ }
105
+ }
82
106
  /**
83
107
  * A write that failed after it may have reached Teams. A timeout or a
84
108
  * transport failure (dropped connection, broken body, the caller cancelling)
@@ -233,18 +257,19 @@ export class ChatServiceClient {
233
257
  }
234
258
  /**
235
259
  * A conversation's messages, newest first, paging back until `stopAt`
236
- * accepts a message, `max` are collected, the pages run out, or 20 pages
237
- * have been read.
260
+ * accepts a message, `max` are collected, the pages run out, or `maxPages`
261
+ * (default 20) have been read.
238
262
  */
239
263
  async getMessages(id, opts) {
240
264
  this.#requireConfigured();
241
265
  const out = [];
242
266
  if (!(opts.max > 0))
243
267
  return out;
268
+ const seen = new Set();
244
269
  let url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages` +
245
270
  `?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
246
271
  for (let page = 0; url !== undefined; page++) {
247
- if (page >= MAX_MESSAGE_PAGES) {
272
+ if (page >= (opts.maxPages ?? MAX_MESSAGE_PAGES)) {
248
273
  opts.onCapped?.();
249
274
  break;
250
275
  }
@@ -257,6 +282,12 @@ export class ChatServiceClient {
257
282
  // each message it rejects — and only the NEXT page is not fetched.
258
283
  let stopped = false;
259
284
  for (const m of msgs) {
285
+ // Live (2026-10-14) the service served one message — same id, same version — on two pages
286
+ // (2 of 567). The first copy stands; a repeat is neither returned nor shown to `stopAt`,
287
+ // whose limit counting would otherwise count it twice.
288
+ if (seen.has(m.id))
289
+ continue;
290
+ seen.add(m.id);
260
291
  if (opts.stopAt?.(m)) {
261
292
  stopped = true;
262
293
  continue;
@@ -382,6 +413,24 @@ export class ChatServiceClient {
382
413
  hint: `Only https images on *${IMAGE_HOST_SUFFIX} (Teams' own image store) are fetched.`,
383
414
  });
384
415
  }
416
+ try {
417
+ return await this.#getImage(target);
418
+ }
419
+ catch (e) {
420
+ if (errorKindOf(e) !== 'transport')
421
+ throw e;
422
+ const viaGateway = new URL(target.pathname + target.search, `https://${IMAGE_GATEWAY_HOST}`);
423
+ try {
424
+ return await this.#getImage(viaGateway);
425
+ }
426
+ catch (e2) {
427
+ if (errorKindOf(e2) !== 'transport')
428
+ throw e2;
429
+ throw new McpToolError(`${e.message} The Teams gateway was tried too: ${e2.message}`, { kind: 'transport', hint: e.hint, cause: e });
430
+ }
431
+ }
432
+ }
433
+ async #getImage(target) {
385
434
  const { status, headers, body } = await this.#send(target.toString(), 'bytes', MAX_IMAGE_BYTES);
386
435
  this.#checkStatus(status);
387
436
  const mimeType = (headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
@@ -478,7 +527,9 @@ export class ChatServiceClient {
478
527
  r = await fetchBounded(url, init, opts);
479
528
  }
480
529
  catch (e) {
481
- throw write ? outcomeUnknown(method, e, write.hint) : e;
530
+ if (write)
531
+ throw outcomeUnknown(method, e, write.hint);
532
+ throw describeTransportFailure(e, url, serviceFor(url)) ?? e;
482
533
  }
483
534
  body = r.body;
484
535
  return r.res;
package/dist/model.js CHANGED
@@ -512,6 +512,16 @@ export function localIsoTime(iso, timeZone) {
512
512
  return (`${pad(get('year'), 4)}-${pad(get('month'))}-${pad(get('day'))}T${pad(get('hour'))}:${pad(get('minute'))}:` +
513
513
  `${pad(get('second'))}.${pad(millis, 3)}${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`);
514
514
  }
515
+ /**
516
+ * A message's last change (epoch ms): its `version`, else its arrival (the id).
517
+ * Live (2026-10-12), pages come newest CHANGE first, so a read that must not
518
+ * miss what arrived after a time stops on this, never on arrival.
519
+ */
520
+ export function changedMs(m) {
521
+ const v = Number(m.version);
522
+ const id = Number(m.id);
523
+ return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
524
+ }
515
525
  export function normaliseMessage(m, meMri, opts = {}) {
516
526
  const props = m.properties ?? {};
517
527
  const mri = senderMri(m.from);
@@ -0,0 +1,124 @@
1
+ /**
2
+ * A request that never got a response, said in a way someone can act on.
3
+ *
4
+ * Node's `fetch` (undici) reports every transport failure — DNS, a refused or
5
+ * reset connection, a TLS certificate it will not trust — as the same
6
+ * `TypeError('fetch failed')`, with the real reason on its `cause` chain.
7
+ * Surfaced as is, that reads "Failed to get the attachment: fetch failed",
8
+ * which names neither the host nor the reason (2026-10-12: two inline images
9
+ * on `in-api`/`us-api.asm.skype.com` failed that way on a machine whose
10
+ * chat-service calls to `teams.cloud.microsoft` were fine, while the same refs
11
+ * downloaded on another machine). This turns it into an `McpToolError` naming
12
+ * the HOST — never the path or query, which may carry ids — the cause's code,
13
+ * and a hint keyed to that code.
14
+ */
15
+ import { McpToolError } from '@chrischall/mcp-utils';
16
+ /** How far down a cause chain (and into an AggregateError) to look for a code. */
17
+ const MAX_CAUSE_DEPTH = 5;
18
+ const DNS_CODES = new Set(['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NONAME']);
19
+ const CONNECT_CODES = new Set([
20
+ 'ECONNREFUSED',
21
+ 'ECONNRESET',
22
+ 'ETIMEDOUT',
23
+ 'ENETUNREACH',
24
+ 'EHOSTUNREACH',
25
+ 'EPIPE',
26
+ 'UND_ERR_CONNECT_TIMEOUT',
27
+ 'UND_ERR_SOCKET',
28
+ 'UND_ERR_HEADERS_TIMEOUT',
29
+ ]);
30
+ const CERT_CODES = new Set([
31
+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
32
+ 'UNABLE_TO_GET_ISSUER_CERT',
33
+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
34
+ 'SELF_SIGNED_CERT_IN_CHAIN',
35
+ 'DEPTH_ZERO_SELF_SIGNED_CERT',
36
+ 'CERT_HAS_EXPIRED',
37
+ 'CERT_NOT_YET_VALID',
38
+ 'ERR_TLS_CERT_ALTNAME_INVALID',
39
+ ]);
40
+ function codeOf(e) {
41
+ if (e === null || typeof e !== 'object')
42
+ return undefined;
43
+ const code = e.code;
44
+ return typeof code === 'string' && code !== '' ? code : undefined;
45
+ }
46
+ /** The causes to look at, nearest first: the cause chain, and an AggregateError's members. */
47
+ function causes(err) {
48
+ const out = [];
49
+ let at = err;
50
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && at !== undefined && at !== null; depth++) {
51
+ out.push(at);
52
+ if (at instanceof AggregateError)
53
+ out.push(...at.errors);
54
+ at = at.cause;
55
+ }
56
+ return out;
57
+ }
58
+ /** The first system/undici error code on `err`'s cause chain. */
59
+ export function transportCauseCode(err) {
60
+ for (const e of causes(err)) {
61
+ const code = codeOf(e);
62
+ if (code !== undefined)
63
+ return code;
64
+ }
65
+ return undefined;
66
+ }
67
+ /** The innermost cause's message, which is where undici puts the real reason. */
68
+ function causeMessage(err) {
69
+ const chain = causes(err).slice(1);
70
+ for (let i = chain.length - 1; i >= 0; i--) {
71
+ const e = chain[i];
72
+ if (e instanceof Error && e.message !== '')
73
+ return e.message;
74
+ }
75
+ return undefined;
76
+ }
77
+ /** Whether `err` is `fetch`'s "never got a response" failure. */
78
+ function isFetchFailed(err) {
79
+ return err instanceof TypeError && err.message === 'fetch failed';
80
+ }
81
+ function hintFor(code, host) {
82
+ if (code !== undefined && DNS_CODES.has(code)) {
83
+ return (`This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves ` +
84
+ 'teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts ' +
85
+ `fails exactly like this. \`nslookup ${host}\` on the machine running this server tells you which.`);
86
+ }
87
+ if (code !== undefined && CERT_CODES.has(code)) {
88
+ return (`Node did not trust the TLS certificate ${host} presented. On a corporate network this is ` +
89
+ 'usually TLS inspection: export your proxy\'s root CA as PEM and start this server with ' +
90
+ 'NODE_EXTRA_CA_CERTS=/path/to/ca.pem (Node does not read the system keychain). If the ' +
91
+ 'certificate is expired or not yet valid, also check the machine\'s clock.');
92
+ }
93
+ if (code !== undefined && CONNECT_CODES.has(code)) {
94
+ return (`The connection to ${host} was refused, reset or timed out before Teams answered — usually a ` +
95
+ 'firewall, or a network that only lets traffic out through a proxy. Node\'s fetch ignores ' +
96
+ 'proxy settings unless told: start this server with HTTPS_PROXY=<your proxy URL> and ' +
97
+ 'NODE_USE_ENV_PROXY=1 (Node 22.21+ / 24.5+), or allow the host through the firewall.');
98
+ }
99
+ return (`No response from ${host}. Check this machine can reach it (VPN, proxy, firewall); ` +
100
+ `\`curl -sI https://${host}/\` from the same machine is a quick test.`);
101
+ }
102
+ /**
103
+ * An `McpToolError` describing `err` when it is `fetch`'s transport failure
104
+ * for `url`, else `undefined` (the caller rethrows `err` as it was).
105
+ */
106
+ export function describeTransportFailure(err, url, service) {
107
+ if (!isFetchFailed(err))
108
+ return undefined;
109
+ let host;
110
+ try {
111
+ host = new URL(url).hostname;
112
+ }
113
+ catch {
114
+ host = '(unknown host)';
115
+ }
116
+ const code = transportCauseCode(err);
117
+ const detail = [code, causeMessage(err)].filter((s) => s !== undefined);
118
+ const why = detail.length > 0 ? ` (${[...new Set(detail)].join(': ')})` : '';
119
+ return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
120
+ kind: 'transport',
121
+ hint: hintFor(code, host),
122
+ cause: err,
123
+ });
124
+ }
@@ -23,6 +23,7 @@
23
23
  * `fetch` — the bridge is only ever touched to capture the token.
24
24
  */
25
25
  import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
26
+ import { describeTransportFailure } from './network-error.js';
26
27
  import { TokenManager } from '@chrischall/mcp-utils/session';
27
28
  import { createSharePointTokenCache } from './sharepoint-token-cache.js';
28
29
  /**
@@ -53,6 +54,15 @@ const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
53
54
  const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
54
55
  /** Per-request deadline, covering the body read. */
55
56
  const REQUEST_TIMEOUT_MS = 60_000;
57
+ /** Run one fetch, turning "never got a response" into an error naming the host and cause. */
58
+ async function reachable(url, run) {
59
+ try {
60
+ return await run();
61
+ }
62
+ catch (e) {
63
+ throw describeTransportFailure(e, url, 'SharePoint') ?? e;
64
+ }
65
+ }
56
66
  /** Copied faithfully from `chatsvc.ts`: a captured token as `TokenManager` input. */
57
67
  function toBearerTokens(accessToken) {
58
68
  let expiresAt;
@@ -195,7 +205,7 @@ export class SharePointClient {
195
205
  async #getDriveItem(captureHost, url) {
196
206
  let body = '';
197
207
  const res = await this.#managerFor(captureHost).withAuth(async (token) => {
198
- const r = await fetchBounded(url, {
208
+ const r = await reachable(url, () => fetchBounded(url, {
199
209
  method: 'GET',
200
210
  headers: {
201
211
  authorization: `Bearer ${token}`,
@@ -203,7 +213,7 @@ export class SharePointClient {
203
213
  behavioroverride: 'redirectAs404',
204
214
  },
205
215
  redirect: 'error',
206
- }, { read: 'text', service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
216
+ }, { read: 'text', service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl }));
207
217
  body = r.body;
208
218
  return r.res;
209
219
  });
@@ -246,7 +256,7 @@ export class SharePointClient {
246
256
  hint: 'SharePoint download links are expected to be https.',
247
257
  });
248
258
  }
249
- const r = await fetchBounded(target.toString(), { method: 'GET', headers: { accept: '*/*' }, redirect: 'follow' }, { read: 'bytes', maxBytes, service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
259
+ const r = await reachable(target.toString(), () => fetchBounded(target.toString(), { method: 'GET', headers: { accept: '*/*' }, redirect: 'follow' }, { read: 'bytes', maxBytes, service: 'SharePoint', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl }));
250
260
  this.#checkStatus(r.status);
251
261
  const mimeType = (r.headers.get('content-type') ?? 'application/octet-stream').split(';')[0].trim();
252
262
  const data = Buffer.from(r.body);
package/dist/substrate.js CHANGED
@@ -51,6 +51,7 @@
51
51
  * (`substrate-auth.ts`); every request is a plain Node `fetch`.
52
52
  */
53
53
  import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
54
+ import { describeTransportFailure } from './network-error.js';
54
55
  import { TokenManager } from '@chrischall/mcp-utils/session';
55
56
  import { createSubstrateTokenCache } from './substrate-token-cache.js';
56
57
  export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
@@ -258,22 +259,28 @@ export class SubstrateClient {
258
259
  throw failed.error;
259
260
  let text = '';
260
261
  const res = await this.#manager.withAuth(async (token) => {
261
- const r = await fetchBounded(SUBSTRATE_QUERY_URL, {
262
- method: 'POST',
263
- headers: {
264
- authorization: `Bearer ${token}`,
265
- 'content-type': 'application/json',
266
- accept: 'application/json',
267
- },
268
- body: JSON.stringify(buildQueryBody(req)),
269
- redirect: 'error',
270
- }, {
271
- read: 'text',
272
- maxBytes: MAX_RESPONSE_BYTES,
273
- service: 'Substrate',
274
- timeoutMs: REQUEST_TIMEOUT_MS,
275
- fetchImpl: this.#fetchImpl,
276
- });
262
+ let r;
263
+ try {
264
+ r = await fetchBounded(SUBSTRATE_QUERY_URL, {
265
+ method: 'POST',
266
+ headers: {
267
+ authorization: `Bearer ${token}`,
268
+ 'content-type': 'application/json',
269
+ accept: 'application/json',
270
+ },
271
+ body: JSON.stringify(buildQueryBody(req)),
272
+ redirect: 'error',
273
+ }, {
274
+ read: 'text',
275
+ maxBytes: MAX_RESPONSE_BYTES,
276
+ service: 'Substrate',
277
+ timeoutMs: REQUEST_TIMEOUT_MS,
278
+ fetchImpl: this.#fetchImpl,
279
+ });
280
+ }
281
+ catch (e) {
282
+ throw describeTransportFailure(e, SUBSTRATE_QUERY_URL, 'Substrate search') ?? e;
283
+ }
277
284
  text = r.body;
278
285
  return r.res;
279
286
  });
@@ -167,6 +167,11 @@ function degradeHint(err, host) {
167
167
  if (errorKindOf(err) === 'no_credential') {
168
168
  return 'SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.';
169
169
  }
170
+ // A network failure is about this machine's route to the host, not the token:
171
+ // say which host and why, never "open the file once in Teams".
172
+ if (errorKindOf(err) === 'transport' && err instanceof McpToolError) {
173
+ return err.hint !== undefined ? `${err.message} ${err.hint}` : err.message;
174
+ }
170
175
  if (err instanceof McpToolError && err.hint !== undefined)
171
176
  return err.hint;
172
177
  return (`Couldn't mint a SharePoint token for ${host} — open the shared file once in a signed-in Teams ` +
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { mapWithConcurrency, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
3
- import { conversationSummary, isUserMessage, lastChangeMs, normaliseMessage, } from '../model.js';
3
+ import { conversationSummary, changedMs, isUserMessage, lastChangeMs, normaliseMessage, } from '../model.js';
4
4
  import { isUnreachable } from './confirm.js';
5
5
  import { includeHiddenArg } from './listing.js';
6
6
  import { enrichTitles } from './titles.js';
@@ -54,12 +54,6 @@ export function decodeChangesCursor(cursor) {
54
54
  throw badCursor(cursor);
55
55
  return t;
56
56
  }
57
- /** A message's last change (epoch ms): its `version`, else its arrival (the id). */
58
- function changedMs(m) {
59
- const v = Number(m.version);
60
- const id = Number(m.id);
61
- return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
62
- }
63
57
  /** Read one conversation down to `t` and count what arrived after it. */
64
58
  async function readChanges(chatsvc, summary, t, me) {
65
59
  let capped = false;
@@ -9,6 +9,7 @@ import { DEFAULT_LIMIT, limitArg, makeLimitedStopAt, sinceArg } from './limit.js
9
9
  import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
10
10
  import { afterMessageIdArg, CURSOR_NO_CACHE_DESCRIPTION, newestId } from './cursor.js';
11
11
  import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
12
+ import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage, tooBusy } from './from.js';
12
13
  import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
13
14
  import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
14
15
  const MAX_MESSAGES = 500;
@@ -130,8 +131,43 @@ export async function resolveListed(chatsvc, raw, me, conversation, verb) {
130
131
  export const MAX_CONVERSATIONS = 20;
131
132
  /** Conversations read at once in a multi-conversation read. */
132
133
  export const READ_CONCURRENCY = 4;
134
+ /**
135
+ * One page of a conversation from a `from` position: everything since it read
136
+ * (`readFrom`), its real messages (unread ones with `unreadOnly`) taken oldest
137
+ * first (`takePage`).
138
+ */
139
+ async function readOneFrom(chatsvc, raw, me, summary, pos, { unreadOnly, limit, timeZone, format, roots }) {
140
+ const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
141
+ const horizon = readHorizon(conv);
142
+ const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
143
+ const boundary = unreadOnly ? Math.max(pos.t, horizon + 1) : pos.t;
144
+ const { messages: fetched, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
145
+ // Its oldest messages are unknown, and a page taken from what was read would skip them.
146
+ if (reachedMs !== undefined) {
147
+ const { error, hint } = tooBusy(boundary, reachedMs);
148
+ throw new McpToolError(error, { hint });
149
+ }
150
+ const { page, has_more, next } = takePage(fetched.filter(wanted).map((m) => ({ ms: arrivalMs(m), key: m.id, item: m })), pos, limit);
151
+ const messages = page.map((m) => normaliseMessage(m, me, { timeZone }));
152
+ const outsideRoots = summary.kind === 'channel'
153
+ ? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone })
154
+ : undefined;
155
+ return {
156
+ summary,
157
+ conv,
158
+ newest: newestId(page),
159
+ result: {
160
+ conversation: formatConversation(summary, format),
161
+ ...formatBody(summary.kind, messages, format, outsideRoots),
162
+ ...fromReport(pos, next, has_more),
163
+ },
164
+ };
165
+ }
133
166
  /** Read one resolved conversation. */
134
- async function readOne(chatsvc, raw, me, summary, { unreadOnly, since, afterMessageId, limit, timeZone, format, roots }) {
167
+ async function readOne(chatsvc, raw, me, summary, opts) {
168
+ if (opts.from !== undefined)
169
+ return readOneFrom(chatsvc, raw, me, summary, opts.from, opts);
170
+ const { unreadOnly, since, afterMessageId, limit, timeZone, format, roots } = opts;
135
171
  // The self-chat resolves even when the listing does not carry it.
136
172
  const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
137
173
  const horizon = readHorizon(conv);
@@ -299,6 +335,10 @@ export function registerConversationTools(server, { chatsvc }) {
299
335
  'arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ' +
300
336
  '... } object a single read returns, and one that cannot be resolved or read is listed in errors ' +
301
337
  'while the rest still come back. ' +
338
+ FROM_DESCRIPTION +
339
+ 'With from, limit keeps the OLDEST messages, unread_only pages only unread ones, and since, ' +
340
+ 'after_message_id and mark_read cannot be used; the result carries from_time, has_more, next_from and ' +
341
+ 'next_from_time in place of unread_count and next_cursor. ' +
302
342
  MARK_READ_DESCRIPTION +
303
343
  'With mark_read the read marker of each conversation read moves up to the newest message returned ' +
304
344
  '(never backwards; outside_window roots do not count) and its result says marked_read; one whose limit ' +
@@ -328,19 +368,30 @@ export function registerConversationTools(server, { chatsvc }) {
328
368
  .describe('Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set.'),
329
369
  since: sinceArg,
330
370
  after_message_id: afterMessageIdArg,
331
- limit: limitArg(MAX_MESSAGES, 'messages'),
371
+ from: fromArg,
372
+ limit: limitArg(MAX_MESSAGES, 'messages', 'newest first kept; with from, oldest first kept'),
332
373
  tz: tzArg,
333
374
  format: formatArg,
334
375
  mark_read: markReadArg,
335
376
  confirmToken: confirmTokenParam,
336
377
  },
337
- }, async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
378
+ }, async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, confirmToken }, ctx) => {
338
379
  try {
339
380
  assertMarkReadFormat(mark_read, format);
381
+ if (from !== undefined) {
382
+ const clash = since !== undefined ? 'since' : after_message_id !== undefined ? 'after_message_id' : mark_read ? 'mark_read' : undefined;
383
+ if (clash !== undefined) {
384
+ throw new McpToolError(`from cannot be combined with ${clash}.`, {
385
+ hint: 'from is its own position: pass a previous next_from to go on. To mark what was paged read, use ' +
386
+ 'teams_mark_read.',
387
+ });
388
+ }
389
+ }
340
390
  const opts = {
341
391
  unreadOnly: unread_only ?? false,
342
392
  since,
343
393
  afterMessageId: after_message_id,
394
+ from: from !== undefined ? decodeFrom(from) : undefined,
344
395
  limit: limit ?? DEFAULT_LIMIT,
345
396
  timeZone: resolveTimeZone(tz),
346
397
  format: format ?? 'full',
@@ -69,6 +69,16 @@ function compactMessage(m) {
69
69
  ...(m.subject !== undefined ? { subject: m.subject } : {}),
70
70
  };
71
71
  }
72
+ /**
73
+ * One message of a flat, cross-conversation list (`teams_get_unread` with
74
+ * `from`): whole in full; compact, but keeping `replyTo`, since no thread
75
+ * grouping says what a channel reply answers. Summary has no messages.
76
+ */
77
+ export function formatFlatMessage(m, format) {
78
+ if (format === 'full')
79
+ return m;
80
+ return { ...compactMessage(m), ...(m.replyTo !== undefined ? { replyTo: m.replyTo } : {}) };
81
+ }
72
82
  const isMissing = (root) => 'missing' in root;
73
83
  const isOutside = (root) => 'outside_window' in root;
74
84
  /** The newest of oldest-first `messages`, as `newest_time` (and `newest_time_local`); nothing for none. */
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Oldest-first paging from a time: `from` in, `next_from` out.
3
+ *
4
+ * A caller ingesting messages passes a UTC time as `from` and gets what
5
+ * arrived at or after it, OLDEST first, at most `limit`; `next_from` is where
6
+ * the page ended, and passing it back as `from` returns the next page. It is
7
+ * always returned — on the last page too, and on an empty one (the position
8
+ * unchanged) — so the same loop that backfills history keeps polling for what
9
+ * is new. The server keeps no state: the position is the token.
10
+ *
11
+ * A position is a time plus the keys already returned AT that time (`seen`),
12
+ * so messages sharing a millisecond — across conversations, say — are neither
13
+ * skipped nor repeated when a page ends among them. The token is base64url
14
+ * JSON `{ t, s? }`; a plain ISO 8601 time is a position with nothing seen.
15
+ *
16
+ * The chat service pages newest first, so a page from `from` is found by
17
+ * reading everything that changed since `from` and taking its oldest: a call
18
+ * costs what has happened since its `from`, not its `limit`. Reads therefore
19
+ * stop on a message's last change, not its arrival (`changedMs`, as
20
+ * `teams_get_changes` learned), and run deeper than other reads
21
+ * ({@link FROM_MAX_RAW}); a conversation busier than that since `from` cannot
22
+ * be paged oldest first and says so.
23
+ */
24
+ import { z } from 'zod';
25
+ import { McpToolError } from '@chrischall/mcp-utils';
26
+ import { changedMs } from '../model.js';
27
+ /** Raw messages a `from` read may page through per conversation (100 pages of 200). */
28
+ export const FROM_MAX_RAW = 20_000;
29
+ export const FROM_MAX_PAGES = 100;
30
+ export const fromArg = z
31
+ .string()
32
+ .min(1)
33
+ .optional()
34
+ .describe('Page oldest first from here: a UTC time (ISO 8601, e.g. 2026-10-01T00:00:00Z; one with no zone is read ' +
35
+ "as UTC) or a previous result's next_from, unchanged. Returns messages that arrived at or after it, " +
36
+ 'oldest first, up to limit, with next_from (pass it back as from for the next page — also once has_more ' +
37
+ 'is false, to pick up what arrives later) and has_more.');
38
+ /** Shared description text for `from` paging. */
39
+ export const FROM_DESCRIPTION = 'from pages oldest first for ingestion and backfill: messages that arrived at or after a UTC time (or a ' +
40
+ "previous result's next_from), oldest first, at most limit; next_from (always returned, with next_from_time) " +
41
+ 'resumes after the last message returned and has_more says whether more are already waiting. Pass an old ' +
42
+ 'from and keep passing next_from to backfill; once has_more is false the same next_from picks up what ' +
43
+ 'arrives later. Delivery is at-least-once: dedupe on message id. Teams pages newest first, so a from call ' +
44
+ `reads everything since from (up to ${FROM_MAX_RAW} raw messages per conversation, past which it never ` +
45
+ 'skips silently: it says what it could not read): the further back from is, the slower the call. ';
46
+ function badFrom(from) {
47
+ return new McpToolError(`"${from}" is not a from position.`, {
48
+ hint: "Pass a UTC time such as 2026-10-01T00:00:00Z, or a previous result's next_from unchanged.",
49
+ });
50
+ }
51
+ /** The position a `from` names: a {@link encodeFrom} token, or an ISO 8601 time (UTC when it names no zone). */
52
+ export function decodeFrom(from) {
53
+ if (/^[A-Za-z0-9_-]+$/.test(from)) {
54
+ let parsed;
55
+ try {
56
+ parsed = JSON.parse(Buffer.from(from, 'base64url').toString('utf8'));
57
+ }
58
+ catch {
59
+ parsed = undefined;
60
+ }
61
+ if (parsed !== undefined) {
62
+ const { t, s } = (parsed ?? {});
63
+ const seen = s === undefined ? [] : s;
64
+ if (typeof t === 'number' &&
65
+ Number.isFinite(t) &&
66
+ t >= 0 &&
67
+ Array.isArray(seen) &&
68
+ seen.every((k) => typeof k === 'string')) {
69
+ return { t, seen: seen };
70
+ }
71
+ throw badFrom(from);
72
+ }
73
+ }
74
+ // Only a string that looks like a date: Date.parse is lenient with words. A date-time with no zone
75
+ // would parse as LOCAL time, so it is pinned to UTC.
76
+ if (!/^\d{4}-\d{2}-\d{2}/.test(from))
77
+ throw badFrom(from);
78
+ const zoned = /T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(from) ? `${from}Z` : from;
79
+ const t = Date.parse(zoned);
80
+ if (Number.isNaN(t))
81
+ throw badFrom(from);
82
+ return { t, seen: [] };
83
+ }
84
+ export function encodeFrom({ t, seen }) {
85
+ return Buffer.from(JSON.stringify(seen.length > 0 ? { t, s: seen } : { t }), 'utf8').toString('base64url');
86
+ }
87
+ /**
88
+ * The page at `pos`: the items not yet returned, oldest first (ties by key),
89
+ * the first `limit` of them, and the position after the last. `ceiling`
90
+ * (epoch ms) caps how far the position moves: an item newer than it is
91
+ * returned but will come again, because something that arrived as late as it
92
+ * may not have been read yet.
93
+ */
94
+ export function takePage(items, pos, limit, ceiling) {
95
+ const seen = new Set(pos.seen);
96
+ const pending = items
97
+ .filter((i) => i.ms > pos.t || (i.ms === pos.t && !seen.has(i.key)))
98
+ .sort((a, b) => a.ms - b.ms || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
99
+ const page = pending.slice(0, limit);
100
+ const last = page.at(-1);
101
+ let next = pos;
102
+ if (last !== undefined) {
103
+ const t = Math.max(pos.t, ceiling !== undefined ? Math.min(last.ms, ceiling) : last.ms);
104
+ const atT = page.filter((i) => i.ms === t).map((i) => i.key);
105
+ next = { t, seen: t === pos.t ? [...pos.seen, ...atT] : atT };
106
+ }
107
+ return { page: page.map((i) => i.item), has_more: pending.length > page.length, remaining: pending.length - page.length, next };
108
+ }
109
+ /** What every `from` result carries about where it is and how to go on. */
110
+ export function fromReport(pos, next, hasMore) {
111
+ return {
112
+ from_time: new Date(pos.t).toISOString(),
113
+ has_more: hasMore,
114
+ next_from: encodeFrom(next),
115
+ next_from_time: new Date(next.t).toISOString(),
116
+ };
117
+ }
118
+ /**
119
+ * Every message of a conversation that changed at or after `boundary` (epoch
120
+ * ms), newest change first — so every message that ARRIVED at or after it,
121
+ * plus older ones edited or reacted to since — or, when that is more than a
122
+ * read can reach, as far back as it got (`reachedMs`).
123
+ */
124
+ export async function readFrom(chatsvc, id, boundary) {
125
+ let capped = false;
126
+ const messages = await chatsvc.getMessages(id, {
127
+ stopAt: (m) => changedMs(m) < boundary,
128
+ max: FROM_MAX_RAW,
129
+ maxPages: FROM_MAX_PAGES,
130
+ onCapped: () => (capped = true),
131
+ });
132
+ if (!capped)
133
+ return { messages };
134
+ return { messages, reachedMs: Math.min(...messages.map(changedMs)) };
135
+ }
136
+ /** Why a conversation cannot be paged oldest first from `boundary`, and what to do. */
137
+ export function tooBusy(boundary, reachedMs) {
138
+ return {
139
+ error: `More than ${FROM_MAX_RAW} messages changed in this conversation since ${new Date(boundary).toISOString()}: ` +
140
+ `a read reached back only to ${new Date(reachedMs).toISOString()}, as Teams pages newest first.`,
141
+ hint: 'Pass a later from.',
142
+ };
143
+ }