@chrischall/microsoft-teams-mcp 0.5.1 → 0.6.1

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
@@ -257,18 +257,19 @@ export class ChatServiceClient {
257
257
  }
258
258
  /**
259
259
  * A conversation's messages, newest first, paging back until `stopAt`
260
- * accepts a message, `max` are collected, the pages run out, or 20 pages
261
- * have been read.
260
+ * accepts a message, `max` are collected, the pages run out, or `maxPages`
261
+ * (default 20) have been read.
262
262
  */
263
263
  async getMessages(id, opts) {
264
264
  this.#requireConfigured();
265
265
  const out = [];
266
266
  if (!(opts.max > 0))
267
267
  return out;
268
+ const seen = new Set();
268
269
  let url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages` +
269
270
  `?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
270
271
  for (let page = 0; url !== undefined; page++) {
271
- if (page >= MAX_MESSAGE_PAGES) {
272
+ if (page >= (opts.maxPages ?? MAX_MESSAGE_PAGES)) {
272
273
  opts.onCapped?.();
273
274
  break;
274
275
  }
@@ -281,6 +282,12 @@ export class ChatServiceClient {
281
282
  // each message it rejects — and only the NEXT page is not fetched.
282
283
  let stopped = false;
283
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);
284
291
  if (opts.stopAt?.(m)) {
285
292
  stopped = true;
286
293
  continue;
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);
@@ -78,7 +78,49 @@ function causeMessage(err) {
78
78
  function isFetchFailed(err) {
79
79
  return err instanceof TypeError && err.message === 'fetch failed';
80
80
  }
81
- function hintFor(code, host) {
81
+ /**
82
+ * The status a configured HTTPS proxy answered the CONNECT with, when that is
83
+ * why the request failed. undici reports it only in the message of an
84
+ * `UND_ERR_ABORTED` cause ("Proxy response (403) !== 200 when HTTP
85
+ * Tunneling") — there is no structured field to branch on — and Node's own
86
+ * http proxy support uses code `ERR_PROXY_TUNNEL`.
87
+ */
88
+ function proxyRefusalStatus(err) {
89
+ for (const e of causes(err)) {
90
+ if (codeOf(e) === 'ERR_PROXY_TUNNEL') {
91
+ const m = /\b(\d{3})\b/.exec(e instanceof Error ? e.message : '');
92
+ return m ? Number(m[1]) : 'unknown';
93
+ }
94
+ if (e instanceof Error) {
95
+ const m = /^Proxy response \((\d{3})\) !== 200 when HTTP Tunneling/.exec(e.message);
96
+ if (m)
97
+ return Number(m[1]);
98
+ }
99
+ }
100
+ return undefined;
101
+ }
102
+ /**
103
+ * A proxy that answered 403/407 refused the destination by policy: on mcp-host
104
+ * that is the registration's egress allow-list (mint.yaml `egress.allow`), not
105
+ * this machine's DNS or VPN, so say that instead of the network-route hints.
106
+ */
107
+ function proxyRefusalHint(status, host) {
108
+ if (status !== 403 && status !== 407 && status !== 'unknown')
109
+ return undefined;
110
+ return (`The outbound proxy this server runs behind refused the connection to ${host}: its egress ` +
111
+ 'policy does not allow that host. On a hosted (mcp-host) registration, the host must be on the ' +
112
+ "registration's egress allow-list — the owner accepts the manifest's egress proposal (or adds " +
113
+ 'the host) on the registration, then retries. Elsewhere, ask whoever runs the proxy to allow it.');
114
+ }
115
+ function hintFor(code, host, err) {
116
+ const refused = proxyRefusalStatus(err);
117
+ if (refused !== undefined) {
118
+ const policy = proxyRefusalHint(refused, host);
119
+ if (policy !== undefined)
120
+ return policy;
121
+ return (`The outbound proxy this server runs behind could not open a connection to ${host} ` +
122
+ `(it answered ${refused}). Retry; if it persists, check the proxy can reach the host.`);
123
+ }
82
124
  if (code !== undefined && DNS_CODES.has(code)) {
83
125
  return (`This machine could not resolve ${host}. Check DNS and VPN: a split-tunnel VPN that resolves ` +
84
126
  'teams.cloud.microsoft but not the regional *.asm.skype.com and *.sharepoint.com hosts ' +
@@ -118,7 +160,7 @@ export function describeTransportFailure(err, url, service) {
118
160
  const why = detail.length > 0 ? ` (${[...new Set(detail)].join(': ')})` : '';
119
161
  return new McpToolError(`Could not reach ${service} at ${host}${why}.`, {
120
162
  kind: 'transport',
121
- hint: hintFor(code, host),
163
+ hint: hintFor(code, host, err),
122
164
  cause: err,
123
165
  });
124
166
  }
@@ -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
+ }
@@ -1,20 +1,25 @@
1
1
  import { z } from 'zod';
2
- import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, toolAnnotations } from '@chrischall/mcp-utils';
3
- import { conversationSummary, matchConversations, normaliseMessage, oldestFirst, } from '../model.js';
4
- import { confirmedSummary, confirmUnreadCandidates, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
2
+ import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, McpToolError, toolAnnotations, } from '@chrischall/mcp-utils';
3
+ import { conversationSummary, isUnread, lastChangeMs, matchConversations, normaliseMessage, oldestFirst, readHorizon, } from '../model.js';
4
+ import { CONFIRM_CONCURRENCY, confirmedSummary, confirmUnreadCandidates, isUnreachable, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
5
5
  import { GROUP_TITLE_DESCRIPTION, includeHiddenArg, isUnreadCandidateFor, MATCH_REASON_DESCRIPTION } from './listing.js';
6
6
  import { enrichTitles } from './titles.js';
7
7
  import { wrapApiError } from './errors.js';
8
8
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
9
  import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
10
10
  import { CURSOR_NO_CACHE_DESCRIPTION, cursorsArg, newestId } from './cursor.js';
11
- import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
11
+ import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation, formatFlatMessage } from './format.js';
12
+ import { arrivalMs } from './conversation.js';
13
+ import { DEFAULT_LIMIT } from './limit.js';
14
+ import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage, tooBusy, } from './from.js';
12
15
  import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
13
16
  import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
14
17
  const MAX_PER_CONVERSATION = 200;
15
18
  const DEFAULT_PER_CONVERSATION = 50;
16
19
  const MAX_CONVERSATIONS = 50;
17
20
  const DEFAULT_CONVERSATIONS = 20;
21
+ /** Messages one `from` page may return, across every conversation. */
22
+ const MAX_FROM_MESSAGES = 500;
18
23
  /**
19
24
  * Raw messages read per conversation before giving up. The real bound is the
20
25
  * read horizon; this only caps a backlog of nothing but system events.
@@ -40,6 +45,98 @@ const TRUNCATED_SKIP = {
40
45
  function byLastActivityDesc(a, b) {
41
46
  return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
42
47
  }
48
+ /**
49
+ * One `from` page of unread messages across `candidates`: each read past the
50
+ * later of `from` and its own horizon (one with no change since `from` is not
51
+ * read), its real unread messages pooled and taken oldest first. The position
52
+ * never moves past the newest change the listing knew of — a message landing
53
+ * mid-call in a conversation already read is then not skipped — nor at all
54
+ * when a read failed, since that conversation may hold older unread messages.
55
+ *
56
+ * A conversation too busy to read back to `from` is not a failed read: that
57
+ * would recur on every call and hold the position for good. What arrived
58
+ * after the oldest point its read reached is complete, so it is paged like the
59
+ * rest; the stretch before it is named in `incomplete`, and the position moves.
60
+ */
61
+ async function unreadFrom(chatsvc, raw, me, candidates, pos, { limit, timeZone, format }) {
62
+ const byId = new Map(raw.map((c) => [c.id, c]));
63
+ const toRead = candidates.filter((s) => (lastChangeMs(byId.get(s.id) ?? { id: s.id }) ?? Infinity) >= pos.t);
64
+ const results = await mapWithConcurrency(toRead, CONFIRM_CONCURRENCY, async (summary) => {
65
+ const horizon = readHorizon(byId.get(summary.id) ?? { id: summary.id });
66
+ try {
67
+ const boundary = Math.max(pos.t, horizon + 1);
68
+ const { messages, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
69
+ // Past a too-busy read's reach only what arrived after it is known complete.
70
+ const known = (m) => reachedMs === undefined || arrivalMs(m) > reachedMs;
71
+ return { kind: 'read', messages: messages.filter((m) => isUnread(m, horizon, me) && known(m)), boundary, reachedMs };
72
+ }
73
+ catch (error) {
74
+ return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
75
+ }
76
+ });
77
+ let skippedUnreachable = 0;
78
+ let anyRead = false;
79
+ const items = [];
80
+ const failed = [];
81
+ const tooDeep = [];
82
+ results.forEach((r, i) => {
83
+ const summary = toRead[i];
84
+ if (r.kind === 'unreachable')
85
+ skippedUnreachable++;
86
+ else if (r.kind === 'failed')
87
+ failed.push({ summary, error: r.error });
88
+ else {
89
+ anyRead = true;
90
+ if (r.reachedMs !== undefined)
91
+ tooDeep.push({ summary, boundary: r.boundary, reachedMs: r.reachedMs });
92
+ for (const m of r.messages)
93
+ items.push({ ms: arrivalMs(m), key: `${summary.id}/${m.id}`, item: { summary, m } });
94
+ }
95
+ });
96
+ // Every read failed: a failure of the call (a revoked token, a rate limit), not of one conversation.
97
+ if (failed.length > 0 && !anyRead)
98
+ throw failed[0].error;
99
+ const listed = Math.max(pos.t, ...raw.map((c) => lastChangeMs(c) ?? 0));
100
+ const { page, has_more, remaining, next } = takePage(items, pos, limit, failed.length > 0 ? pos.t : listed);
101
+ // Only what is returned is titled: the conversations on this page, those whose read failed and those too busy.
102
+ const shown = [...new Map(page.map(({ summary }) => [summary.id, summary])).values()];
103
+ const titled = await enrichTitles(chatsvc, raw, me, [
104
+ ...shown,
105
+ ...failed.map((f) => f.summary),
106
+ ...tooDeep.map((d) => d.summary),
107
+ ]);
108
+ const titledDeep = titled.slice(shown.length + failed.length);
109
+ return {
110
+ total_unread: page.length + remaining,
111
+ messages: page.map(({ summary, m }) => ({
112
+ conversation_id: summary.id,
113
+ ...formatFlatMessage(normaliseMessage(m, me, { timeZone }), format),
114
+ })),
115
+ conversations: titled.slice(0, shown.length).map((s) => formatConversation(confirmedSummary(s, true), format)),
116
+ ...fromReport(pos, next, has_more),
117
+ skipped_unreachable: skippedUnreachable,
118
+ ...(failed.length > 0
119
+ ? {
120
+ errors: failed.map((f, i) => ({
121
+ conversation: titled[shown.length + i],
122
+ error: wrapApiError(f.error, 'read this conversation').message,
123
+ })),
124
+ }
125
+ : {}),
126
+ ...(tooDeep.length > 0
127
+ ? {
128
+ incomplete: tooDeep.map((d, i) => ({
129
+ conversation: titledDeep[i],
130
+ unread_not_read_from: new Date(d.boundary).toISOString(),
131
+ unread_not_read_until: new Date(d.reachedMs).toISOString(),
132
+ ...tooBusy(d.boundary, d.reachedMs),
133
+ })),
134
+ }
135
+ : {}),
136
+ };
137
+ }
138
+ /** The arguments that shape a per-conversation answer, which a `from` page replaces. */
139
+ const NOT_WITH_FROM = ['since_days', 'cursors', 'per_conversation_limit', 'max_conversations', 'mark_read', 'older_unread'];
43
140
  export function registerUnreadTools(server, { chatsvc }) {
44
141
  server.registerTool('teams_get_unread', {
45
142
  title: 'Get unread Teams messages',
@@ -72,6 +169,15 @@ export function registerUnreadTools(server, { chatsvc }) {
72
169
  'id; next_cursors is the cursors passed in updated with every returned conversation\'s next_cursor ' +
73
170
  '(not those only in more_unread_conversations) — pass it back as cursors to get only what is new. ' +
74
171
  CURSOR_NO_CACHE_DESCRIPTION +
172
+ FROM_DESCRIPTION +
173
+ 'With from the result is one list across every conversation instead: messages (each with its ' +
174
+ 'conversation_id; a channel reply keeps replyTo), oldest first, at most limit; conversations (the summary ' +
175
+ 'of each one on the page); total_unread (every unread message past from, this page and later ones); ' +
176
+ 'from_time, has_more, next_from, next_from_time; skipped_unreachable, muted_skipped and errors. next_from ' +
177
+ 'does not move while a read failed (call again). A conversation with more messages since from than a read ' +
178
+ 'can reach is listed in incomplete instead (unread_not_read_from / unread_not_read_until name the stretch ' +
179
+ 'not read; what arrived after it is returned) and does not hold next_from. from takes the place of since_days, cursors, ' +
180
+ 'per_conversation_limit, max_conversations, older_unread and mark_read, and format summary does not apply. ' +
75
181
  FORMAT_DESCRIPTION +
76
182
  MARK_READ_DESCRIPTION +
77
183
  'With mark_read each conversation returned with its messages (not more_unread_conversations) has its ' +
@@ -128,14 +234,39 @@ export function registerUnreadTools(server, { chatsvc }) {
128
234
  `(default ${DEFAULT_CONVERSATIONS}, max ${MAX_CONVERSATIONS}); the rest are listed in ` +
129
235
  'more_unread_conversations.'),
130
236
  cursors: cursorsArg,
237
+ from: fromArg,
238
+ limit: z
239
+ .number()
240
+ .int()
241
+ .min(1)
242
+ .max(MAX_FROM_MESSAGES)
243
+ .optional()
244
+ .describe(`With from only: maximum messages returned across every conversation, oldest first (default ` +
245
+ `${DEFAULT_LIMIT}, max ${MAX_FROM_MESSAGES}).`),
131
246
  tz: tzArg,
132
247
  format: formatArg,
133
248
  mark_read: markReadArg,
134
249
  confirmToken: confirmTokenParam,
135
250
  },
136
- }, async ({ kinds, query, include_hidden, include_muted, since_days, older_unread, per_conversation_limit, max_conversations, cursors, tz, format, mark_read, confirmToken, }, ctx) => {
251
+ }, async ({ kinds, query, include_hidden, include_muted, since_days, older_unread, per_conversation_limit, max_conversations, cursors, from, limit, tz, format, mark_read, confirmToken, }, ctx) => {
137
252
  try {
138
253
  assertMarkReadFormat(mark_read, format);
254
+ if (from === undefined && limit !== undefined) {
255
+ throw new McpToolError('limit applies only with from.', {
256
+ hint: 'Without from, use per_conversation_limit and max_conversations.',
257
+ });
258
+ }
259
+ if (from !== undefined) {
260
+ const args = { since_days, cursors, per_conversation_limit, max_conversations, mark_read, older_unread };
261
+ const clash = NOT_WITH_FROM.find((k) => args[k] !== undefined && args[k] !== false);
262
+ if (clash !== undefined || format === 'summary') {
263
+ throw new McpToolError(`from cannot be combined with ${clash ?? 'format summary'}.`, {
264
+ hint: 'from pages one oldest-first list across every conversation: pass a previous next_from to go on, ' +
265
+ 'and use teams_mark_read to mark what was paged read.',
266
+ });
267
+ }
268
+ }
269
+ const pos = from !== undefined ? decodeFrom(from) : undefined;
139
270
  const timeZone = resolveTimeZone(tz);
140
271
  const fetched_at = new Date().toISOString();
141
272
  const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
@@ -155,6 +286,14 @@ export function registerUnreadTools(server, { chatsvc }) {
155
286
  if (!include_muted)
156
287
  candidates = candidates.filter((s) => !s.muted);
157
288
  candidates.sort(byLastActivityDesc);
289
+ if (pos !== undefined) {
290
+ const page = await unreadFrom(chatsvc, raw, me, candidates, pos, {
291
+ limit: limit ?? DEFAULT_LIMIT,
292
+ timeZone,
293
+ format: format === 'compact' ? 'compact' : 'full',
294
+ });
295
+ return untrustedResult({ ...page, muted_skipped: mutedSkipped, fetched_at });
296
+ }
158
297
  const perLimit = per_conversation_limit ?? DEFAULT_PER_CONVERSATION;
159
298
  const outcome = await confirmUnreadCandidates(chatsvc, raw, me, candidates, { limit: perLimit, maxRaw: MAX_RAW_MESSAGES, since: sinceCutoff(since_days), cursors });
160
299
  const { skippedUnreachable, older } = outcome;
package/dist/version.js CHANGED
@@ -10,4 +10,4 @@
10
10
  * line below and nowhere else — not even in prose.
11
11
  */
12
12
  export const PACKAGE_NAME = 'microsoft-teams-mcp';
13
- export const VERSION = '0.5.1'; // x-release-please-version
13
+ export const VERSION = '0.6.1'; // x-release-please-version
package/mint.yaml CHANGED
@@ -77,6 +77,12 @@ env:
77
77
  help: >-
78
78
  Path to the cached Substrate search token file. Defaults to
79
79
  ~/.microsoft-teams-mcp/substrate-token.json.
80
+ - name: TEAMS_SHAREPOINT_TOKEN_FILE
81
+ required: false
82
+ help: >-
83
+ Path to the cached SharePoint token file (one token per SharePoint host,
84
+ used to download shared files). Defaults to
85
+ ~/.microsoft-teams-mcp/sharepoint-tokens.json.
80
86
  state:
81
87
  dataDir: true
82
88
  reason: >-
@@ -91,9 +97,17 @@ egress:
91
97
  # (us-api.asm.skype.com and the like), retried through the Teams gateway
92
98
  # (us-prod.asyncgw.teams.microsoft.com) when the store cannot be reached —
93
99
  # the client sends its token nowhere else. Message search goes to Microsoft
94
- # Substrate (src/substrate.ts) with its own token.
100
+ # Substrate (src/substrate.ts) with its own token. Shared files
101
+ # (teams_get_attachment) download from the file's SharePoint tenant host
102
+ # (<tenant>.sharepoint.com / <tenant>-my.sharepoint.com, src/sharepoint.ts):
103
+ # the authed driveItem GET and then its pre-signed @content.downloadUrl,
104
+ # which SharePoint issues on the same tenant host (download.aspx + tempauth).
105
+ # That the pre-signed link never redirects off *.sharepoint.com has not been
106
+ # confirmed on a live fenced download; if it does, the refusal now names the
107
+ # host it was refused (src/network-error.ts), and that host belongs here.
95
108
  allow:
96
109
  - teams.cloud.microsoft
97
110
  - '*.asm.skype.com'
98
111
  - us-prod.asyncgw.teams.microsoft.com
99
112
  - substrate.office.com
113
+ - '*.sharepoint.com'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrischall/microsoft-teams-mcp",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "mcpName": "io.github.chrischall/microsoft-teams-mcp",
5
5
  "description": "Microsoft Teams MCP server for Claude — developed and maintained by AI (Claude Code)",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
@@ -45,8 +45,8 @@
45
45
  "typecheck": "tsc -p tsconfig.check.json"
46
46
  },
47
47
  "dependencies": {
48
- "@chrischall/mcp-utils": "^3.0.0",
49
- "@fetchproxy/server": "^3.6.0",
48
+ "@chrischall/mcp-utils": "^3.0.3",
49
+ "@fetchproxy/server": "^3.6.2",
50
50
  "@modelcontextprotocol/server": "^2.3.0",
51
51
  "dotenv": "^18.0.1",
52
52
  "zod": "^4.6.5"