@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.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,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
  }