@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.
@@ -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.0'; // x-release-please-version
13
+ export const VERSION = '0.6.0'; // x-release-please-version
package/mint.yaml CHANGED
@@ -88,10 +88,12 @@ state:
88
88
  egress:
89
89
  # teams.cloud.microsoft serves the chat-service API (src/chatsvc.ts). Inline
90
90
  # images download from Teams' image store on a regional *.asm.skype.com host
91
- # (us-api.asm.skype.com and the like) — the client sends its token nowhere
92
- # else. Message search goes to Microsoft Substrate (src/substrate.ts) with
93
- # its own token.
91
+ # (us-api.asm.skype.com and the like), retried through the Teams gateway
92
+ # (us-prod.asyncgw.teams.microsoft.com) when the store cannot be reached —
93
+ # the client sends its token nowhere else. Message search goes to Microsoft
94
+ # Substrate (src/substrate.ts) with its own token.
94
95
  allow:
95
96
  - teams.cloud.microsoft
96
97
  - '*.asm.skype.com'
98
+ - us-prod.asyncgw.teams.microsoft.com
97
99
  - substrate.office.com
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrischall/microsoft-teams-mcp",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
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>",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/microsoft-teams-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.5.0",
9
+ "version": "0.6.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@chrischall/microsoft-teams-mcp",
14
- "version": "0.5.0",
14
+ "version": "0.6.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },