@chrischall/microsoft-teams-mcp 0.11.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/chatsvc.js CHANGED
@@ -108,6 +108,8 @@ function outcomeUnknown(method, e, hint) {
108
108
  }
109
109
  const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_list_messages) before retrying; do not resend blindly.';
110
110
  const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_list_messages) before retrying.';
111
+ const EDIT_OUTCOME_HINT = 'The edit may already have been applied — read the message (teams_list_messages) before retrying.';
112
+ const DELETE_OUTCOME_HINT = 'The message may already have been deleted — read the conversation (teams_list_messages) before retrying.';
111
113
  const THREAD_OUTCOME_HINT = 'The change to the chat may already have been applied — check the chat (its name and members) before retrying.';
112
114
  const CREATE_OUTCOME_HINT = 'A chat may already have been created — check teams_list_conversations before retrying; a blind retry ' +
113
115
  'would create a second chat (and a chat cannot be deleted).';
@@ -321,6 +323,34 @@ export class ChatServiceClient {
321
323
  const id = /\/messages\/([^/?#]+)\/?(?:[?#].*)?$/.exec(headers.get('location') ?? '')?.[1];
322
324
  return id !== undefined ? { id: decodeURIComponent(id) } : {};
323
325
  }
326
+ /**
327
+ * Replace one of the user's own messages: `PUT …/messages/{id}` with the
328
+ * new body (`teams_edit_message` builds it). An edit is idempotent, but a
329
+ * request that was sent and got no usable answer is still a
330
+ * `WriteOutcomeUnknownError`, so the tool reads the message back rather
331
+ * than report a plain failure for a change that may have landed.
332
+ */
333
+ async editMessage(conversationId, messageId, body) {
334
+ this.#requireConfigured();
335
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
336
+ `/messages/${encodeURIComponent(messageId)}`;
337
+ const { status } = await this.#send(url, 'text', undefined, { method: 'PUT', body, hint: EDIT_OUTCOME_HINT });
338
+ this.#checkWriteStatus('PUT', status, EDIT_OUTCOME_HINT);
339
+ }
340
+ /**
341
+ * Delete one of the user's own messages: `DELETE …/messages/{id}`. Teams
342
+ * keeps a deleted message in the conversation with `properties.deletetime`
343
+ * set and no content. Deleting twice leaves it deleted, but a request that
344
+ * was sent and got no usable answer is still a `WriteOutcomeUnknownError`,
345
+ * so the tool reads the message back to settle it.
346
+ */
347
+ async deleteMessage(conversationId, messageId) {
348
+ this.#requireConfigured();
349
+ const url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(conversationId)}` +
350
+ `/messages/${encodeURIComponent(messageId)}`;
351
+ const { status } = await this.#send(url, 'text', undefined, { method: 'DELETE', hint: DELETE_OUTCOME_HINT });
352
+ this.#checkWriteStatus('DELETE', status, DELETE_OUTCOME_HINT);
353
+ }
324
354
  /**
325
355
  * React to a message: `PUT …/messages/{id}/properties?name=emotions` with
326
356
  * `{ emotions: { key, value: <epoch ms> } }` (captured live). Only the
package/dist/compose.js CHANGED
@@ -6,25 +6,21 @@
6
6
  * markup, which follows the documented Skype format and is NOT yet captured
7
7
  * live. The caller's text is always escaped: the only markup a message can
8
8
  * carry is what these builders emit (paragraph, line breaks, mention spans,
9
- * emoji spans, the quote block), so a caller cannot smuggle HTML into a post.
9
+ * emoji spans, the quote block) and, for `markdown` text, what the Markdown
10
+ * renderer in `@chrischall/mcp-utils/rich` emits, so a caller cannot smuggle
11
+ * HTML into a post.
10
12
  */
11
13
  import { randomInt } from 'node:crypto';
12
14
  import { McpToolError } from '@chrischall/mcp-utils';
13
- const HTML_ESCAPES = {
14
- '&': '&amp;',
15
- '<': '&lt;',
16
- '>': '&gt;',
17
- '"': '&quot;',
18
- "'": '&#39;',
19
- };
20
- export function escapeHtml(s) {
21
- return s.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
22
- }
15
+ import { escapeHtml, renderMarkdown } from '@chrischall/mcp-utils/rich';
16
+ /** `s` safe as HTML text or inside a quoted attribute (`'` → `&#39;`). */
17
+ export { escapeHtml };
23
18
  /**
24
- * Teams' short legacy emoji keys this module can render, with the title Teams
25
- * shows and the character used as the `alt` fallback. The keys are the
26
- * observed ones; the titles and characters are best-effort (they only affect
27
- * hover text and copy-paste, never which emoji renders).
19
+ * Teams' short legacy emoji keys, rendered as Teams' own animated emoji span,
20
+ * with the title Teams shows and the character used as the `alt` fallback.
21
+ * The keys are the observed ones, and each has an image on Teams' emoji CDN
22
+ * (all 12 checked 2026-11-11); the titles and characters only affect hover
23
+ * text and copy-paste.
28
24
  */
29
25
  const NAMED_EMOJI = {
30
26
  like: { title: 'Like', char: '👍' },
@@ -40,41 +36,104 @@ const NAMED_EMOJI = {
40
36
  fire: { title: 'Fire', char: '🔥' },
41
37
  party: { title: 'Party', char: '🎉' },
42
38
  };
39
+ /**
40
+ * Common shortcode names (the GitHub/Slack spellings) sent as the plain
41
+ * character, which Teams always shows — unlike an image span, whose image
42
+ * Teams may not have.
43
+ */
44
+ const PLAIN_EMOJI = {
45
+ rocket: '🚀',
46
+ tada: '🎉',
47
+ thumbsup: '👍',
48
+ thumbsdown: '👎',
49
+ clap: '👏',
50
+ raised_hands: '🙌',
51
+ pray: '🙏',
52
+ muscle: '💪',
53
+ wave: '👋',
54
+ eyes: '👀',
55
+ thinking: '🤔',
56
+ joy: '😂',
57
+ sweat_smile: '😅',
58
+ grin: '😁',
59
+ slightly_smiling_face: '🙂',
60
+ upside_down: '🙃',
61
+ shrug: '🤷',
62
+ facepalm: '🤦',
63
+ white_check_mark: '✅',
64
+ heavy_check_mark: '✔️',
65
+ x: '❌',
66
+ warning: '⚠️',
67
+ bangbang: '‼️',
68
+ question: '❓',
69
+ bulb: '💡',
70
+ star: '⭐',
71
+ sparkles: '✨',
72
+ zap: '⚡',
73
+ boom: '💥',
74
+ '100': '💯',
75
+ robot: '🤖',
76
+ brain: '🧠',
77
+ coffee: '☕',
78
+ chart_with_upwards_trend: '📈',
79
+ chart_with_downwards_trend: '📉',
80
+ memo: '📝',
81
+ calendar: '📅',
82
+ lock: '🔒',
83
+ bug: '🐛',
84
+ wrench: '🔧',
85
+ hammer: '🔨',
86
+ package: '📦',
87
+ ship: '🚢',
88
+ hourglass: '⌛',
89
+ stopwatch: '⏱️',
90
+ point_right: '👉',
91
+ point_up: '☝️',
92
+ ok_hand: '👌',
93
+ crossed_fingers: '🤞',
94
+ see_no_evil: '🙈',
95
+ skull: '💀',
96
+ partying_face: '🥳',
97
+ exploding_head: '🤯',
98
+ mind_blown: '🤯',
99
+ };
43
100
  /**
44
101
  * A unicode-style key: lowercase hex code point(s), `_`, the character's name
45
- * squashed to `[a-z0-9]` (`1f389_partypopper`). Multi-code-point keys are
46
- * assumed `-`-joined — unverified, so such a key at worst renders as Teams'
47
- * missing-emoji image.
102
+ * squashed to `[a-z0-9]` (`1f389_partypopper`); a multi-code-point key is
103
+ * `-`-joined.
48
104
  */
49
105
  const UNICODE_KEY = /^([0-9a-f]{4,6}(?:-[0-9a-f]{4,6})*)_([a-z0-9]+)$/;
50
106
  /**
51
- * The captured inline-emoji span for `key`, or `undefined` when the key is
52
- * neither a known short name nor unicode-style — the caller then leaves the
53
- * `:key:` as plain text (so "10:30:45" is never mangled).
107
+ * The HTML for the `:key:` shortcode, or `undefined` when the key is none
108
+ * this module knows — the caller then leaves the `:key:` as plain text (so
109
+ * "10:30:45" is never mangled).
110
+ *
111
+ * A built-in name ({@link NAMED_EMOJI}) is Teams' animated emoji span. A
112
+ * common name ({@link PLAIN_EMOJI}) or a unicode-style key is the plain
113
+ * character: Teams' emoji CDN has no image for many code points (live
114
+ * 2026-11-11, `1f680_rocket` is a 404 and showed as a broken image), and a
115
+ * plain character always shows.
54
116
  */
55
- export function emojiSpan(key) {
56
- let title;
57
- let char;
117
+ export function emojiHtml(key) {
58
118
  const named = NAMED_EMOJI[key];
59
119
  if (named !== undefined) {
60
- ({ title, char } = named);
120
+ const t = escapeHtml(named.title);
121
+ // `key` is one of the names above, so it is safe in a URL and attribute.
122
+ return (`<span contenteditable="false" title="${t}" type="(${key})" class="animated-emoticon-20-${key}" itemscope>` +
123
+ `<img itemscope itemtype="http://schema.skype.com/Emoji" itemid="${key}" ` +
124
+ `src="https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/${key}/default/20_f.png" ` +
125
+ `title="${t}" alt="${escapeHtml(named.char)}" style="width:20px;height:20px;"></span>`);
61
126
  }
62
- else {
63
- const m = UNICODE_KEY.exec(key);
64
- if (m === null)
65
- return undefined;
66
- const points = m[1].split('-').map((h) => parseInt(h, 16));
67
- if (points.some((p) => p > 0x10ffff))
68
- return undefined;
69
- char = String.fromCodePoint(...points);
70
- title = m[2];
71
- }
72
- // `key` is [a-z0-9_-] by construction here, so it is safe in a URL and attribute.
73
- const t = escapeHtml(title);
74
- return (`<span contenteditable="false" title="${t}" type="(${key})" class="animated-emoticon-20-${key}" itemscope>` +
75
- `<img itemscope itemtype="http://schema.skype.com/Emoji" itemid="${key}" ` +
76
- `src="https://statics.teams.cdn.office.net/evergreen-assets/personal-expressions/v2/assets/emoticons/${key}/default/20_f.png" ` +
77
- `title="${t}" alt="${escapeHtml(char)}" style="width:20px;height:20px;"></span>`);
127
+ const plain = Object.hasOwn(PLAIN_EMOJI, key) ? PLAIN_EMOJI[key] : undefined;
128
+ if (plain !== undefined)
129
+ return plain;
130
+ const m = UNICODE_KEY.exec(key);
131
+ if (m === null)
132
+ return undefined;
133
+ const points = m[1].split('-').map((h) => parseInt(h, 16));
134
+ if (points.some((p) => p > 0x10ffff))
135
+ return undefined;
136
+ return escapeHtml(String.fromCodePoint(...points));
78
137
  }
79
138
  /**
80
139
  * Plain text → escaped HTML, newlines as `<br>`, known `:key:` shortcodes as
@@ -86,7 +145,7 @@ function renderPlain(text) {
86
145
  let at = 0;
87
146
  const shortcode = /:([a-z0-9_-]+):/g;
88
147
  for (let m = shortcode.exec(text); m !== null; m = shortcode.exec(text)) {
89
- const span = emojiSpan(m[1]);
148
+ const span = emojiHtml(m[1]);
90
149
  if (span === undefined) {
91
150
  shortcode.lastIndex = m.index + m[0].length - 1;
92
151
  continue;
@@ -121,11 +180,16 @@ function locate(text, name, taken) {
121
180
  return find(`@${name}`, false, false) ?? find(`@${name}`, true, false) ?? find(name, true, true);
122
181
  }
123
182
  /**
124
- * The message body as Teams HTML: one paragraph of escaped text, with each
125
- * mention's first free occurrence (`@name`, else `name`) replaced by a mention
126
- * span. Mentions are numbered 0, 1, … in order of appearance in the text.
183
+ * How a message's text is written: plain text, or Markdown — the subset
184
+ * `renderMarkdown` in `@chrischall/mcp-utils/rich` reads: paragraphs (a blank
185
+ * line between them; a single newline is a line break), **bold**, *italic*,
186
+ * ~~strike~~, `inline code`, fenced code blocks, nested bulleted and numbered
187
+ * lists, [links](https://…) with their text, and :key: emoji. Anything else —
188
+ * raw HTML, headings, quotes, images — is escaped and shown as written.
127
189
  */
128
- export function renderMessageHtml(text, mentions) {
190
+ export const MESSAGE_FORMATS = ['text', 'markdown'];
191
+ /** Each mention's first free occurrence in `text`, in order of appearance. */
192
+ function placeMentions(text, mentions) {
129
193
  const placed = [];
130
194
  for (const m of mentions) {
131
195
  const range = locate(text, m.text, placed.map((p) => [p.start, p.end]));
@@ -136,15 +200,50 @@ export function renderMessageHtml(text, mentions) {
136
200
  }
137
201
  placed.push({ start: range[0], end: range[1], mri: m.mri });
138
202
  }
139
- placed.sort((a, b) => a.start - b.start);
203
+ return placed.sort((a, b) => a.start - b.start);
204
+ }
205
+ const mentionSpan = (n, shown) => `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown)}</span>`;
206
+ /*
207
+ * Private-use placeholders for a mention (MENTION_OPEN n MENTION_CLOSE),
208
+ * carried through the Markdown renderer as ordinary text. They sit above the
209
+ * renderer's own reserved range (U+E000–U+E00F, which it strips), and the
210
+ * caller's text has U+E010–U+E01F stripped first, so it cannot forge one.
211
+ */
212
+ const MENTION_OPEN = '\ue010';
213
+ const MENTION_CLOSE = '\ue011';
214
+ const PLACEHOLDER_CHARS = /[\ue010-\ue01f]/g;
215
+ /**
216
+ * The message body as Teams HTML, with each mention's first free occurrence
217
+ * (`@name`, else `name`) replaced by a mention span. Mentions are numbered
218
+ * 0, 1, … in order of appearance in the text.
219
+ *
220
+ * `text` format: one paragraph of escaped text, newlines as `<br>`.
221
+ * `markdown` format: the subset described at {@link MESSAGE_FORMATS}.
222
+ */
223
+ export function renderMessageHtml(text, mentions, format = 'text') {
224
+ const placed = placeMentions(text, mentions);
225
+ const out = placed.map((p, n) => ({
226
+ itemid: String(n),
227
+ mri: p.mri,
228
+ displayName: text.slice(p.start, p.end).replace(/^@/, ''),
229
+ }));
230
+ if (format === 'markdown') {
231
+ let src = '';
232
+ let at = 0;
233
+ const clean = (s) => s.replace(PLACEHOLDER_CHARS, '');
234
+ placed.forEach((p, n) => {
235
+ src += clean(text.slice(at, p.start)) + `${MENTION_OPEN}${n}${MENTION_CLOSE}`;
236
+ at = p.end;
237
+ });
238
+ src += clean(text.slice(at));
239
+ const html = renderMarkdown(src, { shortcode: emojiHtml }).replace(new RegExp(`${MENTION_OPEN}(\\d+)${MENTION_CLOSE}`, 'g'), (_w, n) => mentionSpan(Number(n), out[Number(n)].displayName));
240
+ return { html, mentions: out };
241
+ }
140
242
  let html = '';
141
243
  let at = 0;
142
- const out = [];
143
244
  placed.forEach((p, n) => {
144
- const shown = text.slice(p.start, p.end).replace(/^@/, '');
145
245
  html += renderPlain(text.slice(at, p.start));
146
- html += `<span itemscope itemtype="http://schema.skype.com/Mention" itemid="${n}">${escapeHtml(shown)}</span>`;
147
- out.push({ itemid: String(n), mri: p.mri, displayName: shown });
246
+ html += mentionSpan(n, out[n].displayName);
148
247
  at = p.end;
149
248
  });
150
249
  html += renderPlain(text.slice(at));
package/dist/index.js CHANGED
@@ -13,6 +13,8 @@ import { registerChangesTools } from './tools/changes.js';
13
13
  import { registerAttachmentTools } from './tools/attachment.js';
14
14
  import { registerSendTools } from './tools/send.js';
15
15
  import { registerReactTools } from './tools/react.js';
16
+ import { registerEditTools } from './tools/edit.js';
17
+ import { registerDeleteTools } from './tools/delete.js';
16
18
  import { registerMarkReadTools } from './tools/markread.js';
17
19
  import { registerGroupChatTools } from './tools/group-chat.js';
18
20
  import { registerActivityTools } from './tools/activity.js';
@@ -51,6 +53,8 @@ await runMcp({
51
53
  registerChangesTools,
52
54
  registerAttachmentTools,
53
55
  registerSendTools,
56
+ registerEditTools,
57
+ registerDeleteTools,
54
58
  registerReactTools,
55
59
  registerMarkReadTools,
56
60
  registerGroupChatTools,
package/dist/model.js CHANGED
@@ -1,3 +1,6 @@
1
+ import { attr, bodyStructure, decodeEntities, htmlToText, mentionsOf } from './rich.js';
2
+ // The text of a body is rich.ts's to read; kept importable from here, where every reader looks.
3
+ export { decodeEntities, htmlToText };
1
4
  /**
2
5
  * The user's own notes chat ("notes to self") — the one `48:*` system
3
6
  * conversation that is a real chat. Every other `48:*` id (calendar,
@@ -67,7 +70,8 @@ export function senderMri(from) {
67
70
  export function isUserMessage(m) {
68
71
  return USER_MESSAGE_TYPES.has(m.messagetype ?? '');
69
72
  }
70
- function isDeleted(m) {
73
+ /** True when Teams has deleted the message (it keeps it, with `deletetime` set). */
74
+ export function isDeleted(m) {
71
75
  const t = m.properties?.deletetime;
72
76
  return t !== undefined && t !== null && t !== '' && t !== 0;
73
77
  }
@@ -274,95 +278,6 @@ export function conversationSummary(c, meMri, all = []) {
274
278
  function truncate(s, max) {
275
279
  return s.length <= max ? s : `${s.slice(0, max - 1)}…`;
276
280
  }
277
- /*
278
- * Placeholders that survive tag-stripping, so blockquote depth can be applied
279
- * after the text is decoded. Control characters never come out of entity
280
- * decoding (it drops them), so a message cannot forge one.
281
- */
282
- const QUOTE_OPEN = '\u0001';
283
- const QUOTE_CLOSE = '\u0002';
284
- const NAMED_ENTITIES = {
285
- amp: '&',
286
- lt: '<',
287
- gt: '>',
288
- quot: '"',
289
- apos: "'",
290
- nbsp: ' ',
291
- };
292
- export function decodeEntities(s) {
293
- // One pass, so `&amp;lt;` becomes `&lt;` and not `<`.
294
- return s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (whole, dec, hex, name) => {
295
- if (name !== undefined)
296
- return NAMED_ENTITIES[name.toLowerCase()] ?? whole;
297
- const code = dec !== undefined ? Number(dec) : parseInt(hex, 16);
298
- if (!Number.isFinite(code) || code > 0x10ffff)
299
- return whole;
300
- // Drop control characters (keeping tab/newline): they carry no text and
301
- // would collide with the quote placeholders.
302
- if (code < 0x20 && code !== 0x09 && code !== 0x0a)
303
- return '';
304
- return String.fromCodePoint(code);
305
- });
306
- }
307
- function attr(tag, name) {
308
- const m = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(tag);
309
- return m ? (m[1] ?? m[2]) : undefined;
310
- }
311
- const stripTags = (s) => s.replace(/<\/?[a-z!][^>]*>/gi, '');
312
- /**
313
- * One table row on one line, its `<td>`/`<th>` cells joined by ` | ` — a
314
- * pasted table (a file-monitor report, a status grid) otherwise runs its cells
315
- * together. Line breaks inside a cell become spaces so the row stays whole.
316
- */
317
- function tableRow(row) {
318
- const cells = [...row.matchAll(/<t[dh]\b[^>]*>([\s\S]*?)(?:<\/t[dh]\s*>|(?=<t[dh]\b)|$)/gi)].map(([, cell]) => cell
319
- .replace(/[\u0001\u0002]/g, '')
320
- .replace(/<br\s*\/?>|<\/?(p|div|li|h[1-6])\b[^>]*>|\r?\n/gi, ' ')
321
- .trim());
322
- return cells.length > 0 ? cells.join(' | ') : row;
323
- }
324
- /**
325
- * A Teams message body as readable plain text. Links keep their target as
326
- * `text (url)`, inline images become `[image]` (emoji become their alt text),
327
- * a table row becomes one line of ` | `-separated cells, and a quoted reply's
328
- * lines are prefixed `> `. Never truncated: a long body comes back whole. No
329
- * HTML library: Teams bodies are a small, regular subset.
330
- */
331
- export function htmlToText(html) {
332
- let s = html.replace(/[\u0001\u0002]/g, '');
333
- s = s.replace(/<(script|style)\b[\s\S]*?<\/\1\s*>/gi, '');
334
- s = s.replace(/<blockquote\b[^>]*>/gi, `\n${QUOTE_OPEN}\n`).replace(/<\/blockquote\s*>/gi, `\n${QUOTE_CLOSE}\n`);
335
- s = s.replace(/<img\b[^>]*>/gi, (tag) => {
336
- const alt = attr(tag, 'alt');
337
- return /schema\.skype\.com\/Emoji/i.test(attr(tag, 'itemtype') ?? '') && alt ? alt : '[image]';
338
- });
339
- s = s.replace(/<a\b([^>]*)>([\s\S]*?)<\/a\s*>/gi, (_whole, attrs, inner) => {
340
- const href = attr(` ${attrs}`, 'href');
341
- const label = stripTags(inner).trim();
342
- if (!href)
343
- return inner;
344
- if (label === '' || label === href)
345
- return href;
346
- return `${inner} (${href})`;
347
- });
348
- s = s.replace(/<tr\b[^>]*>([\s\S]*?)<\/tr\s*>/gi, (_whole, row) => `\n${tableRow(row)}\n`);
349
- // Block elements start and end a line (a quote's author <strong> runs
350
- // straight into its <p> otherwise); the blank lines this makes collapse below.
351
- s = s.replace(/<br\s*\/?>/gi, '\n').replace(/<\/?(p|div|li|tr|h[1-6])\b[^>]*>/gi, '\n');
352
- s = decodeEntities(stripTags(s));
353
- const out = [];
354
- let depth = 0;
355
- for (const raw of s.split(/\r?\n/)) {
356
- const line = raw.replace(/[ \t ]+/g, ' ').trim();
357
- if (line === QUOTE_OPEN)
358
- depth++;
359
- else if (line === QUOTE_CLOSE)
360
- depth = Math.max(0, depth - 1);
361
- else if (line !== '')
362
- out.push(`${'> '.repeat(depth)}${line}`);
363
- }
364
- return out.join('\n');
365
- }
366
281
  function fileAttachments(raw) {
367
282
  let parsed = raw;
368
283
  if (typeof raw === 'string') {
@@ -534,6 +449,9 @@ export function normaliseMessage(m, meMri, opts = {}) {
534
449
  const content = m.content ?? '';
535
450
  const reactions = reactionsOf(props.emotions, meMri);
536
451
  const timeLocal = opts.timeZone !== undefined ? localIsoTime(time, opts.timeZone) : undefined;
452
+ const deleted = isDeleted(m);
453
+ const { contentHtml, links } = deleted ? { links: [] } : bodyStructure(content);
454
+ const mentions = deleted ? [] : mentionsOf(props.mentions);
537
455
  return {
538
456
  id: m.id,
539
457
  time,
@@ -541,10 +459,13 @@ export function normaliseMessage(m, meMri, opts = {}) {
541
459
  sender: nonEmpty(m.imdisplayname) ?? mri ?? 'unknown',
542
460
  fromMe: mri !== undefined && mri === meMri,
543
461
  text: htmlToText(content),
462
+ ...(contentHtml !== undefined ? { content_html: contentHtml } : {}),
463
+ ...(mentions.length > 0 ? { mentions } : {}),
464
+ ...(links.length > 0 ? { links } : {}),
544
465
  ...(subject !== undefined ? { subject } : {}),
545
466
  ...(root !== undefined && root !== m.id ? { replyTo: root } : {}),
546
467
  edited: props.edittime !== undefined && props.edittime !== null && props.edittime !== '',
547
- ...(isDeleted(m) ? { deleted: true } : {}),
468
+ ...(deleted ? { deleted: true } : {}),
548
469
  attachments: { files: fileAttachments(props.files), images: imageAttachments(content) },
549
470
  ...(reactions.length > 0 ? { reactions } : {}),
550
471
  };
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
+ }