@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
@@ -0,0 +1,217 @@
1
+ import { z } from 'zod';
2
+ import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, McpToolError, toolAnnotations, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
3
+ import { outcomeUnknownStatus } from '../chatsvc.js';
4
+ import { clipText } from '../compose.js';
5
+ import { htmlToText, normaliseMessage, senderMri } from '../model.js';
6
+ import { wrapApiError } from './errors.js';
7
+ import { resolveTarget, SELF_CHAT } from './send.js';
8
+ import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
+ const TOOL = 'teams_react';
10
+ /**
11
+ * The ✅ reaction's key, from the unicode-style key rule (see `KEY_RULE`) and
12
+ * confirmed live 2026-10-10 by reading a ✅ the user added in Teams itself.
13
+ */
14
+ export const CHECKMARK_KEY = '2705_whiteheavycheckmark';
15
+ /** Friendly names and emoji → reaction key. Emoji are matched without U+FE0F. */
16
+ const ALIASES = {
17
+ thumbsup: 'like',
18
+ '👍': 'like',
19
+ like: 'like',
20
+ heart: 'heart',
21
+ '❤': 'heart',
22
+ laugh: 'laugh',
23
+ '😆': 'laugh',
24
+ surprised: 'surprised',
25
+ '😮': 'surprised',
26
+ sad: 'sad',
27
+ '😢': 'sad',
28
+ angry: 'angry',
29
+ '😡': 'angry',
30
+ checkmark: CHECKMARK_KEY,
31
+ '✅': CHECKMARK_KEY,
32
+ };
33
+ /** What a raw key looks like: a legacy name (`fire`) or a unicode-style key (`1f62c_grimacingface`). */
34
+ const RAW_KEY = /^[a-z0-9_]+$/;
35
+ const KEY_RULE = 'Unicode-style reaction keys are "<lowercase hex code point>_<the Unicode character name, lowercased, ' +
36
+ 'spaces and punctuation removed>" — e.g. 💯 1f4af_hundredpointssymbol, 👀 1f440_eyes, 😬 1f62c_grimacingface. ' +
37
+ 'Teams also keeps short names for common ones: like, heart, laugh, surprised, sad, angry, yes, no, party, ' +
38
+ 'fire, smile, cool, wink, hearteyes, manshrug, fistbump, handsinair.';
39
+ /** Previewed text of the message reacted to. */
40
+ const PREVIEW_CHARS = 200;
41
+ /**
42
+ * The reaction key for what the caller passed: an alias (`thumbsup`, 👍, …),
43
+ * else a raw key as-is (case, spaces and surrounding `:colons:` ignored). An
44
+ * emoji with no alias is refused with the key rule — no Unicode-name database
45
+ * is bundled, so its key cannot be derived here.
46
+ */
47
+ export function reactionKey(input) {
48
+ const s = input.trim().replace(/️/g, '').replace(/^:(.+):$/, '$1').toLowerCase();
49
+ const alias = ALIASES[s];
50
+ if (alias !== undefined)
51
+ return alias;
52
+ if (RAW_KEY.test(s))
53
+ return s;
54
+ if (/\p{Extended_Pictographic}/u.test(s)) {
55
+ const points = [...s].map((c) => c.codePointAt(0).toString(16));
56
+ throw new McpToolError(`There is no known reaction key for ${input.trim()}; pass its key instead.`, {
57
+ hint: (points.length === 1
58
+ ? `Its code point is U+${points[0].toUpperCase()}, so its key is "${points[0]}_<its Unicode name>". `
59
+ : `Its code points are ${points.map((p) => `U+${p.toUpperCase()}`).join(' ')}. `) + KEY_RULE,
60
+ });
61
+ }
62
+ throw new McpToolError(`"${input}" is not a reaction: pass an emoji, a name such as thumbsup, or a reaction key.`, {
63
+ hint: KEY_RULE,
64
+ });
65
+ }
66
+ /**
67
+ * Whether the user's own reaction `key` is on the message, read fresh —
68
+ * `undefined` when the message is not there to read (404), which proves
69
+ * nothing either way.
70
+ */
71
+ async function hasMyReaction(chatsvc, conversationId, messageId, key, me) {
72
+ const m = await chatsvc.getMessage(conversationId, messageId);
73
+ if (m === undefined)
74
+ return undefined;
75
+ return normaliseMessage(m, me).reactions?.some((r) => r.key === key && r.byMe) ?? false;
76
+ }
77
+ export function registerReactTools(server, { chatsvc }) {
78
+ server.registerTool(TOOL, {
79
+ title: 'React to a Teams message',
80
+ description: 'Add (or, with remove: true, withdraw) the signed-in user\'s reaction on a message in any chat or ' +
81
+ 'channel. conversation is an id or name as for teams_read_conversation; message_id comes from ' +
82
+ 'teams_read_conversation. reaction is an emoji or name — thumbsup/👍/like, heart/❤️, laugh/😆, ' +
83
+ `surprised/😮, sad/😢, angry/😡, checkmark/✅ — or any raw Teams reaction key (e.g. fire, ` +
84
+ '1f389_partypopper); an emoji without a known key is refused with the rule for spelling its key. ' +
85
+ `conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — use it to try this tool. Everyone ` +
86
+ 'in the conversation sees the reaction. The result says whether reading the message back showed the ' +
87
+ 'change (verified; null when the message was not found again); status "unknown" means Teams did not ' +
88
+ 'confirm the change and the read-back did not show it — check the message before retrying. ' +
89
+ CONFIRM_FLOW_SENTENCE +
90
+ ' The preview shows the conversation, the message and the reaction. ' +
91
+ CONFIRM_INJECTION_RULE +
92
+ UNTRUSTED_DESCRIPTION_SUFFIX,
93
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
94
+ inputSchema: {
95
+ conversation: z
96
+ .string()
97
+ .min(1)
98
+ .describe(`The conversation id (or "${SELF_CHAT}" — also by the name "notes" or "self" — for the self-chat), ` +
99
+ "or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names."),
100
+ message_id: z.string().min(1).describe('The message to react to, as teams_read_conversation lists it.'),
101
+ reaction: z.string().min(1).describe('An emoji (👍), a name (thumbsup) or a Teams reaction key (like, 1f389_partypopper).'),
102
+ remove: z.boolean().optional().describe('Withdraw this reaction instead of adding it (default false).'),
103
+ confirmToken: confirmTokenParam,
104
+ },
105
+ }, async ({ conversation, message_id, reaction, remove, confirmToken }, ctx) => {
106
+ try {
107
+ const key = reactionKey(reaction);
108
+ const me = await chatsvc.meMri();
109
+ const target = await resolveTarget(chatsvc, conversation, me, 'react in');
110
+ const m = await chatsvc.getMessage(target.id, message_id);
111
+ if (m === undefined) {
112
+ throw new McpToolError(`There is no message ${message_id} in this conversation to react to.`, {
113
+ hint: 'Take message ids from teams_read_conversation.',
114
+ });
115
+ }
116
+ const already = normaliseMessage(m, me).reactions?.some((r) => r.key === key && r.byMe) ?? false;
117
+ const method = remove ? 'DELETE' : 'PUT';
118
+ const path = `/users/ME/conversations/${encodeURIComponent(target.id)}` +
119
+ `/messages/${encodeURIComponent(message_id)}/properties?name=emotions`;
120
+ const gate = await confirmWrite(ctx, {
121
+ tool: TOOL,
122
+ action: remove ? 'chat.remove_reaction' : 'chat.react',
123
+ message: `Review and confirm this Teams reaction before it is ${remove ? 'removed' : 'added'}:`,
124
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
125
+ summary: `${remove ? 'Remove' : 'Add'} reaction "${key}" on a message in ${target.kind} ${JSON.stringify(target.title)}`,
126
+ // The signed-in user, so an approval minted under one account never reacts as another.
127
+ account: me,
128
+ target: `${target.id}/${message_id}`,
129
+ // The reaction time is minted when the reaction is set, so it is not bound.
130
+ request: { method, path, body: { emotions: { key } } },
131
+ // The title and the message are written by other people, so each is
132
+ // fenced as a read tool's result is.
133
+ preview: {
134
+ conversation: untrustedField(target),
135
+ message: untrustedField({
136
+ id: m.id,
137
+ sender: m.imdisplayname?.trim() || senderMri(m.from) || 'unknown',
138
+ preview: clipText(htmlToText(m.content ?? ''), PREVIEW_CHARS),
139
+ }),
140
+ reaction: key,
141
+ already_reacted: already,
142
+ },
143
+ confirmToken,
144
+ });
145
+ if (gate)
146
+ return gate;
147
+ let unconfirmed;
148
+ try {
149
+ if (remove)
150
+ await chatsvc.removeReaction(target.id, message_id, key);
151
+ else
152
+ await chatsvc.setReaction(target.id, message_id, key);
153
+ }
154
+ catch (e) {
155
+ if (!(e instanceof WriteOutcomeUnknownError))
156
+ throw e;
157
+ unconfirmed = e;
158
+ }
159
+ // true / false: the read-back shows the change / does not; null: the
160
+ // message is gone (404), so it shows nothing either way.
161
+ let verified = false;
162
+ let readBackFailed = false;
163
+ try {
164
+ const present = await hasMyReaction(chatsvc, target.id, message_id, key, me);
165
+ verified = present === undefined ? null : remove ? !present : present;
166
+ }
167
+ catch {
168
+ readBackFailed = true;
169
+ }
170
+ const shown = remove ? 'gone' : 'present';
171
+ if (unconfirmed !== undefined && verified !== true) {
172
+ const status = outcomeUnknownStatus(unconfirmed);
173
+ const why = unconfirmed.timedOut
174
+ ? 'it did not answer in time'
175
+ : status !== undefined
176
+ ? `it answered HTTP ${status}`
177
+ : 'the connection dropped';
178
+ return untrustedResult({
179
+ status: 'unknown',
180
+ conversation: target,
181
+ message_id,
182
+ reaction: key,
183
+ verified,
184
+ warning: `Teams did not confirm this change (${why}), and reading the message back ` +
185
+ `${readBackFailed ? 'failed' : verified === null ? 'did not find it' : `did not show the reaction ${shown}`} — ` +
186
+ 'check the message (teams_read_conversation) before retrying.',
187
+ });
188
+ }
189
+ let warning;
190
+ if (unconfirmed !== undefined) {
191
+ warning = `Teams did not confirm this change, but reading the message back shows the reaction ${shown}.`;
192
+ }
193
+ else if (readBackFailed) {
194
+ warning = 'Teams accepted the change, but reading the message back failed — check the message (teams_read_conversation).';
195
+ }
196
+ else if (verified === null) {
197
+ warning =
198
+ 'Teams accepted the change, but the message was not found on reading it back (it may have been deleted) — ' +
199
+ 'check the conversation (teams_read_conversation).';
200
+ }
201
+ else if (!verified) {
202
+ warning = `Teams accepted the change, but reading the message back did not show the reaction ${shown} — check the message (teams_read_conversation); the key may not be one Teams knows.`;
203
+ }
204
+ return untrustedResult({
205
+ status: remove ? 'removed' : 'reacted',
206
+ conversation: target,
207
+ message_id,
208
+ reaction: key,
209
+ verified,
210
+ ...(warning !== undefined ? { warning } : {}),
211
+ });
212
+ }
213
+ catch (err) {
214
+ throw wrapApiError(err, 'react to the message');
215
+ }
216
+ });
217
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Channel thread roots that lie outside a read's window.
3
+ *
4
+ * A channel read groups replies under their root post (`format.ts`), but the
5
+ * window — `since`, `limit`, a cursor, or the read horizon for unread — often
6
+ * ends after a thread's root while its newer replies are inside. Each such
7
+ * root is fetched by id (`GET …/conversations/{channelId}/messages/{rootId}`,
8
+ * verified live 2026-10-12: it answers for a root weeks older than the window,
9
+ * in ~250 ms) so the thread keeps its subject, time and sender. A fetched root
10
+ * is context, not part of the read: it is shown marked `outside_window` and
11
+ * counts toward no unread count, message count or cursor.
12
+ *
13
+ * Fetches are bounded per CALL — {@link MAX_ROOT_FETCHES}, shared by every
14
+ * conversation the call reads, newest threads first — and a few run at once.
15
+ * A root past the budget, gone, or unreadable (the service answers 403, not
16
+ * 404, for an id it does not hold) stays the `{ id, missing: true }`
17
+ * placeholder.
18
+ */
19
+ import { mapWithConcurrency } from '@chrischall/mcp-utils';
20
+ import { normaliseMessage } from '../model.js';
21
+ /** Root fetches one tool call may make, across every conversation it reads. */
22
+ export const MAX_ROOT_FETCHES = 25;
23
+ /** Root fetches in flight at once. */
24
+ export const ROOT_FETCH_CONCURRENCY = 5;
25
+ export function rootBudget() {
26
+ return { remaining: MAX_ROOT_FETCHES };
27
+ }
28
+ /**
29
+ * The roots of `messages` (oldest first, as normalised) that they do not
30
+ * themselves hold, newest thread first: the ones worth fetching first when the
31
+ * budget runs short.
32
+ */
33
+ function outsideRootIds(messages) {
34
+ const held = new Set(messages.map((m) => m.id));
35
+ const ids = new Set();
36
+ for (let i = messages.length - 1; i >= 0; i--) {
37
+ const root = messages[i].replyTo;
38
+ if (root !== undefined && !held.has(root))
39
+ ids.add(root);
40
+ }
41
+ return [...ids];
42
+ }
43
+ /**
44
+ * Fetch the roots a channel read's replies point at but its window does not
45
+ * hold, spending from `budget`. Returns those found, by id, normalised as the
46
+ * read's own messages are; a root that failed, came back as some other
47
+ * message, or is itself a reply is left out (it stays missing).
48
+ */
49
+ export async function fetchOutsideRoots(chatsvc, conversationId, messages, me, { budget, timeZone }) {
50
+ const wanted = outsideRootIds(messages);
51
+ // Taken synchronously, so conversations read concurrently cannot overspend it.
52
+ const ids = wanted.slice(0, Math.max(0, budget.remaining));
53
+ budget.remaining -= ids.length;
54
+ const roots = new Map();
55
+ if (ids.length === 0)
56
+ return roots;
57
+ const fetched = await mapWithConcurrency(ids, ROOT_FETCH_CONCURRENCY, async (id) => {
58
+ try {
59
+ return await chatsvc.getMessage(conversationId, id);
60
+ }
61
+ catch {
62
+ return undefined;
63
+ }
64
+ });
65
+ fetched.forEach((raw, i) => {
66
+ if (raw === undefined || raw.id !== ids[i])
67
+ return;
68
+ const root = normaliseMessage(raw, me, { timeZone });
69
+ if (root.replyTo === undefined)
70
+ roots.set(root.id, root);
71
+ });
72
+ return roots;
73
+ }