@chrischall/microsoft-teams-mcp 0.3.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.
Files changed (50) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +577 -93
  4. package/dist/auth-fetchproxy.js +138 -0
  5. package/dist/bundle.js +44324 -37483
  6. package/dist/capture-window.js +41 -0
  7. package/dist/chatsvc.js +580 -0
  8. package/dist/compose.js +241 -0
  9. package/dist/deps.js +1 -0
  10. package/dist/index.js +35 -6
  11. package/dist/model.js +603 -0
  12. package/dist/sharepoint-auth.js +162 -0
  13. package/dist/sharepoint-token-cache.js +105 -0
  14. package/dist/sharepoint.js +289 -0
  15. package/dist/substrate-auth.js +104 -0
  16. package/dist/substrate-token-cache.js +64 -0
  17. package/dist/substrate.js +319 -0
  18. package/dist/token-cache.js +67 -0
  19. package/dist/tools/activity.js +155 -19
  20. package/dist/tools/attachment.js +174 -0
  21. package/dist/tools/changes.js +241 -0
  22. package/dist/tools/channels.js +62 -44
  23. package/dist/tools/chat-search.js +65 -0
  24. package/dist/tools/chat.js +121 -41
  25. package/dist/tools/confirm.js +188 -0
  26. package/dist/tools/conversation.js +394 -30
  27. package/dist/tools/cursor.js +43 -0
  28. package/dist/tools/errors.js +18 -17
  29. package/dist/tools/format.js +135 -0
  30. package/dist/tools/healthcheck.js +91 -27
  31. package/dist/tools/limit.js +43 -12
  32. package/dist/tools/listing.js +180 -0
  33. package/dist/tools/markread.js +246 -0
  34. package/dist/tools/react.js +217 -0
  35. package/dist/tools/roots.js +73 -0
  36. package/dist/tools/search.js +426 -0
  37. package/dist/tools/send.js +309 -0
  38. package/dist/tools/timezone.js +38 -0
  39. package/dist/tools/titles.js +180 -0
  40. package/dist/tools/unread.js +263 -0
  41. package/dist/tools/untrusted.js +16 -1
  42. package/dist/version.js +1 -1
  43. package/mint.yaml +75 -20
  44. package/package.json +1 -2
  45. package/server.json +87 -3
  46. package/skills/teams-fpx/SKILL.md +111 -92
  47. package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
  48. package/skills/teams-fpx/references/teams-env.sh +146 -0
  49. package/dist/client.js +0 -290
  50. package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
@@ -1,54 +1,134 @@
1
- import { toolAnnotations } from '@chrischall/mcp-utils';
2
- import { wrapBridgeError } from './errors.js';
1
+ import { McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
2
+ import { z } from 'zod';
3
+ import { wrapApiError } from './errors.js';
3
4
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
4
- import { OPEN_CONVERSATION_DESCRIPTION, readOpenConversation } from './conversation.js';
5
- import { filterSince, limitArg, sinceArg, trimRows } from './limit.js';
6
- export function registerChatTools(server, client) {
5
+ import { limitArg, trimRows } from './limit.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';
8
+ /** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
9
+ const MAX_CHATS = 500;
10
+ /** Newest activity first; a chat with no messages at all sorts last. */
11
+ function byLastActivityDesc(a, b) {
12
+ return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
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
+ }
51
+ export function registerChatTools(server, { chatsvc }) {
7
52
  server.registerTool('teams_list_chats', {
8
53
  title: 'List Teams chats',
9
- description: 'List the chats in the signed-in user\'s Teams chat sidebar (1:1s, group chats, meeting ' +
10
- 'chats), each with its title, last-message preview, last-activity time, and a ' +
11
- 'conversationKey (Teams\' internal thread id — not usable to open the chat, there is no ' +
12
- 'navigate capability). Reads the currently-rendered list from the user\'s live browser tab.' +
54
+ description: 'List every chat the signed-in user is in — 1:1s, group chats and meeting chats, not ' +
55
+ 'just the ones visible in the Teams sidebar — favorites and pinned first, then most recent activity. Each has an ' +
56
+ 'id, kind (oneOnOne / group / meeting, or self for the user\'s own 48:notes self-chat), ' +
57
+ 'title, unread hint, last-activity time (ISO 8601), and a last-message preview and sender. ' +
58
+ GROUP_TITLE_DESCRIPTION +
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. ' +
62
+ FAVORITES_DESCRIPTION +
63
+ ' ' +
64
+ 'Pass an id (or the title) to teams_read_conversation to read the messages. Use ' +
65
+ 'unread_only to find chats with messages the user has not read, exactly as Teams counts ' +
66
+ 'them: each candidate is confirmed by reading its messages past the read marker, so a ' +
67
+ 'call recording, transcript or other system event never makes a chat unread. By default ' +
68
+ 'unread_only keeps only chats whose newest unread message is from the last 14 days ' +
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. ' +
72
+ UNREAD_HINT_DESCRIPTION +
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.' +
13
77
  UNTRUSTED_DESCRIPTION_SUFFIX,
14
78
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
15
- inputSchema: { limit: limitArg(200, 'chats') },
16
- }, async ({ limit }) => {
17
- try {
18
- const rows = await client.listChats();
19
- return untrustedResult(rows.length > 0
20
- ? trimRows(rows, limit, 'start', 200)
21
- : {
22
- rows,
23
- empty_hint: 'No chat list is rendered. The Teams tab is probably not on the Chat view — ' +
24
- 'ask the user to click Chat in the left nav, then retry.',
25
- });
79
+ inputSchema: {
80
+ unread_only: unreadOnlyArg,
81
+ since_days: listSinceDaysArg,
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'),
89
+ },
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
+ });
26
95
  }
27
- catch (err) {
28
- throw wrapBridgeError(err, 'list chats');
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
+ });
29
107
  }
30
- });
31
- server.registerTool('teams_get_open_chat_messages', {
32
- title: 'Read the currently open Teams chat',
33
- description: 'Read the message thread of whichever Teams chat is CURRENTLY OPEN in the user\'s ' +
34
- 'signed-in browser tab — sender, ISO-8601 time, message id, and text for each message. ' +
35
- 'There is no way to choose a different chat from here (the bridge can only read the DOM, ' +
36
- 'not navigate it): ask the user to open the chat they mean first, or use ' +
37
- 'teams_list_chats to show them what is available. A quoted-reply message\'s text may ' +
38
- 'include the quoted preview concatenated in.' +
39
- OPEN_CONVERSATION_DESCRIPTION +
40
- UNTRUSTED_DESCRIPTION_SUFFIX,
41
- annotations: toolAnnotations({ readOnly: true, openWorld: true }),
42
- inputSchema: { limit: limitArg(200, 'messages'), since: sinceArg },
43
- }, async ({ limit, since }) => {
44
108
  try {
45
- const all = await client.getOpenChatMessages();
46
- const identity = await readOpenConversation(client, 'chat');
47
- const { rows: messages, truncated } = trimRows(filterSince(all, since), limit, 'end', 200);
48
- return untrustedResult({ ...identity, messages, ...(truncated ? { truncated } : {}) });
109
+ const { rows, retitle, errors: _untitledErrors, ...unreadInfo } = await listSummaries(chatsvc, {
110
+ kinds: ['group', 'meeting', 'oneOnOne', 'self'],
111
+ unread_only,
112
+ since_days,
113
+ older_unread,
114
+ query,
115
+ searchMessages: search_messages,
116
+ activeSince,
117
+ activeUntil,
118
+ });
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);
128
+ return untrustedResult({ chats, ...unreadInfo, ...(errors ? { errors } : {}), ...(truncated ? { truncated } : {}) });
49
129
  }
50
130
  catch (err) {
51
- throw wrapBridgeError(err, 'read the open chat');
131
+ throw wrapApiError(err, 'list chats');
52
132
  }
53
133
  });
54
134
  }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Confirm-by-fetch: the one rule every unread answer goes through.
3
+ *
4
+ * The conversation listing cannot say whether a conversation is unread. Live
5
+ * (2026-10-10, a real tenant): `lastimreceivedtime` equals the last message's
6
+ * id even when that is a call recording; `lastMessage` can be stale, showing an
7
+ * older real message while only `Event/Call` and `ThreadActivity/*` came after
8
+ * the horizon; and a meeting chat never opened has no horizon at all. Reading
9
+ * the messages past the horizon matched Teams exactly (0 of 32 meeting-chat
10
+ * candidates were really unread). So the listing only nominates candidates
11
+ * (`isUnreadCandidate`), and a candidate counts as unread only when a read past
12
+ * its horizon finds a real message from someone else (`isUnread`). A candidate
13
+ * that answers 404 or 403 — a channel that is gone, or no longer readable — is
14
+ * not unread; it is skipped and counted, never reported as an error.
15
+ *
16
+ * A `since` window (`since_days`, default {@link DEFAULT_SINCE_DAYS}) keeps
17
+ * only conversations whose newest real unread message is inside it. Live
18
+ * (2026-10-10): 14 of 16 confirmed-unread channels had last moved months or
19
+ * years ago, in teams the user never looks at. A candidate whose newest
20
+ * activity of any kind is already older than the window is skipped without a
21
+ * read; both kinds of skip are kept in `older` (counted in `older_unread_skipped`,
22
+ * listed with `older_unread`), never dropped silently.
23
+ */
24
+ import { errorStatusOf, mapWithConcurrency } from '@chrischall/mcp-utils';
25
+ import { z } from 'zod';
26
+ import { isUnread, newestActivityMs, readHorizon } from '../model.js';
27
+ import { makeLimitedStopAt } from './limit.js';
28
+ /** Candidates read at once. */
29
+ export const CONFIRM_CONCURRENCY = 4;
30
+ export const DEFAULT_SINCE_DAYS = 14;
31
+ export const MAX_SINCE_DAYS = 3650;
32
+ const DAY_MS = 86_400_000;
33
+ /** The optional `since_days` argument shared by every unread answer. */
34
+ export function sinceDaysArg(scope = '') {
35
+ return z
36
+ .number()
37
+ .int()
38
+ .min(1)
39
+ .max(MAX_SINCE_DAYS)
40
+ .optional()
41
+ .describe(`${scope}Only count a conversation as unread when its newest unread message arrived in the last ` +
42
+ `since_days days (default ${DEFAULT_SINCE_DAYS}, max ${MAX_SINCE_DAYS}). Older unread ` +
43
+ 'conversations are left out and counted in older_unread_skipped; pass a larger since_days ' +
44
+ 'to include them.');
45
+ }
46
+ /** The start of the `since_days` window (epoch ms), measured from now. */
47
+ export function sinceCutoff(sinceDays) {
48
+ return Date.now() - (sinceDays ?? DEFAULT_SINCE_DAYS) * DAY_MS;
49
+ }
50
+ /**
51
+ * What a result says about conversations the window left out: always the
52
+ * count, and a hint only when something was left out.
53
+ */
54
+ export function olderUnreadReport(olderSkipped, sinceDays) {
55
+ const days = sinceDays ?? DEFAULT_SINCE_DAYS;
56
+ return {
57
+ older_unread_skipped: olderSkipped,
58
+ ...(olderSkipped > 0
59
+ ? {
60
+ older_unread_hint: `${olderSkipped} conversation${olderSkipped === 1 ? '' : 's'} with unread activity older than ` +
61
+ `${days} days ${olderSkipped === 1 ? 'was' : 'were'} left out; pass a larger since_days ` +
62
+ `(max ${MAX_SINCE_DAYS}) to include ${olderSkipped === 1 ? 'it' : 'them'}, or older_unread: true ` +
63
+ `to list ${olderSkipped === 1 ? 'it' : 'them'}.`,
64
+ }
65
+ : {}),
66
+ };
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
+ }
103
+ /** A 404 or 403: the conversation is gone or not readable, so it is not unread. */
104
+ export function isUnreachable(err) {
105
+ const status = errorStatusOf(err);
106
+ return status === 404 || status === 403;
107
+ }
108
+ /**
109
+ * Read a conversation's messages past `horizon`, newest first, keeping only
110
+ * the real unread ones (`isUnread`). Stops at the horizon, at the first real
111
+ * unread message past `limit`, or after `maxRaw` raw messages.
112
+ */
113
+ export async function readUnread(chatsvc, id, horizon, me, { limit, maxRaw }) {
114
+ const wanted = (m) => isUnread(m, horizon, me);
115
+ const limited = makeLimitedStopAt(horizon, wanted, limit);
116
+ let capped = false;
117
+ const fetched = await chatsvc.getMessages(id, {
118
+ stopAt: limited.stopAt,
119
+ max: maxRaw,
120
+ onCapped: () => (capped = true),
121
+ });
122
+ return { messages: fetched.filter(wanted), truncated: limited.truncated || capped };
123
+ }
124
+ /**
125
+ * Read each candidate past its own horizon, {@link CONFIRM_CONCURRENCY} at a
126
+ * time, and keep those with a real unread message. One read failing never
127
+ * costs the others; when every read failed (none confirmed, none came back
128
+ * empty), the first failure is thrown — it is a failure of the call (a revoked
129
+ * token, a rate limit), not of one conversation.
130
+ *
131
+ * With `since` (epoch ms), a candidate whose newest activity predates it is
132
+ * not read at all, and one whose newest real unread message predates it is
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.
138
+ */
139
+ export async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts) {
140
+ const byId = new Map(raw.map((c) => [c.id, c]));
141
+ const since = opts.since ?? 0;
142
+ const results = await mapWithConcurrency(candidates, CONFIRM_CONCURRENCY, async (summary) => {
143
+ const conv = byId.get(summary.id) ?? { id: summary.id };
144
+ const newest = newestActivityMs(conv);
145
+ // Nothing at all happened inside the window, so no unread message can be in it.
146
+ if (newest !== undefined && newest < since)
147
+ return { kind: 'older' };
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);
151
+ try {
152
+ return { kind: 'read', read: await readUnread(chatsvc, summary.id, horizon, me, opts) };
153
+ }
154
+ catch (error) {
155
+ return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
156
+ }
157
+ });
158
+ const outcome = { confirmed: [], skippedUnreachable: 0, older: [], failed: [] };
159
+ let anyRead = false;
160
+ results.forEach((r, i) => {
161
+ const summary = candidates[i];
162
+ if (r.kind === 'older')
163
+ outcome.older.push({ summary });
164
+ else if (r.kind === 'unreachable')
165
+ outcome.skippedUnreachable++;
166
+ else if (r.kind === 'failed')
167
+ outcome.failed.push({ summary, error: r.error });
168
+ else {
169
+ anyRead = true;
170
+ // Read newest first, so the first message is the newest real unread one.
171
+ const newestUnread = r.read.messages[0];
172
+ if (newestUnread === undefined)
173
+ return;
174
+ if (Number(newestUnread.id) < since)
175
+ outcome.older.push({ summary, read: r.read });
176
+ else
177
+ outcome.confirmed.push({ summary, read: r.read });
178
+ }
179
+ });
180
+ const first = outcome.failed[0];
181
+ if (first !== undefined && !anyRead)
182
+ throw first.error;
183
+ return outcome;
184
+ }
185
+ /** A summary whose unread state a read has settled. */
186
+ export function confirmedSummary(summary, unread) {
187
+ return { ...summary, unread, unread_confirmed: true };
188
+ }