@chrischall/microsoft-teams-mcp 0.10.0 → 0.12.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.
package/dist/recap.js ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Meeting recaps: the Meeting Collab Platform Service (MCPS) behind Teams'
3
+ * Recap tab.
4
+ *
5
+ * GET https://teams.cloud.microsoft/api/mcps/<region>/collab/readcollabobject/V2/
6
+ * <organizerOid>@<tenantId>/<occurrence id>/<meeting thread id>
7
+ * [Authorization: Bearer <MCPS token> — see `recap-auth.ts`]
8
+ * → { changeKey, id?, participants: [], resources: [{ id, type, location,
9
+ * metadata: { … }, subType, addedBy, additionDateTime }], … }
10
+ *
11
+ * Verified live 2026-11-10 against a real tenant (40 meeting chats sampled):
12
+ * - the organizer, tenant and series `iCalUid` come from the meeting thread's
13
+ * `meeting` property (`GET /threads/<id>`), as does `meetingType`
14
+ * (`Recurring` / `Scheduled`);
15
+ * - the occurrence id is the `iCalUid` (an Outlook GlobalObjectId, hex) with
16
+ * bytes 16-19 — hex characters 32-39 — set to the occurrence's year (2
17
+ * bytes), month and day; a one-off meeting, and a recurring series as a
18
+ * whole, use the `iCalUid` as it is (those bytes zero). The day was the
19
+ * same in UTC and the organizer's zone in every sample: which one MCPS
20
+ * means is not established;
21
+ * - an occurrence with nothing recorded answers 200 with `resources: []`;
22
+ * - resource types seen: `Recording` (location: the OneDrive/Stream play
23
+ * link; .NET-tick start/end), `TranscriptV2` (location: a SharePoint
24
+ * `/media/transcripts/<id>/content` API URL; `metadata.duration`),
25
+ * `transcript` (an older kind, ISO start), `notes` (the Loop meeting-notes
26
+ * page), `AttendanceReport`, `MeetingChat` (a file shared in the meeting
27
+ * chat), `MeetingStage` (shared on stage, e.g. a Whiteboard) and
28
+ * `AISummary` (the Intelligent Recap AI notes);
29
+ * - the AI notes themselves are a per-user file read through MCPS
30
+ * `groundingdata/drives/<d>/items/<i>/recapAISummary`: that answered 403
31
+ * ("Graph denied access") for anyone but the file's owner, and an
32
+ * unlicensed user sees no notes in Teams either. So this module reports
33
+ * that a summary exists, and never reads it;
34
+ * - the chat-service token is a 401 here: MCPS needs its own token.
35
+ *
36
+ * The bearer only ever goes to a URL this module BUILDS from vetted parts
37
+ * (GUIDs, a hex occurrence id, a `19:…@thread.v2` id) — never to a URL taken
38
+ * from a response.
39
+ */
40
+ import { fetchBounded, McpToolError, parseBoolEnv, readEnvVar } from '@chrischall/mcp-utils';
41
+ import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
42
+ import { describeTransportFailure } from './network-error.js';
43
+ import { createRecapTokenCache } from './recap-token-cache.js';
44
+ /** The MCPS region this tenant was verified on. */
45
+ export const DEFAULT_MCPS_REGION = 'us';
46
+ /** Per-request deadline, covering the body read. */
47
+ const REQUEST_TIMEOUT_MS = 30_000;
48
+ /** A collab object is a list of links; anything near this is not one. */
49
+ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
50
+ const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
51
+ /** An Outlook GlobalObjectId as hex: the 16-byte class id, the date, then the rest. */
52
+ const GOID = /^[0-9a-f]{40,256}$/i;
53
+ const THREAD_ID = /^19:[A-Za-z0-9_-]+@thread\.(?:v2|tacv2|skype)$/;
54
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
55
+ /** .NET ticks at the Unix epoch. */
56
+ const EPOCH_TICKS = 621355968000000000n;
57
+ /** Capture lazily, so boot never loads the bridge. */
58
+ async function captureRecapTokenLazily() {
59
+ const mod = await import('./recap-auth.js');
60
+ return mod.captureRecapTokenViaFetchproxy();
61
+ }
62
+ function obj(v) {
63
+ return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
64
+ }
65
+ function str(v) {
66
+ return typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined;
67
+ }
68
+ function isoOf(v) {
69
+ const s = str(v);
70
+ if (s === undefined)
71
+ return undefined;
72
+ const ms = Date.parse(s);
73
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
74
+ }
75
+ function httpsUrl(v) {
76
+ const s = str(v);
77
+ return s !== undefined && /^https:\/\//i.test(s) ? s : undefined;
78
+ }
79
+ /**
80
+ * The meeting a thread's `meeting` property describes (a JSON string, as
81
+ * Teams sends it, or an object), or `undefined` when there is none or its ids
82
+ * are not ids.
83
+ */
84
+ export function parseMeetingInfo(thread) {
85
+ const raw = thread.properties?.meeting;
86
+ let m;
87
+ if (typeof raw === 'string') {
88
+ try {
89
+ m = obj(JSON.parse(raw));
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ }
95
+ else {
96
+ m = obj(raw);
97
+ }
98
+ const iCalUid = str(m?.iCalUid);
99
+ const organizerId = str(m?.organizerId);
100
+ const tenantId = str(m?.tenantId);
101
+ if (m === undefined || iCalUid === undefined || organizerId === undefined || tenantId === undefined)
102
+ return undefined;
103
+ if (!GOID.test(iCalUid) || !GUID.test(organizerId) || !GUID.test(tenantId))
104
+ return undefined;
105
+ const subject = str(m.subject);
106
+ const seriesStart = isoOf(m.startTime);
107
+ const joinUrl = httpsUrl(m.meetingJoinUrl);
108
+ return {
109
+ ...(subject !== undefined ? { subject } : {}),
110
+ iCalUid,
111
+ organizerId,
112
+ tenantId,
113
+ recurring: m.meetingType === 'Recurring',
114
+ ...(seriesStart !== undefined ? { seriesStart } : {}),
115
+ ...(joinUrl !== undefined ? { joinUrl } : {}),
116
+ };
117
+ }
118
+ /** Whether `date` is a real `YYYY-MM-DD` day. */
119
+ export function isOccurrenceDate(date) {
120
+ const m = DATE.exec(date);
121
+ if (!m)
122
+ return false;
123
+ const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
124
+ return d.toISOString().slice(0, 10) === date;
125
+ }
126
+ /** The id of the occurrence of series `iCalUid` on `date` (`YYYY-MM-DD`) — see the module note. */
127
+ export function occurrenceUid(iCalUid, date) {
128
+ if (!GOID.test(iCalUid))
129
+ throw new Error(`not a meeting id: ${JSON.stringify(iCalUid)}`);
130
+ if (!isOccurrenceDate(date))
131
+ throw new Error(`not a YYYY-MM-DD date: ${JSON.stringify(date)}`);
132
+ const [y, mo, d] = date.split('-').map(Number);
133
+ const hex = [y >> 8, y & 0xff, mo, d].map((b) => b.toString(16).padStart(2, '0')).join('').toUpperCase();
134
+ return iCalUid.slice(0, 32) + hex + iCalUid.slice(40);
135
+ }
136
+ /** The MCPS base for `TEAMS_MCPS_REGION` (default `us`). */
137
+ export function mcpsBase(env = process.env) {
138
+ const region = readEnvVar('TEAMS_MCPS_REGION', { env }) ?? DEFAULT_MCPS_REGION;
139
+ return `https://teams.cloud.microsoft/api/mcps/${encodeURIComponent(region)}`;
140
+ }
141
+ /** The collab-object read URL, built only from vetted parts. */
142
+ export function collabObjectUrl(base, meeting, uid, threadId) {
143
+ if (!GUID.test(meeting.organizerId) || !GUID.test(meeting.tenantId))
144
+ throw new Error('not a meeting organizer');
145
+ if (!GOID.test(uid))
146
+ throw new Error(`not a meeting id: ${JSON.stringify(uid)}`);
147
+ if (!THREAD_ID.test(threadId))
148
+ throw new Error(`not a meeting thread id: ${JSON.stringify(threadId)}`);
149
+ return `${base}/collab/readcollabobject/V2/${meeting.organizerId}@${meeting.tenantId}/${uid}/${threadId}`;
150
+ }
151
+ /** .NET ticks (100 ns since 0001-01-01, as a decimal string) as UTC ISO. */
152
+ export function ticksToIso(ticks) {
153
+ const s = str(ticks);
154
+ if (s === undefined || !/^\d{15,20}$/.test(s))
155
+ return undefined;
156
+ const ms = Number((BigInt(s) - EPOCH_TICKS) / 10000n);
157
+ return Number.isFinite(ms) && ms > 0 ? new Date(ms).toISOString() : undefined;
158
+ }
159
+ function hms(totalSeconds) {
160
+ const s = Math.floor(totalSeconds);
161
+ return `${Math.floor(s / 3600)}:${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
162
+ }
163
+ /** `00:06:17.5000000` → `0:06:17`. */
164
+ function timespan(v) {
165
+ const m = /^(\d+):(\d{2}):(\d{2})/.exec(str(v) ?? '');
166
+ return m ? hms(Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3])) : undefined;
167
+ }
168
+ /** The resources of a collab-object response, one per id. Never throws on shape. */
169
+ export function parseCollabObject(body) {
170
+ const list = obj(body)?.resources;
171
+ if (!Array.isArray(list))
172
+ return [];
173
+ const byId = new Map();
174
+ for (const raw of list) {
175
+ const r = obj(raw);
176
+ const id = str(r?.id);
177
+ const type = str(r?.type);
178
+ if (r === undefined || id === undefined || type === undefined || byId.has(id))
179
+ continue;
180
+ const location = str(r.location);
181
+ const added = isoOf(r.additionDateTime);
182
+ byId.set(id, {
183
+ id,
184
+ type,
185
+ ...(location !== undefined ? { location } : {}),
186
+ metadata: obj(r.metadata) ?? {},
187
+ ...(added !== undefined ? { added } : {}),
188
+ });
189
+ }
190
+ return [...byId.values()];
191
+ }
192
+ /** Drop the undefined fields of a flat record. */
193
+ function compact(o) {
194
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
195
+ }
196
+ /** Group a collab object's resources into the recap's sections. Links are passed on only when https. */
197
+ export function summarizeRecap(resources) {
198
+ const out = {
199
+ recordings: [],
200
+ transcripts: [],
201
+ notes: [],
202
+ attendance_reports: [],
203
+ files: [],
204
+ other: [],
205
+ };
206
+ for (const r of resources) {
207
+ const md = r.metadata;
208
+ switch (r.type) {
209
+ case 'Recording': {
210
+ const started = ticksToIso(md.startTime);
211
+ const ended = ticksToIso(md.endTime);
212
+ const duration = started && ended ? hms((Date.parse(ended) - Date.parse(started)) / 1000) : undefined;
213
+ out.recordings.push(compact({ started, ended, duration, url: httpsUrl(r.location) }));
214
+ break;
215
+ }
216
+ case 'TranscriptV2':
217
+ // Its location is a SharePoint API URL, not something a person opens; webUrl is the recording.
218
+ out.transcripts.push(compact({ started: ticksToIso(md.startTime), duration: timespan(md.duration), url: httpsUrl(md.webUrl) }));
219
+ break;
220
+ case 'transcript':
221
+ out.transcripts.push(compact({ started: isoOf(md.startTime), state: str(md.state) }));
222
+ break;
223
+ case 'notes':
224
+ out.notes.push(compact({ url: httpsUrl(r.location), added: r.added }));
225
+ break;
226
+ case 'AttendanceReport':
227
+ out.attendance_reports.push(compact({ started: ticksToIso(md.startTime), url: httpsUrl(md.webUrl) ?? httpsUrl(r.location) }));
228
+ break;
229
+ case 'MeetingChat':
230
+ case 'MeetingStage':
231
+ out.files.push(compact({
232
+ name: str(md.fileTitle),
233
+ file_type: str(md.fileType),
234
+ app: str(md.appTitle),
235
+ shared_in: r.type === 'MeetingChat' ? 'chat' : 'meeting',
236
+ url: httpsUrl(md.shareUrl) ?? httpsUrl(r.location),
237
+ added: r.added,
238
+ }));
239
+ break;
240
+ case 'AISummary':
241
+ out.ai_summary = compact({ exists: true, generated: r.added });
242
+ break;
243
+ default:
244
+ out.other.push(compact({ type: r.type, url: httpsUrl(r.location), added: r.added }));
245
+ }
246
+ }
247
+ return Object.fromEntries(Object.entries(out).filter(([, v]) => v !== undefined && (!Array.isArray(v) || v.length > 0)));
248
+ }
249
+ export class RecapClient {
250
+ #fetchImpl;
251
+ #base;
252
+ #configError = null;
253
+ #manager;
254
+ constructor(opts = {}) {
255
+ const env = opts.env ?? process.env;
256
+ // A receiver-safe wrapper, never the bare global (see `sharepoint.ts`).
257
+ this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
258
+ this.#base = mcpsBase(env);
259
+ this.#manager = createCapturedTokenManager({
260
+ capture: opts.captureToken ?? captureRecapTokenLazily,
261
+ persistence: createRecapTokenCache(env),
262
+ });
263
+ if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env })) {
264
+ this.#configError = new McpToolError('Meeting recaps are disabled (no token source).', {
265
+ kind: 'no_credential',
266
+ hint: 'Unset TEAMS_DISABLE_FETCHPROXY so a recap token can be captured from a signed-in Teams tab.',
267
+ });
268
+ }
269
+ }
270
+ isConfigured() {
271
+ return this.#configError === null;
272
+ }
273
+ async readCollabObject(meeting, uid, threadId) {
274
+ if (this.#configError)
275
+ throw this.#configError;
276
+ const url = collabObjectUrl(this.#base, meeting, uid, threadId);
277
+ let text = '';
278
+ const res = await this.#manager.withAuth(async (token) => {
279
+ let r;
280
+ try {
281
+ r = await fetchBounded(url, { method: 'GET', headers: { authorization: `Bearer ${token}`, accept: 'application/json' }, redirect: 'error' }, { read: 'text', maxBytes: MAX_RESPONSE_BYTES, service: 'Teams meeting recap', timeoutMs: REQUEST_TIMEOUT_MS, fetchImpl: this.#fetchImpl });
282
+ }
283
+ catch (e) {
284
+ throw describeTransportFailure(e, url, 'Teams meeting recap') ?? e;
285
+ }
286
+ text = r.body;
287
+ return r.res;
288
+ });
289
+ checkStatus(res.status);
290
+ try {
291
+ return parseCollabObject(JSON.parse(text));
292
+ }
293
+ catch {
294
+ // Never echo the body: it holds links to other people's files.
295
+ throw new McpToolError('The Teams meeting-recap service returned a response that is not JSON.', { status: res.status, kind: 'http' });
296
+ }
297
+ }
298
+ }
299
+ /** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
300
+ function checkStatus(status) {
301
+ if (status >= 200 && status < 300)
302
+ return;
303
+ if (status === 401) {
304
+ throw new McpToolError('The Teams meeting-recap service rejected the recap token (401) even after a fresh capture.', {
305
+ status,
306
+ kind: 'credential_rejected',
307
+ hint: "Open a meeting chat's Recap tab in a signed-in Teams tab to mint a fresh recap token, then retry.",
308
+ });
309
+ }
310
+ if (status === 403) {
311
+ throw new McpToolError("You are not allowed to read this meeting's recap (403).", { status, kind: 'http' });
312
+ }
313
+ if (status === 429) {
314
+ throw new McpToolError('The Teams meeting-recap service is rate-limiting requests (429).', {
315
+ status,
316
+ kind: 'http',
317
+ hint: 'Wait a minute before retrying.',
318
+ });
319
+ }
320
+ throw new McpToolError(`The Teams meeting-recap service returned HTTP ${status}.`, {
321
+ status,
322
+ kind: 'http',
323
+ ...(status >= 500 ? { hint: 'A Teams-side failure; retry shortly.' } : {}),
324
+ });
325
+ }
package/dist/rich.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * The structure of a Teams message body: sanitised HTML, its mentions and
3
+ * links, plain text and a Markdown rendering. Pure functions, no I/O.
4
+ *
5
+ * The parsing and rendering live in `@chrischall/mcp-utils/rich`; this module
6
+ * is the Teams layer over it: {@link TEAMS} keeps @mention spans (shown as
7
+ * `@name` in Markdown) and shows an emoji image as its character and any
8
+ * other inline image as `[image]` (its ref is in the attachments). Mentions'
9
+ * MRIs come from `properties.mentions` ({@link mentionsOf}).
10
+ */
11
+ import * as rich from '@chrischall/mcp-utils/rich';
12
+ export { attr, decodeEntities } from '@chrischall/mcp-utils/rich';
13
+ const MENTION_TYPE = 'http://schema.skype.com/Mention';
14
+ const EMOJI_TYPE = /schema\.skype\.com\/Emoji/i;
15
+ /** How Teams' own elements read: mention spans kept, emoji as their character, other images `[image]`. */
16
+ const TEAMS = {
17
+ element: (el, output, inner) => {
18
+ if (el.tag === 'img') {
19
+ const alt = rich.attr(el.attrs, 'alt');
20
+ const text = EMOJI_TYPE.test(rich.attr(el.attrs, 'itemtype') ?? '') && alt ? rich.decodeEntities(alt) : '[image]';
21
+ return output === 'html' ? rich.escapeHtml(text) : text;
22
+ }
23
+ if (el.tag === 'span' && rich.attr(el.attrs, 'itemtype') === MENTION_TYPE) {
24
+ if (output === 'markdown')
25
+ return `@${inner.trim()}`;
26
+ if (output === 'html') {
27
+ const id = rich.attr(el.attrs, 'itemid');
28
+ const itemid = id !== undefined && /^\d+$/.test(id) ? ` itemid="${id}"` : '';
29
+ return `<span itemtype="${MENTION_TYPE}"${itemid}>${inner}</span>`;
30
+ }
31
+ }
32
+ return undefined;
33
+ },
34
+ };
35
+ /**
36
+ * A message body reduced to the formatting Teams shows: paragraphs, line
37
+ * breaks, bold/italic/underline/strike, lists, links (http, https, mailto),
38
+ * inline code and code blocks, quotes, headings, tables and @mention spans.
39
+ * Every attribute but a link's href, a list's start and a mention's id is
40
+ * dropped; scripts, styles, comments and hidden content go with their
41
+ * content; any other tag goes but its text stays. Emoji become their
42
+ * character, other images `[image]`.
43
+ */
44
+ export function sanitiseHtml(html) {
45
+ return rich.sanitiseHtml(html, TEAMS);
46
+ }
47
+ /** True when `html` carries any formatting beyond paragraphs and line breaks. */
48
+ export function isRichHtml(html) {
49
+ return rich.isRichHtml(html, TEAMS);
50
+ }
51
+ /** Every http(s)/mailto link in a body with its shown text, in order, each pair once. */
52
+ export function linksOf(html) {
53
+ return rich.linksOf(html, TEAMS);
54
+ }
55
+ /**
56
+ * What a read shows of a body's structure, from one parse: its sanitised HTML
57
+ * when it carries formatting (`undefined` for a plain body, whose text says
58
+ * everything), and its links.
59
+ */
60
+ export function bodyStructure(html) {
61
+ return rich.bodyStructure(html, TEAMS);
62
+ }
63
+ /**
64
+ * A Teams message body as readable plain text. Links keep their target as
65
+ * `text (url)`, inline images become `[image]` (emoji become their character),
66
+ * a numbered list's items `1. `, `2. ` … and a bulleted one's `- `, a table
67
+ * row one line of ` | `-separated cells, and a quoted reply's lines are
68
+ * prefixed `> `. Never truncated: a long body comes back whole.
69
+ */
70
+ export function htmlToText(html) {
71
+ return rich.htmlToText(html, TEAMS);
72
+ }
73
+ /**
74
+ * A message body as Markdown: bold, italic, strike, inline code, fenced code
75
+ * blocks, numbered and bulleted lists (nested ones indented), links with
76
+ * their text, quotes, headings, tables, and mentions as `@name`.
77
+ */
78
+ export function htmlToMarkdown(html) {
79
+ return rich.htmlToMarkdown(html, TEAMS);
80
+ }
81
+ /**
82
+ * `properties.mentions` (a JSON string, or an already-parsed array) as
83
+ * `{ mri, displayName }`; entries without an MRI are skipped and anything
84
+ * unreadable yields none.
85
+ */
86
+ export function mentionsOf(raw) {
87
+ let parsed = raw;
88
+ if (typeof raw === 'string') {
89
+ try {
90
+ parsed = JSON.parse(raw);
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ }
96
+ if (!Array.isArray(parsed))
97
+ return [];
98
+ const out = [];
99
+ for (const e of parsed) {
100
+ if (e === null || typeof e !== 'object')
101
+ continue;
102
+ const { mri, displayName } = e;
103
+ if (typeof mri !== 'string' || mri === '')
104
+ continue;
105
+ out.push({ mri, displayName: typeof displayName === 'string' ? displayName : '' });
106
+ }
107
+ return out;
108
+ }
@@ -321,7 +321,10 @@ export function registerConversationTools(server, { chatsvc }) {
321
321
  description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
322
322
  'teams_list_conversations / teams_list_channels) or by name, without opening it in ' +
323
323
  'Teams. "48:notes" (or the name "notes" / "self") is the user\'s own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, ' +
324
- 'text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, ' +
324
+ 'text (never truncated; table cells separated by " | "; lists numbered or bulleted), subject, edited/deleted flags and attachments; ' +
325
+ 'a formatted message also carries content_html (its body as sanitised HTML: bold, lists, links, code, quotes, mentions), ' +
326
+ 'mentions ([{mri, displayName}], who was @mentioned) and links ([{href, text}]), each absent when there is none; ' +
327
+ 'a channel is returned as threads, ' +
325
328
  'each root post with its replies. A root older than the window is fetched and marked outside_window: ' +
326
329
  'true (it is context, not counted or cursored); up to ' +
327
330
  `${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is ` +
@@ -0,0 +1,72 @@
1
+ import { z } from 'zod';
2
+ import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, toolAnnotations, } from '@chrischall/mcp-utils';
3
+ import { htmlToText, isDeleted, normaliseMessage, SELF_CHAT } from '../model.js';
4
+ import { ownMessage, writeAndReadBack } from './own-message.js';
5
+ import { wrapApiError } from './errors.js';
6
+ import { resolveTarget } from './send.js';
7
+ import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
8
+ import { workMeta } from './hints.js';
9
+ const TOOL = 'teams_delete_message';
10
+ export function registerDeleteTools(server, { chatsvc }) {
11
+ server.registerTool(TOOL, {
12
+ title: 'Delete a Teams message',
13
+ description: 'Delete one of your own messages in any chat or channel. conversation is an id or name as for ' +
14
+ 'teams_list_messages; message_id comes from teams_list_messages and must be a message you sent ' +
15
+ "(someone else's or a system event is refused). One already deleted is reported as status " +
16
+ '"already_deleted" with nothing asked or sent. Everyone in the conversation sees that the message was ' +
17
+ 'deleted, and this MCP cannot bring it back. The result says whether reading the message back shows it ' +
18
+ 'deleted (verified); status "unknown" means Teams did not confirm it and the read-back did not show it ' +
19
+ `deleted — check before retrying. conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own ` +
20
+ 'notes self-chat — use it to try this tool. ' +
21
+ CONFIRM_FLOW_SENTENCE +
22
+ ' The preview shows the conversation and the message that will be deleted. ' +
23
+ CONFIRM_INJECTION_RULE +
24
+ UNTRUSTED_DESCRIPTION_SUFFIX,
25
+ annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: true, openWorld: true }),
26
+ _meta: workMeta('change', { aliases: ['delete', 'delete message', 'remove message', 'unsend', 'take back'] }),
27
+ inputSchema: {
28
+ conversation: z
29
+ .string()
30
+ .min(1)
31
+ .describe(`The conversation id (or "${SELF_CHAT}" — also by the name "notes" or "self" — for the self-chat), ` +
32
+ "or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names."),
33
+ message_id: z.string().min(1).describe('The message to delete — one you sent — as teams_list_messages lists it.'),
34
+ confirmToken: confirmTokenParam,
35
+ },
36
+ }, async ({ conversation, message_id, confirmToken }, ctx) => {
37
+ try {
38
+ const me = await chatsvc.meMri();
39
+ const target = await resolveTarget(chatsvc, conversation, me, 'delete a message in');
40
+ const m = await ownMessage(chatsvc, target.id, message_id, me, 'delete');
41
+ if (isDeleted(m)) {
42
+ return untrustedResult({ status: 'already_deleted', conversation: target, message_id });
43
+ }
44
+ const path = `/users/ME/conversations/${encodeURIComponent(target.id)}/messages/${encodeURIComponent(message_id)}`;
45
+ const gate = await confirmWrite(ctx, {
46
+ tool: TOOL,
47
+ action: 'chat.delete_message',
48
+ message: 'Review and confirm before this Teams message of yours is deleted:',
49
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
50
+ summary: `Delete your message ${message_id} in ${target.kind} ${JSON.stringify(target.title)}`,
51
+ account: me,
52
+ target: `${target.id}/${message_id}`,
53
+ request: { method: 'DELETE', path },
54
+ preview: {
55
+ conversation: untrustedField(target),
56
+ message_id,
57
+ time: normaliseMessage(m, me).time,
58
+ // The user's own text, but a quote-reply's quote is someone else's.
59
+ text: untrustedField(htmlToText(m.content ?? '')),
60
+ },
61
+ confirmToken,
62
+ });
63
+ if (gate)
64
+ return gate;
65
+ const { status, ...settled } = await writeAndReadBack(() => chatsvc.deleteMessage(target.id, message_id), () => chatsvc.getMessage(target.id, message_id), (back) => back === undefined || isDeleted(back), 'delete', 'it deleted');
66
+ return untrustedResult({ status: status === 'done' ? 'deleted' : 'unknown', conversation: target, message_id, ...settled });
67
+ }
68
+ catch (err) {
69
+ throw wrapApiError(err, 'delete the message');
70
+ }
71
+ });
72
+ }
@@ -0,0 +1,131 @@
1
+ import { z } from 'zod';
2
+ import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, McpToolError, toolAnnotations, } from '@chrischall/mcp-utils';
3
+ import { mentionsProperty, renderMessageHtml } from '../compose.js';
4
+ import { htmlToText, isDeleted, SELF_CHAT } from '../model.js';
5
+ import { mentionsOf, sanitiseHtml } from '../rich.js';
6
+ import { ownMessage, writeAndReadBack } from './own-message.js';
7
+ import { wrapApiError } from './errors.js';
8
+ import { formatParam, mentionArg, resolveMentions, resolveTarget } from './send.js';
9
+ import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
10
+ import { workMeta } from './hints.js';
11
+ const TOOL = 'teams_edit_message';
12
+ /** A quote-reply's quote block, as Teams (and `compose.quoteHtml`) put it at the start of the body. */
13
+ const QUOTE_BLOCK = /^\s*(<blockquote\b[^>]*schema\.skype\.com\/Reply[^>]*>[\s\S]*?<\/blockquote\s*>)/i;
14
+ /** The quote block a quote-reply starts with, kept through an edit; `''` for none. */
15
+ export function quotePrefix(content) {
16
+ return QUOTE_BLOCK.exec(content)?.[1] ?? '';
17
+ }
18
+ /** Whether `m` reads as the edit: its text is the text of `content`. */
19
+ const readsAs = (m, content) => m !== undefined && htmlToText(m.content ?? '') === htmlToText(content);
20
+ /** A block-level tag, open or close: whitespace beside one never shows. */
21
+ const BLOCK_TAG = /\s*(<\/?(?:p|div|ol|ul|li|pre|blockquote|table|thead|tbody|tr|td|th|h[1-6])>)\s*/g;
22
+ /**
23
+ * Whether two bodies are the same message: Teams stores what it is sent with
24
+ * `\r\n` around block elements (between them, and between an item's text and
25
+ * a list nested in it), so compare them sanitised, without the whitespace
26
+ * beside block tags.
27
+ */
28
+ export function sameBody(a, b) {
29
+ const norm = (h) => sanitiseHtml(h).replace(BLOCK_TAG, '$1').trim();
30
+ return norm(a) === norm(b);
31
+ }
32
+ export function registerEditTools(server, { chatsvc }) {
33
+ server.registerTool(TOOL, {
34
+ title: 'Edit a Teams message',
35
+ description: 'Replace the text of one of your own messages in any chat or channel. conversation is an id or name as ' +
36
+ 'for teams_list_messages; message_id comes from teams_list_messages and must be a message you sent ' +
37
+ "(someone else's, a deleted one or a system event is refused). text replaces the whole message: plain " +
38
+ 'text by default, or Markdown with format "markdown" (as teams_send_message reads it). mentions ' +
39
+ '@-mention people as in teams_send_message. A quote-reply keeps its quote. Text that renders exactly as ' +
40
+ 'the message already does, mentioning the same people, changes nothing (status "unchanged"). Everyone in the conversation sees the ' +
41
+ 'message marked edited. The result says whether reading the message back shows the edit (verified); ' +
42
+ 'status "unknown" means Teams did not confirm it and the read-back did not show it — check the message ' +
43
+ `before retrying. conversation "${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — ` +
44
+ 'use it to try this tool. ' +
45
+ CONFIRM_FLOW_SENTENCE +
46
+ ' The preview shows the conversation, the current text, the new text and exactly what will replace it. ' +
47
+ CONFIRM_INJECTION_RULE +
48
+ UNTRUSTED_DESCRIPTION_SUFFIX,
49
+ annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: true, openWorld: true }),
50
+ _meta: workMeta('change', { aliases: ['edit', 'edit message', 'fix my message', 'correct', 'reword', 'update message'] }),
51
+ inputSchema: {
52
+ conversation: z
53
+ .string()
54
+ .min(1)
55
+ .describe(`The conversation id (or "${SELF_CHAT}" — also by the name "notes" or "self" — for the self-chat), ` +
56
+ "or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names."),
57
+ message_id: z.string().min(1).describe('The message to edit — one you sent — as teams_list_messages lists it.'),
58
+ text: z
59
+ .string()
60
+ .min(1)
61
+ .describe('The whole new message: plain text (newlines kept, :key: shortcodes become emoji), or Markdown with format "markdown".'),
62
+ format: formatParam,
63
+ mentions: z.array(mentionArg).max(20).optional().describe('People to @-mention in text.'),
64
+ confirmToken: confirmTokenParam,
65
+ },
66
+ }, async ({ conversation, message_id, text, format = 'text', mentions, confirmToken }, ctx) => {
67
+ try {
68
+ const me = await chatsvc.meMri();
69
+ const target = await resolveTarget(chatsvc, conversation, me, 'edit a message in');
70
+ const original = await ownMessage(chatsvc, target.id, message_id, me, 'edit');
71
+ if (isDeleted(original)) {
72
+ throw new McpToolError(`Message ${message_id} has been deleted, so it cannot be edited.`, {
73
+ hint: 'Send a new message instead (teams_send_message).',
74
+ });
75
+ }
76
+ const before = original.content ?? '';
77
+ const people = await resolveMentions(chatsvc, target.id, mentions ?? []);
78
+ const rendered = renderMessageHtml(text, people.map((p) => p.target), format);
79
+ const content = quotePrefix(before) + rendered.html;
80
+ // A mention span names only who it shows, so the people are compared too.
81
+ const mentionedNow = rendered.mentions.map((m) => m.mri.toLowerCase());
82
+ const mentionedBefore = mentionsOf(original.properties?.mentions).map((m) => m.mri.toLowerCase());
83
+ if (sameBody(content, before) && mentionedNow.join('\n') === mentionedBefore.join('\n')) {
84
+ return untrustedResult({ status: 'unchanged', conversation: target, message_id });
85
+ }
86
+ const qtdMsgs = original.properties?.qtdMsgs;
87
+ const body = {
88
+ content,
89
+ messagetype: 'RichText/Html',
90
+ contenttype: 'text',
91
+ amsreferences: [],
92
+ properties: {
93
+ mentions: rendered.mentions.length > 0 ? mentionsProperty(rendered.mentions) : '[]',
94
+ ...(typeof qtdMsgs === 'string' && quotePrefix(before) !== '' ? { qtdMsgs } : {}),
95
+ },
96
+ };
97
+ const path = `/users/ME/conversations/${encodeURIComponent(target.id)}/messages/${encodeURIComponent(message_id)}`;
98
+ const gate = await confirmWrite(ctx, {
99
+ tool: TOOL,
100
+ action: 'chat.edit_message',
101
+ message: 'Review and confirm this edit before it replaces your Teams message:',
102
+ // The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
103
+ summary: `Edit your message ${message_id} in ${target.kind} ${JSON.stringify(target.title)}`,
104
+ account: me,
105
+ target: `${target.id}/${message_id}`,
106
+ request: { method: 'PUT', path, body },
107
+ preview: {
108
+ conversation: untrustedField(target),
109
+ message_id,
110
+ // The user's own text, but a quote-reply's quote is someone else's.
111
+ current_text: untrustedField(htmlToText(before)),
112
+ text,
113
+ format,
114
+ ...(people.length > 0
115
+ ? {
116
+ mentions: untrustedField(people.map((p, i) => ({ name_in_text: mentions[i].name_in_text, person: p.person, mri: p.target.mri }))),
117
+ }
118
+ : {}),
119
+ },
120
+ confirmToken,
121
+ });
122
+ if (gate)
123
+ return gate;
124
+ const { status, ...settled } = await writeAndReadBack(() => chatsvc.editMessage(target.id, message_id, body), () => chatsvc.getMessage(target.id, message_id), (m) => readsAs(m, content), 'edit', 'the new text');
125
+ return untrustedResult({ status: status === 'done' ? 'edited' : 'unknown', conversation: target, message_id, ...settled });
126
+ }
127
+ catch (err) {
128
+ throw wrapApiError(err, 'edit the message');
129
+ }
130
+ });
131
+ }