@chrischall/microsoft-teams-mcp 0.2.7 → 0.4.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 (39) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +3 -3
  3. package/README.md +281 -87
  4. package/dist/auth-fetchproxy.js +138 -0
  5. package/dist/bundle.js +42668 -37351
  6. package/dist/capture-window.js +41 -0
  7. package/dist/chatsvc.js +552 -0
  8. package/dist/compose.js +241 -0
  9. package/dist/deps.js +1 -0
  10. package/dist/index.js +26 -6
  11. package/dist/model.js +499 -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/token-cache.js +67 -0
  16. package/dist/tools/activity.js +156 -13
  17. package/dist/tools/attachment.js +174 -0
  18. package/dist/tools/channels.js +62 -38
  19. package/dist/tools/chat.js +48 -35
  20. package/dist/tools/confirm.js +145 -0
  21. package/dist/tools/conversation.js +172 -26
  22. package/dist/tools/errors.js +18 -17
  23. package/dist/tools/healthcheck.js +86 -12
  24. package/dist/tools/limit.js +83 -0
  25. package/dist/tools/listing.js +116 -0
  26. package/dist/tools/react.js +217 -0
  27. package/dist/tools/send.js +309 -0
  28. package/dist/tools/titles.js +180 -0
  29. package/dist/tools/unread.js +162 -0
  30. package/dist/tools/untrusted.js +16 -1
  31. package/dist/version.js +1 -1
  32. package/mint.yaml +63 -20
  33. package/package.json +3 -4
  34. package/server.json +96 -4
  35. package/skills/teams-fpx/SKILL.md +108 -92
  36. package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
  37. package/skills/teams-fpx/references/teams-env.sh +146 -0
  38. package/dist/client.js +0 -281
  39. 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,309 @@
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 { buildSendBody, clipText, mentionsProperty, newClientMessageId, qtdMsgsProperty, quoteHtml, renderMessageHtml, } from '../compose.js';
5
+ import { htmlToText, isUserMessage, normaliseMessage, SELF_CHAT, senderMri } from '../model.js';
6
+ import { resolveListed } from './conversation.js';
7
+ import { wrapApiError } from './errors.js';
8
+ import { THIRD_PARTY_NAMES_NOTE, untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX, } from './untrusted.js';
9
+ const TOOL = 'teams_send_message';
10
+ /**
11
+ * The user's own notes chat — the one `48:*` system conversation that takes
12
+ * messages, and the safe place to try this tool out. Every other `48:*` id
13
+ * (calendar, notifications, …) is refused.
14
+ */
15
+ export { SELF_CHAT };
16
+ /** Recent messages scanned for mention candidates and for the read-back. */
17
+ const RECENT_MESSAGES = 200;
18
+ const READBACK_MESSAGES = 50;
19
+ /** Candidates a mention error lists. */
20
+ const MAX_CANDIDATES = 10;
21
+ /** Previewed text of a quoted message. */
22
+ const PREVIEW_CHARS = 200;
23
+ /** An MRI such as `8:orgid:<oid>` (a person) or `28:<id>` (a bot). */
24
+ const MRI = /^\d+:\S+$/;
25
+ const mentionArg = z.object({
26
+ name_in_text: z
27
+ .string()
28
+ .min(1)
29
+ .describe('How the person is named in text — its first "@name" (else "name") becomes the mention.'),
30
+ person: z
31
+ .string()
32
+ .min(1)
33
+ .describe('Who to mention: an MRI (8:orgid:…), or a display name matched among recent senders in this conversation.'),
34
+ });
35
+ /**
36
+ * The conversation a write goes to: `48:notes` (also by the names `notes` /
37
+ * `self`), else an id or name as `teams_read_conversation` resolves it. `verb` words the refusals ("post to",
38
+ * "react in").
39
+ */
40
+ export async function resolveTarget(chatsvc, conversation, me, verb = 'post to') {
41
+ if (conversation === SELF_CHAT)
42
+ return { id: SELF_CHAT, title: 'Notes (self-chat)', kind: 'self' };
43
+ if (conversation.startsWith('48:')) {
44
+ throw new McpToolError(`Refusing to ${verb} the Teams system conversation ${conversation}.`, {
45
+ hint: `Only ${SELF_CHAT} (the self-chat) takes messages among 48: ids; pass a chat or channel instead.`,
46
+ });
47
+ }
48
+ const raw = await chatsvc.listConversations();
49
+ const s = await resolveListed(chatsvc, raw, me, conversation, verb);
50
+ return { id: s.id, title: s.title, kind: s.kind };
51
+ }
52
+ /** Who has written in the conversation lately, by MRI → display name. */
53
+ async function recentSenders(chatsvc, conversationId) {
54
+ const out = new Map();
55
+ for (const m of await chatsvc.getMessages(conversationId, { max: RECENT_MESSAGES })) {
56
+ const mri = senderMri(m.from);
57
+ const name = m.imdisplayname?.trim();
58
+ if (isUserMessage(m) && mri !== undefined && name && !out.has(mri))
59
+ out.set(mri, name);
60
+ }
61
+ return out;
62
+ }
63
+ /**
64
+ * Each mention's MRI: an MRI is taken as-is; a name must match exactly one
65
+ * recent sender (exactly, else as a substring, ignoring case). Ambiguous or
66
+ * unknown is an error naming the candidates — never a guess.
67
+ */
68
+ async function resolveMentions(chatsvc, conversationId, mentions) {
69
+ if (mentions.length === 0)
70
+ return [];
71
+ const senders = mentions.every((m) => MRI.test(m.person.trim()))
72
+ ? new Map()
73
+ : await recentSenders(chatsvc, conversationId);
74
+ const known = [...senders].map(([mri, name]) => ({ mri, name }));
75
+ return mentions.map(({ name_in_text, person }) => {
76
+ const p = person.trim();
77
+ if (MRI.test(p))
78
+ return { target: { text: name_in_text, mri: p }, person: p };
79
+ const q = p.toLowerCase();
80
+ const exact = known.filter((k) => k.name.toLowerCase() === q);
81
+ const found = exact.length > 0 ? exact : known.filter((k) => k.name.toLowerCase().includes(q));
82
+ if (found.length === 1)
83
+ return { target: { text: name_in_text, mri: found[0].mri }, person: found[0].name };
84
+ // Candidate names are other people's display names: JSON-quoted and
85
+ // flagged as data, as a read tool's envelope would.
86
+ if (found.length > 1) {
87
+ const named = found
88
+ .slice(0, MAX_CANDIDATES)
89
+ .map((k) => `${JSON.stringify(k.name)} (${k.mri})`)
90
+ .join('; ');
91
+ throw new McpToolError(`"${person}" matches ${found.length} people in this conversation: ${named}. ${THIRD_PARTY_NAMES_NOTE}`, { hint: 'Pass the MRI of the one to mention as person.' });
92
+ }
93
+ const some = known
94
+ .slice(0, MAX_CANDIDATES)
95
+ .map((k) => JSON.stringify(k.name))
96
+ .join(', ');
97
+ throw new McpToolError(`No recent sender in this conversation is called "${person}".`, {
98
+ hint: (some ? `Recent senders: ${some}. ${THIRD_PARTY_NAMES_NOTE} ` : '') +
99
+ 'Pass an exact display name, or the person\'s MRI (8:orgid:…) as person.',
100
+ });
101
+ });
102
+ }
103
+ /** The message a quote points at, read for its sender and text. */
104
+ async function quoted(chatsvc, conversationId, id) {
105
+ const m = await chatsvc.getMessage(conversationId, id);
106
+ if (m === undefined) {
107
+ throw new McpToolError(`There is no message ${id} in this conversation to quote.`, {
108
+ hint: 'Take message ids from teams_read_conversation.',
109
+ });
110
+ }
111
+ const mri = senderMri(m.from) ?? '';
112
+ return { id: m.id, senderMri: mri, senderName: m.imdisplayname?.trim() || mri, text: htmlToText(m.content ?? '') };
113
+ }
114
+ /**
115
+ * The channel root post a threaded reply goes under, read to prove it is one:
116
+ * it must exist in this channel and not itself be a reply (Teams threads are
117
+ * one level deep, so a reply cannot itself be replied under).
118
+ */
119
+ async function threadRoot(chatsvc, channelId, id, me) {
120
+ const m = await chatsvc.getMessage(channelId, id);
121
+ if (m === undefined) {
122
+ throw new McpToolError(`There is no post ${id} in this channel to reply under.`, {
123
+ hint: 'Take the root post\'s id from teams_read_conversation.',
124
+ });
125
+ }
126
+ const replyTo = normaliseMessage(m, me).replyTo;
127
+ if (replyTo !== undefined) {
128
+ throw new McpToolError(`Message ${id} is itself a reply in this channel, not a root post.`, {
129
+ hint: `Reply under its root post instead: reply_to "${replyTo}".`,
130
+ });
131
+ }
132
+ }
133
+ /**
134
+ * A send that may or may not have landed becomes a `status: "unknown"`
135
+ * result, never an error: an error invites a fresh preview and a second post.
136
+ * Any other failure is a real failure and still throws.
137
+ */
138
+ async function writeOrUnknown(run, conversation) {
139
+ try {
140
+ return { ok: true, value: await run() };
141
+ }
142
+ catch (e) {
143
+ if (!(e instanceof WriteOutcomeUnknownError))
144
+ throw e;
145
+ const status = outcomeUnknownStatus(e);
146
+ const why = e.timedOut
147
+ ? 'it did not answer in time'
148
+ : status !== undefined
149
+ ? `it answered HTTP ${status} after the post was sent`
150
+ : 'the connection dropped';
151
+ return {
152
+ ok: false,
153
+ result: untrustedResult({
154
+ status: 'unknown',
155
+ conversation,
156
+ warning: `Teams did not confirm this post (${why}), ` +
157
+ 'so it may already be in the conversation. Check the conversation before retrying ' +
158
+ '(teams_read_conversation); do not resend blindly.',
159
+ }),
160
+ };
161
+ }
162
+ }
163
+ export function registerSendTools(server, { chatsvc }) {
164
+ server.registerTool(TOOL, {
165
+ title: 'Send a Teams message',
166
+ description: 'Post a message as the signed-in user to any chat or channel, by id (from teams_list_chats / ' +
167
+ 'teams_list_teams_and_channels) or by name. text is plain text: it is escaped, newlines are kept, ' +
168
+ 'and :key: shortcodes (e.g. :smile:, :1f389_partypopper:) become Teams emoji. reply_to in a ' +
169
+ 'channel posts into that root post\'s thread; in a chat it quote-replies that message. quote ' +
170
+ 'quote-replies a message in any conversation. mentions @-mention people: name_in_text must appear ' +
171
+ 'in text, and person is an MRI or a display name matched among recent senders (ambiguous names ' +
172
+ `are refused with the candidates). conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — ` +
173
+ 'use it to try this tool without anyone else seeing; other 48: system conversations are refused. ' +
174
+ 'Everyone in the conversation sees the post. The result says whether the post was found again by ' +
175
+ 'reading the conversation back (verified); status "unknown" means Teams did not confirm it — check ' +
176
+ 'the conversation before retrying. ' +
177
+ CONFIRM_FLOW_SENTENCE +
178
+ ' The preview shows the conversation and exactly what would be posted. ' +
179
+ CONFIRM_INJECTION_RULE +
180
+ UNTRUSTED_DESCRIPTION_SUFFIX,
181
+ annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: false, openWorld: true }),
182
+ inputSchema: {
183
+ conversation: z
184
+ .string()
185
+ .min(1)
186
+ .describe(`The conversation id (or "${SELF_CHAT}" — also by the name "notes" or "self" — for the self-chat), ` +
187
+ "or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names."),
188
+ text: z.string().min(1).describe('The message, as plain text. Newlines are kept; :key: shortcodes become emoji.'),
189
+ reply_to: z
190
+ .string()
191
+ .min(1)
192
+ .optional()
193
+ .describe('A message id. Channel: the root post to reply under (threaded). Chat: the message to quote-reply.'),
194
+ quote: z.string().min(1).optional().describe('A message id to quote-reply, in any conversation.'),
195
+ mentions: z.array(mentionArg).max(20).optional().describe('People to @-mention in text.'),
196
+ confirmToken: confirmTokenParam,
197
+ },
198
+ }, async ({ conversation, text, reply_to, quote, mentions, confirmToken }, ctx) => {
199
+ try {
200
+ const [me, meName] = await Promise.all([chatsvc.meMri(), chatsvc.meDisplayName()]);
201
+ const target = await resolveTarget(chatsvc, conversation, me);
202
+ const inChannel = target.kind === 'channel';
203
+ // In a chat there is no thread to reply under, so reply_to means "quote this".
204
+ let quoteId = quote;
205
+ if (!inChannel && reply_to !== undefined) {
206
+ if (quote !== undefined && quote !== reply_to) {
207
+ throw new McpToolError('reply_to and quote name different messages, and a chat message can quote only one.', {
208
+ hint: 'In a chat, pass just one of them.',
209
+ });
210
+ }
211
+ quoteId = reply_to;
212
+ }
213
+ // A threaded channel reply posts to "<channelId>;messageid=<rootId>" (unverified live; see the plan).
214
+ const postTo = inChannel && reply_to !== undefined ? `${target.id};messageid=${reply_to}` : target.id;
215
+ if (inChannel && reply_to !== undefined)
216
+ await threadRoot(chatsvc, target.id, reply_to, me);
217
+ const q = quoteId !== undefined ? await quoted(chatsvc, target.id, quoteId) : undefined;
218
+ const people = await resolveMentions(chatsvc, target.id, mentions ?? []);
219
+ const rendered = renderMessageHtml(text, people.map((p) => p.target));
220
+ const content = (q ? quoteHtml(q) : '') + rendered.html;
221
+ const properties = {
222
+ ...(rendered.mentions.length > 0 ? { mentions: mentionsProperty(rendered.mentions) } : {}),
223
+ ...(q ? { qtdMsgs: qtdMsgsProperty(q) } : {}),
224
+ };
225
+ // What is bound and previewed: the body minus the parts minted at send
226
+ // time (clientmessageid, timestamps), which differ on every call and
227
+ // would otherwise refuse every phase-2 call as changed.
228
+ const draft = buildSendBody({ conversationId: postTo, meMri: me, meName, content, clientmessageid: '', now: new Date(0), ...properties });
229
+ const { clientmessageid: _id, composetime: _c, originalarrivaltime: _o, ...bound } = draft;
230
+ const path = `/users/ME/conversations/${encodeURIComponent(postTo)}/messages`;
231
+ const gate = await confirmWrite(ctx, {
232
+ tool: TOOL,
233
+ action: 'chat.send_message',
234
+ message: 'Review and confirm this Teams message before it is posted:',
235
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
236
+ summary: `Post a message to ${target.kind} ${JSON.stringify(target.title)}`,
237
+ // The signed-in user, so an approval minted under one account never posts as another.
238
+ account: me,
239
+ target: postTo,
240
+ request: { method: 'POST', path, body: bound },
241
+ // The conversation title, the quoted message and the resolved names
242
+ // are written by other people, so each is fenced as a read tool's
243
+ // result is; `text` is the caller's own.
244
+ preview: {
245
+ conversation: untrustedField(target),
246
+ text,
247
+ ...(inChannel && reply_to !== undefined ? { thread_root: reply_to } : {}),
248
+ ...(people.length > 0
249
+ ? {
250
+ mentions: untrustedField(people.map((p, i) => ({
251
+ name_in_text: mentions[i].name_in_text,
252
+ person: p.person,
253
+ mri: p.target.mri,
254
+ }))),
255
+ }
256
+ : {}),
257
+ ...(q
258
+ ? { quoting: untrustedField({ id: q.id, sender: q.senderName, preview: clipText(q.text, PREVIEW_CHARS) }) }
259
+ : {}),
260
+ note: 'clientmessageid and the timestamps are filled in when the message is posted.',
261
+ },
262
+ confirmToken,
263
+ });
264
+ if (gate)
265
+ return gate;
266
+ const clientmessageid = newClientMessageId();
267
+ const body = buildSendBody({
268
+ conversationId: postTo,
269
+ meMri: me,
270
+ meName,
271
+ content,
272
+ clientmessageid,
273
+ now: new Date(),
274
+ ...properties,
275
+ });
276
+ const sent = await writeOrUnknown(() => chatsvc.sendMessage(postTo, body), target);
277
+ if (!sent.ok)
278
+ return sent.result;
279
+ // Read back: a channel lists its thread replies, so read the channel itself.
280
+ let found;
281
+ let readBackFailed = false;
282
+ try {
283
+ const recent = await chatsvc.getMessages(target.id, { max: READBACK_MESSAGES });
284
+ found = recent.find((m) => m.clientmessageid === clientmessageid)?.id;
285
+ }
286
+ catch {
287
+ readBackFailed = true;
288
+ }
289
+ const verified = found !== undefined;
290
+ const message_id = sent.value.id ?? found;
291
+ return untrustedResult({
292
+ status: 'sent',
293
+ conversation: target,
294
+ ...(message_id !== undefined ? { message_id } : {}),
295
+ verified,
296
+ ...(verified
297
+ ? {}
298
+ : {
299
+ warning: readBackFailed
300
+ ? 'Teams accepted the post, but reading the conversation back failed — check it before posting again.'
301
+ : 'Teams accepted the post, but it was not among the newest messages on reading back — check the conversation before posting again.',
302
+ }),
303
+ });
304
+ }
305
+ catch (err) {
306
+ throw wrapApiError(err, 'send the message');
307
+ }
308
+ });
309
+ }