@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.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.
@@ -0,0 +1,241 @@
1
+ import { z } from 'zod';
2
+ import { mapWithConcurrency, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
3
+ import { conversationSummary, isUserMessage, lastChangeMs, normaliseMessage, } from '../model.js';
4
+ import { isUnreachable } from './confirm.js';
5
+ import { includeHiddenArg } from './listing.js';
6
+ import { enrichTitles } from './titles.js';
7
+ import { wrapApiError } from './errors.js';
8
+ import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
+ import { CURSOR_NO_CACHE_DESCRIPTION } from './cursor.js';
10
+ import { DEFAULT_LIMIT, limitArg } from './limit.js';
11
+ import { KIND_FILTERS } from './unread.js';
12
+ const MAX_CONVERSATIONS = 200;
13
+ /** How far back a call with no cursor looks. */
14
+ export const DEFAULT_WINDOW_MS = 86_400_000;
15
+ /**
16
+ * Raw messages read per conversation before giving up; past it the
17
+ * conversation is marked truncated and its count is a lower bound.
18
+ */
19
+ const MAX_RAW_MESSAGES = 1000;
20
+ /** Messages per page: a conversation that changed usually changed by a few. */
21
+ const PAGE_SIZE = 50;
22
+ /** Conversations read at once. */
23
+ const READ_CONCURRENCY = 4;
24
+ /** `cursor` as handed out: base64url JSON `{ t }`, `t` epoch ms. */
25
+ export function encodeChangesCursor(t) {
26
+ return Buffer.from(JSON.stringify({ t }), 'utf8').toString('base64url');
27
+ }
28
+ function badCursor(cursor) {
29
+ return new McpToolError(`"${cursor}" is not a changes cursor.`, {
30
+ hint: "Pass a previous result's next_cursor unchanged, or an ISO 8601 time such as 2026-10-12T09:00:00Z. " +
31
+ 'A message id (digits) is not a changes cursor: pass it to teams_read_conversation as after_message_id.',
32
+ });
33
+ }
34
+ /** The epoch ms a `cursor` names: a token from {@link encodeChangesCursor}, or an ISO 8601 time. */
35
+ export function decodeChangesCursor(cursor) {
36
+ if (/^[A-Za-z0-9_-]+$/.test(cursor)) {
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
40
+ }
41
+ catch {
42
+ parsed = undefined;
43
+ }
44
+ if (parsed !== undefined) {
45
+ const t = parsed?.t;
46
+ if (typeof t === 'number' && Number.isFinite(t) && t >= 0)
47
+ return t;
48
+ throw badCursor(cursor);
49
+ }
50
+ }
51
+ // Only a string that looks like a date: Date.parse is lenient with words.
52
+ const t = /^\d{4}-\d{2}-\d{2}/.test(cursor) ? Date.parse(cursor) : NaN;
53
+ if (Number.isNaN(t))
54
+ throw badCursor(cursor);
55
+ return t;
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
+ /** Read one conversation down to `t` and count what arrived after it. */
64
+ async function readChanges(chatsvc, summary, t, me) {
65
+ let capped = false;
66
+ const fetched = await chatsvc.getMessages(summary.id, {
67
+ stopAt: (m) => changedMs(m) <= t,
68
+ max: MAX_RAW_MESSAGES,
69
+ pageSize: PAGE_SIZE,
70
+ onCapped: () => (capped = true),
71
+ });
72
+ const arrived = fetched.filter((m) => Number(m.id) > t);
73
+ const maxSeen = arrived.reduce((n, m) => Math.max(n, Number(m.id)), 0);
74
+ const fresh = arrived
75
+ .filter(isUserMessage)
76
+ .map((m) => normaliseMessage(m, me))
77
+ .filter((m) => m.deleted !== true)
78
+ .sort((a, b) => Number(b.id) - Number(a.id));
79
+ let threads;
80
+ if (summary.kind === 'channel') {
81
+ // Newest first, so threads come in order of their newest new message.
82
+ const byRoot = new Map();
83
+ for (const m of fresh) {
84
+ const rootId = m.replyTo ?? m.id;
85
+ let thread = byRoot.get(rootId);
86
+ if (thread === undefined)
87
+ byRoot.set(rootId, (thread = { root_id: rootId, new_root: false, new_reply_count: 0 }));
88
+ if (m.replyTo === undefined)
89
+ thread.new_root = true;
90
+ else
91
+ thread.new_reply_count++;
92
+ }
93
+ threads = [...byRoot.values()];
94
+ }
95
+ return {
96
+ count: fresh.length,
97
+ fromOthers: fresh.filter((m) => !m.fromMe).length,
98
+ newest: fresh.length > 0 ? Number(fresh[0].id) : 0,
99
+ ...(fresh.length > 0 ? { newestTime: fresh[0].time } : {}),
100
+ maxSeen,
101
+ ...(threads !== undefined ? { threads } : {}),
102
+ truncated: capped,
103
+ };
104
+ }
105
+ export function registerChangesTools(server, { chatsvc }) {
106
+ server.registerTool('teams_get_changes', {
107
+ title: 'Get Teams conversations with new messages',
108
+ description: 'List the chats and channels that got new messages since a cursor, most recent first — counts, not ' +
109
+ 'the messages: each with its summary (id, kind, title, team), new_message_count (real messages ' +
110
+ 'only — call recordings and other system events, and deleted messages, are not counted), ' +
111
+ 'new_from_others_count, newest_time and, for a channel, threads: one { root_id, new_root, ' +
112
+ 'new_reply_count } per thread the new messages landed in, including a thread whose root post is ' +
113
+ 'older than the cursor, and after_message_id: read the messages it counted with ' +
114
+ 'teams_read_conversation({ conversation: <its id>, after_message_id: <its after_message_id> }). ' +
115
+ 'Two cursor kinds, not interchangeable: this tool\'s cursor/next_cursor is a time token for ' +
116
+ 'teams_get_changes only and is not a message id; after_message_id is a message-id cursor (ids are ' +
117
+ 'arrival ms, so it is the cursor time as an id) for teams_read_conversation (or teams_get_unread ' +
118
+ 'cursors). Without cursor it looks back 24 hours. next_cursor is an opaque token — pass it back as ' +
119
+ 'cursor to get only what arrived since this call (cursor also takes a plain ISO 8601 time). It is ' +
120
+ 'at-least-once: a conversation can come back again but none is skipped; it stays at the input ' +
121
+ 'time when a read failed. Use the same kinds and include_hidden with a cursor as the call that ' +
122
+ 'returned it. Channels hidden in Teams are left out unless include_hidden (then every hidden channel ' +
123
+ 'is read, since Teams stops updating their listing); one that is gone or no ' +
124
+ 'longer readable (404/403) is skipped and counted in skipped_unreachable; one whose read failed ' +
125
+ 'is listed in errors. limit caps the conversations returned; the rest are named, with their ' +
126
+ 'new_message_count and after_message_id, in more_conversations, and total_new_messages counts them all. A conversation ' +
127
+ `with more than ${MAX_RAW_MESSAGES} new messages is marked truncated (its count is a lower bound). ` +
128
+ CURSOR_NO_CACHE_DESCRIPTION +
129
+ 'This does NOT mark anything read — the user\'s Teams unread badges are unaffected. ' +
130
+ UNTRUSTED_DESCRIPTION_SUFFIX,
131
+ annotations: toolAnnotations({ readOnly: true, openWorld: true }),
132
+ inputSchema: {
133
+ cursor: z
134
+ .string()
135
+ .min(1)
136
+ .optional()
137
+ .describe("A previous teams_get_changes result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): " +
138
+ 'only messages that arrived after it count. Default: 24 hours ago. Not a message id, and not ' +
139
+ "teams_read_conversation's next_cursor."),
140
+ kinds: z
141
+ .array(z.enum(Object.keys(KIND_FILTERS)))
142
+ .min(1)
143
+ .optional()
144
+ .describe('Only these kinds of conversation (default all): chat = every group, meeting and 1:1 ' +
145
+ 'chat; channel; meeting = meeting chats only; oneOnOne = 1:1 chats only.'),
146
+ include_hidden: includeHiddenArg.describe('Also include channels the user has hidden in Teams (default false: Teams shows them nowhere).'),
147
+ limit: limitArg(MAX_CONVERSATIONS, 'conversations', 'most recent activity first kept'),
148
+ },
149
+ }, async ({ cursor, kinds, include_hidden, limit }) => {
150
+ try {
151
+ const t = cursor !== undefined ? decodeChangesCursor(cursor) : Date.now() - DEFAULT_WINDOW_MS;
152
+ const fetched_at = new Date().toISOString();
153
+ const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
154
+ const allowed = new Set((kinds ?? ['chat', 'channel']).flatMap((k) => KIND_FILTERS[k]));
155
+ const lastChange = new Map(raw.map((c) => [c.id, lastChangeMs(c)]));
156
+ // Summaries are built against the FULL listing so a channel can find its team's name. A
157
+ // hidden channel's listing entry stops moving (live: days stale while posts arrived), so
158
+ // with include_hidden every hidden channel is read; otherwise the listing nominates.
159
+ const candidates = raw
160
+ .map((c) => conversationSummary(c, me, raw))
161
+ .filter((s) => allowed.has(s.kind))
162
+ .filter((s) => (s.hidden === true ? include_hidden === true : (lastChange.get(s.id) ?? 0) > t));
163
+ const results = await mapWithConcurrency(candidates, READ_CONCURRENCY, async (summary) => {
164
+ try {
165
+ return { kind: 'read', read: await readChanges(chatsvc, summary, t, me) };
166
+ }
167
+ catch (error) {
168
+ return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
169
+ }
170
+ });
171
+ let skipped_unreachable = 0;
172
+ let maxSeen = t;
173
+ let anyRead = false;
174
+ const changed = [];
175
+ const failed = [];
176
+ results.forEach((r, i) => {
177
+ if (r.kind === 'unreachable')
178
+ skipped_unreachable++;
179
+ else if (r.kind === 'failed')
180
+ failed.push({ summary: candidates[i], error: r.error });
181
+ else {
182
+ anyRead = true;
183
+ maxSeen = Math.max(maxSeen, r.read.maxSeen);
184
+ if (r.read.count > 0)
185
+ changed.push({ summary: candidates[i], read: r.read });
186
+ }
187
+ });
188
+ // Every read failed: a failure of the call (a revoked token, a rate limit), not of one conversation.
189
+ if (failed.length > 0 && !anyRead)
190
+ throw failed[0].error;
191
+ changed.sort((a, b) => b.read.newest - a.read.newest);
192
+ // Never past the newest change the listing saw: a quiet conversation's mid-call message stays ahead.
193
+ const listed = Math.max(t, ...[...lastChange.values()].map((n) => n ?? 0));
194
+ const next = failed.length > 0 ? t : Math.min(maxSeen, listed);
195
+ const cap = limit ?? DEFAULT_LIMIT;
196
+ const shown = changed.slice(0, cap);
197
+ const rest = changed.slice(cap);
198
+ const titled = await enrichTitles(chatsvc, raw, me, [
199
+ ...shown.map((c) => c.summary),
200
+ ...rest.map((c) => c.summary),
201
+ ...failed.map((f) => f.summary),
202
+ ]);
203
+ // The read_conversation hand-off: a message id is its arrival ms, so the cursor time as an id
204
+ // stops that read exactly where this one stopped counting.
205
+ const after_message_id = String(Math.floor(t));
206
+ const conversations = shown.map(({ read }, i) => ({
207
+ conversation: titled[i],
208
+ new_message_count: read.count,
209
+ new_from_others_count: read.fromOthers,
210
+ ...(read.newestTime !== undefined ? { newest_time: read.newestTime } : {}),
211
+ after_message_id,
212
+ ...(read.threads !== undefined ? { threads: read.threads } : {}),
213
+ ...(read.truncated ? { truncated: true } : {}),
214
+ }));
215
+ const more = rest.map(({ read }, i) => ({
216
+ id: titled[shown.length + i].id,
217
+ title: titled[shown.length + i].title,
218
+ new_message_count: read.count,
219
+ after_message_id,
220
+ }));
221
+ const errors = failed.map((f, i) => ({
222
+ conversation: titled[changed.length + i],
223
+ error: wrapApiError(f.error, 'read this conversation').message,
224
+ }));
225
+ return untrustedResult({
226
+ since: new Date(t).toISOString(),
227
+ total_new_messages: changed.reduce((n, c) => n + c.read.count, 0),
228
+ conversations,
229
+ ...(more.length > 0 ? { more_conversations: more } : {}),
230
+ skipped_unreachable,
231
+ ...(errors.length > 0 ? { errors } : {}),
232
+ next_cursor: next === t && cursor !== undefined ? cursor : encodeChangesCursor(next),
233
+ next_cursor_time: new Date(next).toISOString(),
234
+ fetched_at,
235
+ });
236
+ }
237
+ catch (err) {
238
+ throw wrapApiError(err, 'get changed conversations');
239
+ }
240
+ });
241
+ }
@@ -2,7 +2,7 @@ import { toolAnnotations } from '@chrischall/mcp-utils';
2
2
  import { wrapApiError } from './errors.js';
3
3
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
4
4
  import { limitArg, trimRows } from './limit.js';
5
- import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
5
+ import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, MATCH_REASON_DESCRIPTION, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
6
6
  /** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
7
7
  const MAX_CHANNELS = 500;
8
8
  /**
@@ -38,7 +38,9 @@ export function registerChannelTools(server, { chatsvc }) {
38
38
  'keeps only channels whose newest unread post is from the last 14 days (since_days widens ' +
39
39
  'it); older ones are counted in older_unread_skipped, not listed. ' +
40
40
  UNREAD_HINT_DESCRIPTION +
41
- ' Listing never marks anything read. query matches the channel title or team name. ' +
41
+ ' Listing never marks anything read (teams_mark_read does). query matches the channel title, team name or last-message preview. ' +
42
+ MATCH_REASON_DESCRIPTION +
43
+ ' ' +
42
44
  FAVORITES_DESCRIPTION +
43
45
  UNTRUSTED_DESCRIPTION_SUFFIX,
44
46
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
@@ -46,7 +48,7 @@ export function registerChannelTools(server, { chatsvc }) {
46
48
  unread_only: unreadOnlyArg,
47
49
  since_days: listSinceDaysArg,
48
50
  include_hidden: includeHiddenArg,
49
- query: queryArg('channel title or team name'),
51
+ query: queryArg('channel title, team name or last-message preview'),
50
52
  limit: limitArg(MAX_CHANNELS, 'channels', 'favorites and pinned first, then by team and title, kept'),
51
53
  },
52
54
  }, async ({ unread_only, include_hidden, since_days, query, limit }) => {
@@ -0,0 +1,65 @@
1
+ /**
2
+ * `teams_list_chats`' opt-in `search_messages`: a query matched against what
3
+ * was said in each chat, not only what the chat is called.
4
+ *
5
+ * The chat service has no search call this server can reach, so each chat no
6
+ * name or last-message preview matched is read here — one page of its
7
+ * {@link SEARCH_FETCH_MESSAGES} most recent messages, {@link SEARCH_CONCURRENCY}
8
+ * chats at a time, the same bounded fan-out `titles.ts` uses. Only messages a
9
+ * person wrote count (not deleted ones or system events), matched on their
10
+ * plain text. A read that fails leaves its chat out and is counted — it never
11
+ * fails the call. Nothing is cached: a search wants the newest messages.
12
+ */
13
+ import { mapWithConcurrency } from '@chrischall/mcp-utils';
14
+ import { isUserMessage, normaliseMessage } from '../model.js';
15
+ /** Recent messages read per chat — one page. */
16
+ export const SEARCH_FETCH_MESSAGES = 50;
17
+ /** Chats read at once. */
18
+ export const SEARCH_CONCURRENCY = 4;
19
+ /** Longest matched-message text returned, centred on the match. */
20
+ const SNIPPET_CHARS = 200;
21
+ /** Context kept before the match when the text has to be cut. */
22
+ const SNIPPET_LEAD = 60;
23
+ /**
24
+ * Read the recent messages of each chat in `ids` and keep, per chat, the
25
+ * newest whose text contains `query` (case-insensitive).
26
+ */
27
+ export async function searchRecentMessages(chatsvc, me, ids, query) {
28
+ const q = query.trim().toLowerCase();
29
+ const hits = new Map();
30
+ let failed = 0;
31
+ if (q === '')
32
+ return { hits, failed };
33
+ await mapWithConcurrency([...new Set(ids)], SEARCH_CONCURRENCY, async (id) => {
34
+ let messages;
35
+ try {
36
+ messages = await chatsvc.getMessages(id, { max: SEARCH_FETCH_MESSAGES, pageSize: SEARCH_FETCH_MESSAGES });
37
+ }
38
+ catch {
39
+ failed++;
40
+ return;
41
+ }
42
+ // Served newest first, so the first match is the newest.
43
+ for (const m of messages) {
44
+ if (!isUserMessage(m))
45
+ continue;
46
+ const n = normaliseMessage(m, me);
47
+ if (n.deleted)
48
+ continue;
49
+ const at = n.text.toLowerCase().indexOf(q);
50
+ if (at === -1)
51
+ continue;
52
+ hits.set(id, { id: n.id, time: n.time, sender: n.sender, text: snippet(n.text, at) });
53
+ return;
54
+ }
55
+ });
56
+ return { hits, failed };
57
+ }
58
+ /** `text` whole when short, else a window of it that starts a little before index `at`. */
59
+ function snippet(text, at) {
60
+ if (text.length <= SNIPPET_CHARS)
61
+ return text;
62
+ const start = Math.max(0, Math.min(at - SNIPPET_LEAD, text.length - SNIPPET_CHARS));
63
+ const end = start + SNIPPET_CHARS;
64
+ return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`;
65
+ }
@@ -1,14 +1,53 @@
1
- import { toolAnnotations } from '@chrischall/mcp-utils';
1
+ import { McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
2
+ import { z } from 'zod';
2
3
  import { wrapApiError } from './errors.js';
3
4
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
4
5
  import { limitArg, trimRows } from './limit.js';
5
- import { FAVORITES_DESCRIPTION, favoritesFirst, GROUP_TITLE_DESCRIPTION, listSinceDaysArg, listSummaries, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
6
+ import { SEARCH_FETCH_MESSAGES } from './chat-search.js';
7
+ import { FAVORITES_DESCRIPTION, favoritesFirst, GROUP_TITLE_DESCRIPTION, listOlderUnreadArg, listSinceDaysArg, listSummaries, MATCH_REASON_DESCRIPTION, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
6
8
  /** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
7
9
  const MAX_CHATS = 500;
8
10
  /** Newest activity first; a chat with no messages at all sorts last. */
9
11
  function byLastActivityDesc(a, b) {
10
12
  return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
11
13
  }
14
+ /** Alphabetical by title, ignoring case and accents; a stable sort keeps recency among equals. */
15
+ function byTitle(a, b) {
16
+ return a.title.localeCompare(b.title, undefined, { sensitivity: 'base' });
17
+ }
18
+ /** An optional ISO 8601 date-time bound on a chat's last activity. */
19
+ function activityBoundArg(name, side) {
20
+ return z
21
+ .string()
22
+ .refine((s) => !Number.isNaN(Date.parse(s)), { message: `${name} must be an ISO 8601 date-time` })
23
+ .optional()
24
+ .describe(`Only return chats whose last activity is ${side} this ISO 8601 date-time (e.g. 2026-09-21T09:00:00Z). ` +
25
+ 'A chat with no last activity is left out whenever since or until is given.');
26
+ }
27
+ const SORTS = ['activity', 'activity_only', 'title'];
28
+ const sortArg = z
29
+ .enum(SORTS)
30
+ .optional()
31
+ .describe('Order of the result, and so which chats limit keeps: "activity" (default) — favorites, then pinned, ' +
32
+ 'then most recent activity (unread_only: most recent activity); "activity_only" — most recent ' +
33
+ 'activity first, ignoring favorites and pinned; "title" — alphabetical by title, case-insensitive ' +
34
+ '(titles every untitled chat in the listing first, so it reads more).');
35
+ const searchMessagesArg = z
36
+ .boolean()
37
+ .optional()
38
+ .describe(`With query: also read the last ${SEARCH_FETCH_MESSAGES} messages of every chat no name or ` +
39
+ 'last-message preview matched, and return the chats where one of them contains the query ' +
40
+ '(match_reason "message", with the newest such message as matched_message: id, time, sender, ' +
41
+ 'text). Reads one page per chat, four at a time, so it is slower on a large listing; narrow it ' +
42
+ 'with since / until or unread_only. Default false.');
43
+ /** Orders `rows` in place for `sort`; titles must already be final for "title". */
44
+ function sortChats(rows, sort, unreadOnly) {
45
+ rows.sort(byLastActivityDesc);
46
+ if (sort === 'title')
47
+ rows.sort(byTitle);
48
+ else if (sort === 'activity' && !unreadOnly)
49
+ rows.sort(favoritesFirst);
50
+ }
12
51
  export function registerChatTools(server, { chatsvc }) {
13
52
  server.registerTool('teams_list_chats', {
14
53
  title: 'List Teams chats',
@@ -17,7 +56,9 @@ export function registerChatTools(server, { chatsvc }) {
17
56
  'id, kind (oneOnOne / group / meeting, or self for the user\'s own 48:notes self-chat), ' +
18
57
  'title, unread hint, last-activity time (ISO 8601), and a last-message preview and sender. ' +
19
58
  GROUP_TITLE_DESCRIPTION +
20
- ' query also matches those participant names. ' +
59
+ ' query also matches those participant names, and the last-message preview. ' +
60
+ MATCH_REASON_DESCRIPTION +
61
+ ' search_messages extends the match to each chat\'s recent messages. ' +
21
62
  FAVORITES_DESCRIPTION +
22
63
  ' ' +
23
64
  'Pass an id (or the title) to teams_read_conversation to read the messages. Use ' +
@@ -25,31 +66,65 @@ export function registerChatTools(server, { chatsvc }) {
25
66
  'them: each candidate is confirmed by reading its messages past the read marker, so a ' +
26
67
  'call recording, transcript or other system event never makes a chat unread. By default ' +
27
68
  'unread_only keeps only chats whose newest unread message is from the last 14 days ' +
28
- '(since_days widens it); older ones are counted in older_unread_skipped, not listed. ' +
69
+ '(since_days widens it); older ones are counted in older_unread_skipped, and older_unread: ' +
70
+ 'true lists them in older_unread_conversations (unread_count only for those already read). ' +
71
+ 'A chat the user muted in Teams carries muted: true. ' +
29
72
  UNREAD_HINT_DESCRIPTION +
30
- ' Listing never marks anything read. Channels are listed by teams_list_teams_and_channels instead.' +
73
+ ' since / until (ISO 8601 date-times) keep chats whose last activity falls in that window; ' +
74
+ 'sort picks the order: activity (default, as above), activity_only (most recent first, ' +
75
+ 'ignoring favorites and pinned) or title (alphabetical, case-insensitive).' +
76
+ ' Listing never marks anything read (teams_mark_read does). Channels are listed by teams_list_teams_and_channels instead.' +
31
77
  UNTRUSTED_DESCRIPTION_SUFFIX,
32
78
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
33
79
  inputSchema: {
34
80
  unread_only: unreadOnlyArg,
35
81
  since_days: listSinceDaysArg,
36
- query: queryArg('chat title or an untitled chat\'s participant names'),
37
- limit: limitArg(MAX_CHATS, 'chats', 'favorites and pinned first, then most recent activity, kept'),
82
+ older_unread: listOlderUnreadArg,
83
+ query: queryArg('chat title, an untitled chat\'s participant names or the last-message preview'),
84
+ search_messages: searchMessagesArg,
85
+ since: activityBoundArg('since', 'at or after'),
86
+ until: activityBoundArg('until', 'at or before'),
87
+ sort: sortArg,
88
+ limit: limitArg(MAX_CHATS, 'chats', 'the head of the sort order kept'),
38
89
  },
39
- }, async ({ unread_only, since_days, query, limit }) => {
90
+ }, async ({ unread_only, since_days, older_unread, query, search_messages, since, until, sort = 'activity', limit }) => {
91
+ if (older_unread && !unread_only) {
92
+ throw new McpToolError('older_unread lists what unread_only left out, so it needs unread_only.', {
93
+ hint: 'Pass unread_only: true with older_unread, or drop older_unread.',
94
+ });
95
+ }
96
+ if (search_messages && query === undefined) {
97
+ throw new McpToolError('search_messages needs a query to search for.', {
98
+ hint: 'Pass the text to find as query, or drop search_messages.',
99
+ });
100
+ }
101
+ const activeSince = since !== undefined ? Date.parse(since) : undefined;
102
+ const activeUntil = until !== undefined ? Date.parse(until) : undefined;
103
+ if (activeSince !== undefined && activeUntil !== undefined && activeSince > activeUntil) {
104
+ throw new McpToolError(`since (${since}) is after until (${until}).`, {
105
+ hint: 'Pass a since at or before until.',
106
+ });
107
+ }
40
108
  try {
41
109
  const { rows, retitle, errors: _untitledErrors, ...unreadInfo } = await listSummaries(chatsvc, {
42
110
  kinds: ['group', 'meeting', 'oneOnOne', 'self'],
43
111
  unread_only,
44
112
  since_days,
113
+ older_unread,
45
114
  query,
115
+ searchMessages: search_messages,
116
+ activeSince,
117
+ activeUntil,
46
118
  });
47
- rows.sort(byLastActivityDesc);
48
- if (!unread_only)
49
- rows.sort(favoritesFirst);
50
- const { rows: kept, truncated } = trimRows(rows, limit, 'start', MAX_CHATS, unread_only ? 'most recent' : 'first');
51
- // errors names conversations too, so it is retitled alongside the rows.
52
- const { rows: chats, errors } = await retitle(kept);
119
+ // A title sort needs every untitled chat's final title before limit picks the head;
120
+ // otherwise only the kept rows are titled. errors names conversations too, so it is
121
+ // retitled alongside the rows.
122
+ const titledFirst = sort === 'title' ? await retitle(rows) : undefined;
123
+ const ordered = titledFirst?.rows ?? rows;
124
+ sortChats(ordered, sort, unread_only);
125
+ const which = sort === 'title' || (sort === 'activity' && !unread_only) ? 'first' : 'most recent';
126
+ const { rows: kept, truncated } = trimRows(ordered, limit, 'start', MAX_CHATS, which);
127
+ const { rows: chats, errors } = titledFirst ? { rows: kept, errors: titledFirst.errors } : await retitle(kept);
53
128
  return untrustedResult({ chats, ...unreadInfo, ...(errors ? { errors } : {}), ...(truncated ? { truncated } : {}) });
54
129
  }
55
130
  catch (err) {
@@ -18,7 +18,8 @@
18
18
  * (2026-10-10): 14 of 16 confirmed-unread channels had last moved months or
19
19
  * years ago, in teams the user never looks at. A candidate whose newest
20
20
  * activity of any kind is already older than the window is skipped without a
21
- * read; both kinds of skip are counted in `olderSkipped`, never dropped silently.
21
+ * read; both kinds of skip are kept in `older` (counted in `older_unread_skipped`,
22
+ * listed with `older_unread`), never dropped silently.
22
23
  */
23
24
  import { errorStatusOf, mapWithConcurrency } from '@chrischall/mcp-utils';
24
25
  import { z } from 'zod';
@@ -58,11 +59,47 @@ export function olderUnreadReport(olderSkipped, sinceDays) {
58
59
  ? {
59
60
  older_unread_hint: `${olderSkipped} conversation${olderSkipped === 1 ? '' : 's'} with unread activity older than ` +
60
61
  `${days} days ${olderSkipped === 1 ? 'was' : 'were'} left out; pass a larger since_days ` +
61
- `(max ${MAX_SINCE_DAYS}) to include ${olderSkipped === 1 ? 'it' : 'them'}.`,
62
+ `(max ${MAX_SINCE_DAYS}) to include ${olderSkipped === 1 ? 'it' : 'them'}, or older_unread: true ` +
63
+ `to list ${olderSkipped === 1 ? 'it' : 'them'}.`,
62
64
  }
63
65
  : {}),
64
66
  };
65
67
  }
68
+ /** The optional `older_unread` argument: list what the `since_days` window left out. */
69
+ export function olderUnreadArg(scope = '') {
70
+ return z
71
+ .boolean()
72
+ .optional()
73
+ .describe(`${scope}Also list the conversations since_days left out, as older_unread_conversations: id, ` +
74
+ 'kind, title, team (a channel\'s), lastActivity and, where its messages were read, ' +
75
+ 'unread_count. One never read (nothing at all happened inside the window) carries ' +
76
+ 'unread_count_known: false instead and is not read now — its news may be only system ' +
77
+ 'events. Default false.');
78
+ }
79
+ /**
80
+ * `older_unread_conversations` from the left-out conversations, given their
81
+ * (re)titled summaries in the same order: most recent activity first, and
82
+ * absent when nothing was left out.
83
+ */
84
+ export function olderUnreadConversations(older, titled) {
85
+ if (older.length === 0)
86
+ return {};
87
+ const rows = older.map(({ read }, i) => {
88
+ const s = titled[i];
89
+ return {
90
+ id: s.id,
91
+ kind: s.kind,
92
+ title: s.title,
93
+ ...(s.team !== undefined ? { team: s.team } : {}),
94
+ ...(s.lastActivity !== undefined ? { lastActivity: s.lastActivity } : {}),
95
+ ...(read === undefined
96
+ ? { unread_count_known: false }
97
+ : { unread_count: read.messages.length, ...(read.truncated ? { unread_count_exact: false } : {}) }),
98
+ };
99
+ });
100
+ rows.sort((a, b) => (b.lastActivity ?? '').localeCompare(a.lastActivity ?? ''));
101
+ return { older_unread_conversations: rows };
102
+ }
66
103
  /** A 404 or 403: the conversation is gone or not readable, so it is not unread. */
67
104
  export function isUnreachable(err) {
68
105
  const status = errorStatusOf(err);
@@ -93,7 +130,11 @@ export async function readUnread(chatsvc, id, horizon, me, { limit, maxRaw }) {
93
130
  *
94
131
  * With `since` (epoch ms), a candidate whose newest activity predates it is
95
132
  * not read at all, and one whose newest real unread message predates it is
96
- * not kept; both are counted in `olderSkipped`.
133
+ * not kept; both go in `older`.
134
+ *
135
+ * With `cursors` ({ conversationId: messageId }), a candidate's read stops at
136
+ * the later of its horizon and its cursor (`cursor.ts`), so only unread
137
+ * messages newer than the cursor count — one with none past it is not kept.
97
138
  */
98
139
  export async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts) {
99
140
  const byId = new Map(raw.map((c) => [c.id, c]));
@@ -104,7 +145,9 @@ export async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts
104
145
  // Nothing at all happened inside the window, so no unread message can be in it.
105
146
  if (newest !== undefined && newest < since)
106
147
  return { kind: 'older' };
107
- const horizon = readHorizon(conv);
148
+ const cursors = opts.cursors ?? {};
149
+ const cursor = Object.hasOwn(cursors, summary.id) ? Number(cursors[summary.id]) : 0;
150
+ const horizon = Math.max(readHorizon(conv), Number.isFinite(cursor) ? cursor : 0);
108
151
  try {
109
152
  return { kind: 'read', read: await readUnread(chatsvc, summary.id, horizon, me, opts) };
110
153
  }
@@ -112,12 +155,12 @@ export async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts
112
155
  return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
113
156
  }
114
157
  });
115
- const outcome = { confirmed: [], skippedUnreachable: 0, olderSkipped: 0, failed: [] };
158
+ const outcome = { confirmed: [], skippedUnreachable: 0, older: [], failed: [] };
116
159
  let anyRead = false;
117
160
  results.forEach((r, i) => {
118
161
  const summary = candidates[i];
119
162
  if (r.kind === 'older')
120
- outcome.olderSkipped++;
163
+ outcome.older.push({ summary });
121
164
  else if (r.kind === 'unreachable')
122
165
  outcome.skippedUnreachable++;
123
166
  else if (r.kind === 'failed')
@@ -129,7 +172,7 @@ export async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts
129
172
  if (newestUnread === undefined)
130
173
  return;
131
174
  if (Number(newestUnread.id) < since)
132
- outcome.olderSkipped++;
175
+ outcome.older.push({ summary, read: r.read });
133
176
  else
134
177
  outcome.confirmed.push({ summary, read: r.read });
135
178
  }