@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.1
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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +344 -32
- package/dist/bundle.js +2216 -474
- package/dist/chatsvc.js +81 -9
- package/dist/index.js +10 -1
- package/dist/model.js +119 -15
- package/dist/network-error.js +124 -0
- package/dist/sharepoint.js +13 -3
- package/dist/substrate-auth.js +104 -0
- package/dist/substrate-token-cache.js +64 -0
- package/dist/substrate.js +326 -0
- package/dist/tools/attachment.js +5 -0
- package/dist/tools/changes.js +241 -0
- package/dist/tools/channels.js +5 -3
- package/dist/tools/chat-search.js +65 -0
- package/dist/tools/chat.js +89 -14
- package/dist/tools/confirm.js +50 -7
- package/dist/tools/conversation.js +326 -102
- package/dist/tools/cursor.js +43 -0
- package/dist/tools/format.js +135 -0
- package/dist/tools/healthcheck.js +7 -2
- package/dist/tools/listing.js +74 -10
- package/dist/tools/markread.js +246 -0
- package/dist/tools/roots.js +73 -0
- package/dist/tools/search.js +426 -0
- package/dist/tools/timezone.js +38 -0
- package/dist/tools/unread.js +140 -39
- package/dist/version.js +1 -1
- package/mint.yaml +16 -2
- package/package.json +1 -1
- package/server.json +10 -3
- package/skills/teams-fpx/SKILL.md +6 -3
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Output-size modes for the read tools (`teams_read_conversation`,
|
|
3
|
+
* `teams_get_unread`): how much of each conversation a result carries.
|
|
4
|
+
*
|
|
5
|
+
* - `full` (default) — every message field and the whole conversation summary,
|
|
6
|
+
* exactly as before.
|
|
7
|
+
* - `compact` — each message only `{ id, time, time_local?, sender, text }`
|
|
8
|
+
* (plus `subject` when it has one): no reactions, attachments, edited/deleted
|
|
9
|
+
* flags, `fromMe` or `replyTo` (a channel's threads already say what replies
|
|
10
|
+
* to what), and the conversation only `{ id, kind, title, team? }`.
|
|
11
|
+
* - `summary` — no messages at all: per conversation `message_count`, the
|
|
12
|
+
* newest message's time and, for a channel, one line per thread (root id,
|
|
13
|
+
* subject, reply count, newest time).
|
|
14
|
+
*
|
|
15
|
+
* A channel thread whose root is older than the window shows the root fetched
|
|
16
|
+
* by id (`roots.ts`), marked `outside_window` (`root_outside_window` in
|
|
17
|
+
* summary), or — when it could not be fetched — a `{ id, missing: true }`
|
|
18
|
+
* placeholder (`root_missing`).
|
|
19
|
+
*
|
|
20
|
+
* Every format keeps the conversation's id, and everything else a read reports
|
|
21
|
+
* (unread_count, next_cursor, truncated, …) is the same in all three: the
|
|
22
|
+
* format only changes how the messages are shown, never which were read.
|
|
23
|
+
*/
|
|
24
|
+
import { z } from 'zod';
|
|
25
|
+
export const READ_FORMATS = ['full', 'compact', 'summary'];
|
|
26
|
+
export const formatArg = z
|
|
27
|
+
.enum(READ_FORMATS)
|
|
28
|
+
.optional()
|
|
29
|
+
.describe('How much to return (default full). full: every message field. compact: each message only id, time, ' +
|
|
30
|
+
'time_local, sender, text (and subject when set) — no reactions, attachments or edited/deleted flags. ' +
|
|
31
|
+
'summary: no messages, just per conversation its counts, newest message time and, for a channel, ' +
|
|
32
|
+
'each thread\'s root id, subject, reply count and newest time.');
|
|
33
|
+
/** Shared description text for the `format` argument. */
|
|
34
|
+
export const FORMAT_DESCRIPTION = 'format "compact" trims each message to id, time, sender and text, and the conversation to id, kind ' +
|
|
35
|
+
'and title; format "summary" returns no messages, only message_count, newest_time and, for a channel, ' +
|
|
36
|
+
'threads of { root_id, subject, reply_count, newest_time } — every format keeps the conversation id. ';
|
|
37
|
+
const NO_ROOTS = new Map();
|
|
38
|
+
/**
|
|
39
|
+
* Group oldest-first channel messages under their root post, in order of first
|
|
40
|
+
* appearance. A reply whose root is older than the window still appears, under
|
|
41
|
+
* that root as fetched (`roots`, marked `outside_window`), else a
|
|
42
|
+
* `{ id, missing: true }` placeholder.
|
|
43
|
+
*/
|
|
44
|
+
export function groupThreads(messages, roots = NO_ROOTS) {
|
|
45
|
+
const byRoot = new Map();
|
|
46
|
+
for (const m of messages) {
|
|
47
|
+
const rootId = m.replyTo ?? m.id;
|
|
48
|
+
let thread = byRoot.get(rootId);
|
|
49
|
+
if (thread === undefined) {
|
|
50
|
+
const outside = roots.get(rootId);
|
|
51
|
+
const root = outside !== undefined ? { ...outside, outside_window: true } : { id: rootId, missing: true };
|
|
52
|
+
thread = { root, replies: [] };
|
|
53
|
+
byRoot.set(rootId, thread);
|
|
54
|
+
}
|
|
55
|
+
if (m.replyTo === undefined)
|
|
56
|
+
thread.root = m;
|
|
57
|
+
else
|
|
58
|
+
thread.replies.push(m);
|
|
59
|
+
}
|
|
60
|
+
return [...byRoot.values()];
|
|
61
|
+
}
|
|
62
|
+
function compactMessage(m) {
|
|
63
|
+
return {
|
|
64
|
+
id: m.id,
|
|
65
|
+
time: m.time,
|
|
66
|
+
...(m.time_local !== undefined ? { time_local: m.time_local } : {}),
|
|
67
|
+
sender: m.sender,
|
|
68
|
+
text: m.text,
|
|
69
|
+
...(m.subject !== undefined ? { subject: m.subject } : {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const isMissing = (root) => 'missing' in root;
|
|
73
|
+
const isOutside = (root) => 'outside_window' in root;
|
|
74
|
+
/** The newest of oldest-first `messages`, as `newest_time` (and `newest_time_local`); nothing for none. */
|
|
75
|
+
function newestTime(messages) {
|
|
76
|
+
const newest = messages.at(-1);
|
|
77
|
+
if (newest === undefined)
|
|
78
|
+
return {};
|
|
79
|
+
return {
|
|
80
|
+
newest_time: newest.time,
|
|
81
|
+
...(newest.time_local !== undefined ? { newest_time_local: newest.time_local } : {}),
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function summariseThread({ root, replies }) {
|
|
85
|
+
const subject = isMissing(root) ? undefined : root.subject;
|
|
86
|
+
// A root from outside the window is not one of the read's messages, so it does not time the thread.
|
|
87
|
+
const inWindow = !isMissing(root) && !isOutside(root);
|
|
88
|
+
return {
|
|
89
|
+
root_id: root.id,
|
|
90
|
+
...(isMissing(root) ? { root_missing: true } : {}),
|
|
91
|
+
...(isOutside(root) ? { root_outside_window: true } : {}),
|
|
92
|
+
...(subject !== undefined ? { subject } : {}),
|
|
93
|
+
reply_count: replies.length,
|
|
94
|
+
// Replies are oldest first and newer than their root, so the last reply is the newest.
|
|
95
|
+
...newestTime(inWindow ? [root, ...replies] : replies),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function compactRoot(root) {
|
|
99
|
+
if (isMissing(root))
|
|
100
|
+
return root;
|
|
101
|
+
return { ...compactMessage(root), ...(isOutside(root) ? { outside_window: true } : {}) };
|
|
102
|
+
}
|
|
103
|
+
/** The conversation summary a result carries: whole in full, else just what names it. */
|
|
104
|
+
export function formatConversation(summary, format) {
|
|
105
|
+
if (format === 'full')
|
|
106
|
+
return summary;
|
|
107
|
+
const { id, kind, title, team } = summary;
|
|
108
|
+
return { id, kind, title, ...(team !== undefined ? { team } : {}) };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* A conversation's oldest-first messages as a result shows them: `messages`
|
|
112
|
+
* (or a channel's `threads`, with `roots` fetched from outside the window) in
|
|
113
|
+
* full or compact, or their summary.
|
|
114
|
+
*/
|
|
115
|
+
export function formatBody(kind, messages, format, roots = NO_ROOTS) {
|
|
116
|
+
const channel = kind === 'channel';
|
|
117
|
+
if (format === 'summary') {
|
|
118
|
+
return {
|
|
119
|
+
message_count: messages.length,
|
|
120
|
+
...newestTime(messages),
|
|
121
|
+
...(channel ? { threads: groupThreads(messages, roots).map(summariseThread) } : {}),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
if (format === 'compact') {
|
|
125
|
+
if (!channel)
|
|
126
|
+
return { messages: messages.map(compactMessage) };
|
|
127
|
+
return {
|
|
128
|
+
threads: groupThreads(messages, roots).map(({ root, replies }) => ({
|
|
129
|
+
root: compactRoot(root),
|
|
130
|
+
replies: replies.map(compactMessage),
|
|
131
|
+
})),
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
return channel ? { threads: groupThreads(messages, roots) } : { messages: [...messages] };
|
|
135
|
+
}
|
|
@@ -10,6 +10,11 @@ const TITLE = 'Verify the Teams chat-service token and API end-to-end';
|
|
|
10
10
|
const SHAREPOINT_NOTE = 'Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on ' +
|
|
11
11
|
'demand per SharePoint host and short-lived (~53 min). None is held until you open a file, and ' +
|
|
12
12
|
'this healthcheck neither mints nor requires one.';
|
|
13
|
+
/** Static note on the search path. Not probed — a healthy result never depends on it. */
|
|
14
|
+
const SUBSTRATE_NOTE = 'Search (teams_search_messages) uses a separate Microsoft Substrate token for substrate.office.com, ' +
|
|
15
|
+
'captured on demand when you run a search in a Teams tab (the bridge pairing must trust ' +
|
|
16
|
+
'substrate.office.com). Without one, search falls back to a scan of recent conversations; this ' +
|
|
17
|
+
'healthcheck neither mints nor requires one.';
|
|
13
18
|
export function registerHealthcheckTool(server, { chatsvc }) {
|
|
14
19
|
server.registerTool('teams_healthcheck', {
|
|
15
20
|
title: TITLE,
|
|
@@ -68,7 +73,7 @@ export function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
68
73
|
...result.content,
|
|
69
74
|
{
|
|
70
75
|
type: 'text',
|
|
71
|
-
text: JSON.stringify({ chat_service: chatService, sharepoint: SHAREPOINT_NOTE }, null, 2),
|
|
76
|
+
text: JSON.stringify({ chat_service: chatService, sharepoint: SHAREPOINT_NOTE, substrate: SUBSTRATE_NOTE }, null, 2),
|
|
72
77
|
},
|
|
73
78
|
],
|
|
74
79
|
};
|
|
@@ -77,7 +82,7 @@ export function registerHealthcheckTool(server, { chatsvc }) {
|
|
|
77
82
|
content: [
|
|
78
83
|
{
|
|
79
84
|
type: 'text',
|
|
80
|
-
text: JSON.stringify({ ...body, chat_service: chatService, sharepoint: SHAREPOINT_NOTE }, null, 2),
|
|
85
|
+
text: JSON.stringify({ ...body, chat_service: chatService, sharepoint: SHAREPOINT_NOTE, substrate: SUBSTRATE_NOTE }, null, 2),
|
|
81
86
|
},
|
|
82
87
|
],
|
|
83
88
|
};
|
package/dist/tools/listing.js
CHANGED
|
@@ -6,18 +6,34 @@
|
|
|
6
6
|
* is confirmed by reading past its horizon (`confirm.ts`).
|
|
7
7
|
*/
|
|
8
8
|
import { z } from 'zod';
|
|
9
|
-
import { confirmedSummary, confirmUnreadCandidates, olderUnreadReport, sinceCutoff, sinceDaysArg } from './confirm.js';
|
|
9
|
+
import { confirmedSummary, confirmUnreadCandidates, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
|
|
10
10
|
import { wrapApiError } from './errors.js';
|
|
11
|
+
import { searchRecentMessages } from './chat-search.js';
|
|
11
12
|
import { enrichTitles } from './titles.js';
|
|
12
|
-
import { conversationSummary, matchConversations, } from '../model.js';
|
|
13
|
+
import { conversationSummary, matchConversations, SELF_CHAT, SELF_CHAT_ALIASES, } from '../model.js';
|
|
14
|
+
/**
|
|
15
|
+
* Whether a conversation's last activity falls in `[since, until]` (either
|
|
16
|
+
* end open when undefined). With either end given, a conversation with no
|
|
17
|
+
* readable last activity is out: nothing places it in the window.
|
|
18
|
+
*/
|
|
19
|
+
export function activeWithin(s, since, until) {
|
|
20
|
+
if (since === undefined && until === undefined)
|
|
21
|
+
return true;
|
|
22
|
+
const t = s.lastActivity === undefined ? Number.NaN : Date.parse(s.lastActivity);
|
|
23
|
+
if (Number.isNaN(t))
|
|
24
|
+
return false;
|
|
25
|
+
return (since === undefined || t >= since) && (until === undefined || t <= until);
|
|
26
|
+
}
|
|
13
27
|
/** The list tools' `since_days`: it narrows `unread_only` only. */
|
|
14
28
|
export const listSinceDaysArg = sinceDaysArg('With unread_only: ');
|
|
29
|
+
/** The list tools' `older_unread`: it needs `unread_only`. */
|
|
30
|
+
export const listOlderUnreadArg = olderUnreadArg('With unread_only: ');
|
|
15
31
|
export const unreadOnlyArg = z
|
|
16
32
|
.boolean()
|
|
17
33
|
.optional()
|
|
18
34
|
.describe('Only return conversations with a real message (not a call recording or other system event) ' +
|
|
19
35
|
'the user has not read yet, each with its unread_count (default false). Exact: every candidate ' +
|
|
20
|
-
'is confirmed by reading its messages past the read marker. Never marks anything read.');
|
|
36
|
+
'is confirmed by reading its messages past the read marker. Never marks anything read (teams_mark_read does).');
|
|
21
37
|
/** Description text shared by the list tools on what their unread flag means. */
|
|
22
38
|
export const UNREAD_HINT_DESCRIPTION = 'Without unread_only, unread is only a hint from the listing (unread_confirmed: false): it can ' +
|
|
23
39
|
'flag a conversation whose only news is a call recording or other system event. For an exact ' +
|
|
@@ -47,6 +63,10 @@ export function queryArg(what) {
|
|
|
47
63
|
.optional()
|
|
48
64
|
.describe(`Case-insensitive substring of the ${what}, or an exact conversation id.`);
|
|
49
65
|
}
|
|
66
|
+
/** Description text on the match_reason a query adds to each row. */
|
|
67
|
+
export const MATCH_REASON_DESCRIPTION = 'With a query, each row carries match_reason — the first of "id" (exact id), "title", "team", ' +
|
|
68
|
+
'"participant" (an untitled chat\'s participant) or "message" (what was said, not what the ' +
|
|
69
|
+
'conversation is called) that applies.';
|
|
50
70
|
/** Description text on how an untitled group chat or 1:1 is titled. */
|
|
51
71
|
export const GROUP_TITLE_DESCRIPTION = 'A group chat with no topic is titled "Group chat: " and up to three of its recent senders other ' +
|
|
52
72
|
'than the user, most recent first ("; " between names, "+N" for more), and carries every such ' +
|
|
@@ -73,14 +93,29 @@ export const FAVORITES_DESCRIPTION = 'Conversations the user marked a favorite o
|
|
|
73
93
|
*/
|
|
74
94
|
export async function listSummaries(chatsvc, filter) {
|
|
75
95
|
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
76
|
-
let rows = raw
|
|
96
|
+
let rows = raw
|
|
97
|
+
.map((c) => conversationSummary(c, me, raw))
|
|
98
|
+
.filter((s) => filter.kinds.includes(s.kind) && activeWithin(s, filter.activeSince, filter.activeUntil));
|
|
77
99
|
if (filter.unread_only)
|
|
78
100
|
rows = rows.filter((s) => isUnreadCandidateFor(s, filter.include_hidden));
|
|
79
|
-
|
|
80
|
-
if (filter.query !== undefined)
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
101
|
+
let searched = {};
|
|
102
|
+
if (filter.query !== undefined) {
|
|
103
|
+
// A query can name a group chat or 1:1 by a participant, so every untitled one is titled first.
|
|
104
|
+
const titled = await enrichTitles(chatsvc, raw, me, rows);
|
|
105
|
+
const matched = matchConversations(titled, filter.query, { messages: true });
|
|
106
|
+
if (filter.searchMessages && !namesOne(matched, filter.query)) {
|
|
107
|
+
const found = await searchUnmatched(chatsvc, me, titled, matched, filter.query);
|
|
108
|
+
rows = found.rows;
|
|
109
|
+
if (found.failed > 0)
|
|
110
|
+
searched = { messages_not_searched: found.failed };
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
rows = matched;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (!filter.unread_only) {
|
|
117
|
+
return { rows, ...searched, retitle: async (kept) => ({ rows: await enrichTitles(chatsvc, raw, me, kept) }) };
|
|
118
|
+
}
|
|
84
119
|
const outcome = await confirmUnreadCandidates(chatsvc, raw, me, rows, {
|
|
85
120
|
limit: CONFIRM_LIMIT,
|
|
86
121
|
maxRaw: CONFIRM_MAX_RAW,
|
|
@@ -102,6 +137,9 @@ export async function listSummaries(chatsvc, filter) {
|
|
|
102
137
|
return { rows, ...(errs ? { errors: errs } : {}) };
|
|
103
138
|
};
|
|
104
139
|
const errs = errors(failedSummaries);
|
|
140
|
+
// Listed only on request; titled now, since nothing later trims them.
|
|
141
|
+
const listedOlder = filter.older_unread ? outcome.older : [];
|
|
142
|
+
const olderTitled = await enrichTitles(chatsvc, raw, me, listedOlder.map((o) => o.summary));
|
|
105
143
|
return {
|
|
106
144
|
retitle,
|
|
107
145
|
rows: outcome.confirmed.map(({ summary, read }) => ({
|
|
@@ -110,7 +148,33 @@ export async function listSummaries(chatsvc, filter) {
|
|
|
110
148
|
...(read.truncated ? { unread_count_exact: false } : {}),
|
|
111
149
|
})),
|
|
112
150
|
skipped_unreachable: outcome.skippedUnreachable,
|
|
113
|
-
...olderUnreadReport(outcome.
|
|
151
|
+
...olderUnreadReport(outcome.older.length, filter.since_days),
|
|
152
|
+
...olderUnreadConversations(listedOlder, olderTitled),
|
|
114
153
|
...(errs ? { errors: errs } : {}),
|
|
154
|
+
...searched,
|
|
115
155
|
};
|
|
116
156
|
}
|
|
157
|
+
/** Whether the match is an exact id or a self-chat alias — a named chat, not a search. */
|
|
158
|
+
function namesOne(matched, query) {
|
|
159
|
+
if (matched.length !== 1)
|
|
160
|
+
return false;
|
|
161
|
+
const [m] = matched;
|
|
162
|
+
return m.match_reason === 'id' || (m.id === SELF_CHAT && SELF_CHAT_ALIASES.has(query.trim().toLowerCase()));
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* `matched` plus every other row in `all` whose recent messages contain the
|
|
166
|
+
* query (`match_reason: "message"`, with `matched_message`), in `all`'s order.
|
|
167
|
+
*/
|
|
168
|
+
async function searchUnmatched(chatsvc, me, all, matched, query) {
|
|
169
|
+
const byId = new Map(matched.map((m) => [m.id, m]));
|
|
170
|
+
const rest = all.filter((s) => !byId.has(s.id));
|
|
171
|
+
const { hits, failed } = await searchRecentMessages(chatsvc, me, rest.map((s) => s.id), query);
|
|
172
|
+
const rows = all.flatMap((s) => {
|
|
173
|
+
const named = byId.get(s.id);
|
|
174
|
+
if (named !== undefined)
|
|
175
|
+
return [named];
|
|
176
|
+
const hit = hits.get(s.id);
|
|
177
|
+
return hit !== undefined ? [{ ...s, match_reason: 'message', matched_message: hit }] : [];
|
|
178
|
+
});
|
|
179
|
+
return { rows, failed };
|
|
180
|
+
}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { CONFIRM_FLOW_SENTENCE, CONFIRM_INJECTION_RULE, confirmTokenParam, confirmWrite, mapWithConcurrency, McpToolError, toolAnnotations, WriteOutcomeUnknownError, } from '@chrischall/mcp-utils';
|
|
3
|
+
import { outcomeUnknownStatus } from '../chatsvc.js';
|
|
4
|
+
import { clipText } from '../compose.js';
|
|
5
|
+
import { htmlToText, isUnread, readHorizon, SELF_CHAT, senderMri } from '../model.js';
|
|
6
|
+
import { confirmedSummary } from './confirm.js';
|
|
7
|
+
import { resolveListed } from './conversation.js';
|
|
8
|
+
import { wrapApiError } from './errors.js';
|
|
9
|
+
import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
10
|
+
const TOOL = 'teams_mark_read';
|
|
11
|
+
/** Messages read to find the newest one — one page; a page is not strictly ordered, so all of it is looked at. */
|
|
12
|
+
const NEWEST_PAGE = 50;
|
|
13
|
+
/** Previewed text of the message the marker moves to. */
|
|
14
|
+
const PREVIEW_CHARS = 200;
|
|
15
|
+
/** Markers moved at once by a read tool's `mark_read`. */
|
|
16
|
+
const MARK_CONCURRENCY = 4;
|
|
17
|
+
/** The `mark_read` argument the read tools share. */
|
|
18
|
+
export const markReadArg = z
|
|
19
|
+
.boolean()
|
|
20
|
+
.optional()
|
|
21
|
+
.describe('After the read, also mark it read in Teams: move the read marker of each conversation returned up to ' +
|
|
22
|
+
'the newest message returned (default false — the read leaves the unread badges alone). Never moves a ' +
|
|
23
|
+
'marker backwards, and never past an unread message the caller did not receive: a conversation whose ' +
|
|
24
|
+
'read was cut short is left as it was (marked_read: { skipped, hint }). Not allowed with format ' +
|
|
25
|
+
'"summary", which returns no message text. A write, so it asks the user to confirm first, as ' +
|
|
26
|
+
'teams_mark_read does.');
|
|
27
|
+
/**
|
|
28
|
+
* Refuse `mark_read` with `format: "summary"`: the caller would get no message
|
|
29
|
+
* text, so marking would clear badges on messages nobody read.
|
|
30
|
+
*/
|
|
31
|
+
export function assertMarkReadFormat(markRead, format) {
|
|
32
|
+
if (markRead && format === 'summary') {
|
|
33
|
+
throw new McpToolError('mark_read cannot be combined with format "summary": a summary returns no messages, so nothing would have been read.', {
|
|
34
|
+
hint: 'Read with format "full" or "compact" to mark what is returned, or use teams_mark_read to mark a conversation read deliberately.',
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Description text for a read tool that takes `mark_read`. */
|
|
39
|
+
export const MARK_READ_DESCRIPTION = 'By default this does NOT mark anything read — the user\'s Teams unread badges are unaffected; pass ' +
|
|
40
|
+
'mark_read: true (or use teams_mark_read) to clear them. mark_read never marks a message the caller did ' +
|
|
41
|
+
'not receive: it is refused with format "summary" (compact is fine), and a conversation whose read was ' +
|
|
42
|
+
'cut short, leaving unread messages older than those returned, keeps its marker and reports ' +
|
|
43
|
+
'marked_read: { skipped: "truncated" (or "since"), hint }. ';
|
|
44
|
+
/** The request path a marker move PUTs to — the same string the client builds. */
|
|
45
|
+
export function horizonPath(conversationId) {
|
|
46
|
+
return `/users/ME/conversations/${encodeURIComponent(conversationId)}/properties?name=consumptionhorizon`;
|
|
47
|
+
}
|
|
48
|
+
/** The id of the newest of `messages` (a message's id is its arrival ms), or `undefined` for none. */
|
|
49
|
+
export function newestMessageId(messages) {
|
|
50
|
+
let best;
|
|
51
|
+
for (const m of messages) {
|
|
52
|
+
const n = Number(m.id);
|
|
53
|
+
if (Number.isFinite(n) && (best === undefined || n > Number(best)))
|
|
54
|
+
best = m.id;
|
|
55
|
+
}
|
|
56
|
+
return best;
|
|
57
|
+
}
|
|
58
|
+
/** The current marker as a message id (its arrival ms), or `null` for a conversation never opened. */
|
|
59
|
+
export function horizonMessageId(conv) {
|
|
60
|
+
const h = readHorizon(conv);
|
|
61
|
+
return h > 0 ? String(h) : null;
|
|
62
|
+
}
|
|
63
|
+
/** Whether moving the marker to `target` moves it forwards. */
|
|
64
|
+
export function advancesHorizon(conv, target) {
|
|
65
|
+
if (target === undefined)
|
|
66
|
+
return false;
|
|
67
|
+
const n = Number(target);
|
|
68
|
+
return Number.isFinite(n) && n > readHorizon(conv);
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The confirmation for a read tool's `mark_read`: one approval covering every
|
|
72
|
+
* move, each conversation's title fenced as a read tool's result is.
|
|
73
|
+
* Resolves `undefined` when the moves may proceed (see `confirmWrite`).
|
|
74
|
+
*/
|
|
75
|
+
export async function confirmMarks(ctx, opts) {
|
|
76
|
+
const { plans } = opts;
|
|
77
|
+
const many = plans.length > 1;
|
|
78
|
+
return confirmWrite(ctx, {
|
|
79
|
+
tool: opts.tool,
|
|
80
|
+
action: 'chat.mark_read',
|
|
81
|
+
message: 'Review and confirm marking these Teams messages read:',
|
|
82
|
+
summary: many
|
|
83
|
+
? `Mark ${plans.length} conversations read up to their newest returned message`
|
|
84
|
+
: `Mark a ${plans[0].summary.kind} ${JSON.stringify(plans[0].summary.title)} read up to message ${plans[0].target}`,
|
|
85
|
+
account: opts.me,
|
|
86
|
+
...(many
|
|
87
|
+
? { payload: plans.map((p) => ({ conversation: p.summary.id, up_to_message_id: p.target })) }
|
|
88
|
+
: { target: `${plans[0].summary.id}/${plans[0].target}`, request: { method: 'PUT', path: horizonPath(plans[0].summary.id) } }),
|
|
89
|
+
preview: {
|
|
90
|
+
conversations: untrustedField(plans.map((p) => ({
|
|
91
|
+
id: p.summary.id,
|
|
92
|
+
title: p.summary.title,
|
|
93
|
+
kind: p.summary.kind,
|
|
94
|
+
previous_horizon_message_id: p.previous,
|
|
95
|
+
up_to_message_id: p.target,
|
|
96
|
+
}))),
|
|
97
|
+
...(opts.note !== undefined ? { note: opts.note } : {}),
|
|
98
|
+
},
|
|
99
|
+
confirmToken: opts.confirmToken,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
/** Why a write went unconfirmed, for a warning. */
|
|
103
|
+
function unconfirmedWhy(e) {
|
|
104
|
+
const status = outcomeUnknownStatus(e);
|
|
105
|
+
return e.timedOut ? 'it did not answer in time' : status !== undefined ? `it answered HTTP ${status}` : 'the connection dropped';
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Make every move, a few at a time. One failing never costs the others: an
|
|
109
|
+
* unconfirmed or refused move is `marked_read: false` with a warning.
|
|
110
|
+
*/
|
|
111
|
+
export async function applyMarks(chatsvc, plans) {
|
|
112
|
+
const results = await mapWithConcurrency(plans, MARK_CONCURRENCY, async (p) => {
|
|
113
|
+
try {
|
|
114
|
+
await chatsvc.setConsumptionHorizon(p.summary.id, p.target);
|
|
115
|
+
return { marked_read: true };
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
if (e instanceof WriteOutcomeUnknownError) {
|
|
119
|
+
return {
|
|
120
|
+
marked_read: false,
|
|
121
|
+
mark_read_warning: `Teams did not confirm moving the read marker (${unconfirmedWhy(e)}); it may have moved — ` +
|
|
122
|
+
'retrying is harmless.',
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
return { marked_read: false, mark_read_warning: wrapApiError(e, 'mark this conversation read').message };
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
return new Map(plans.map((p, i) => [p.summary.id, results[i]]));
|
|
129
|
+
}
|
|
130
|
+
export function registerMarkReadTools(server, { chatsvc }) {
|
|
131
|
+
server.registerTool(TOOL, {
|
|
132
|
+
title: 'Mark a Teams conversation read',
|
|
133
|
+
description: 'Mark a chat or channel read in Teams, clearing its unread badge: moves the signed-in user\'s read ' +
|
|
134
|
+
'marker up to up_to_message_id (from teams_read_conversation), or by default up to the newest message ' +
|
|
135
|
+
'in the conversation. conversation is an id or name as for teams_read_conversation; ' +
|
|
136
|
+
`"${SELF_CHAT}" (or "notes" / "self") is the user's own notes self-chat — use it to try this tool. ` +
|
|
137
|
+
'The marker never moves backwards: when it is already at or past the target, nothing is written and ' +
|
|
138
|
+
'status is "already_read". Returns the conversation, previous_horizon_message_id (null if it was never ' +
|
|
139
|
+
'opened) and new_horizon_message_id; status "unknown" means Teams did not confirm the move — retrying is ' +
|
|
140
|
+
'harmless. teams_read_conversation and teams_get_unread can do the same after a read with mark_read. ' +
|
|
141
|
+
CONFIRM_FLOW_SENTENCE +
|
|
142
|
+
' The preview shows the conversation, the message the marker moves to and where it was. ' +
|
|
143
|
+
CONFIRM_INJECTION_RULE +
|
|
144
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
145
|
+
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
146
|
+
inputSchema: {
|
|
147
|
+
conversation: z
|
|
148
|
+
.string()
|
|
149
|
+
.min(1)
|
|
150
|
+
.describe(`The conversation id (or "${SELF_CHAT}" — also by the name "notes" or "self" — for the self-chat), ` +
|
|
151
|
+
"or a case-insensitive substring of the chat title, channel name, team name or an untitled chat's participant names."),
|
|
152
|
+
up_to_message_id: z
|
|
153
|
+
.string()
|
|
154
|
+
.min(1)
|
|
155
|
+
.optional()
|
|
156
|
+
.describe('Mark read up to and including this message, as teams_read_conversation lists it (default: the ' +
|
|
157
|
+
'newest message in the conversation). Messages after it stay unread.'),
|
|
158
|
+
confirmToken: confirmTokenParam,
|
|
159
|
+
},
|
|
160
|
+
}, async ({ conversation, up_to_message_id, confirmToken }, ctx) => {
|
|
161
|
+
try {
|
|
162
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
163
|
+
const summary = await resolveListed(chatsvc, raw, me, conversation, 'mark read');
|
|
164
|
+
// The self-chat resolves even when the listing does not carry it.
|
|
165
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
166
|
+
const previous = horizonMessageId(conv);
|
|
167
|
+
const page = await chatsvc.getMessages(summary.id, { max: NEWEST_PAGE, pageSize: NEWEST_PAGE });
|
|
168
|
+
let target;
|
|
169
|
+
if (up_to_message_id !== undefined) {
|
|
170
|
+
target = await chatsvc.getMessage(summary.id, up_to_message_id);
|
|
171
|
+
if (target === undefined) {
|
|
172
|
+
throw new McpToolError(`There is no message ${up_to_message_id} in this conversation to mark read up to.`, {
|
|
173
|
+
hint: 'Take message ids from teams_read_conversation, or leave up_to_message_id out to mark it all read.',
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
const newest = newestMessageId(page);
|
|
179
|
+
target = page.find((m) => m.id === newest);
|
|
180
|
+
}
|
|
181
|
+
if (!advancesHorizon(conv, target?.id)) {
|
|
182
|
+
return untrustedResult({
|
|
183
|
+
status: 'already_read',
|
|
184
|
+
conversation: summary,
|
|
185
|
+
previous_horizon_message_id: previous,
|
|
186
|
+
new_horizon_message_id: previous,
|
|
187
|
+
hint: target === undefined
|
|
188
|
+
? 'The conversation has no messages, so there is nothing to mark read.'
|
|
189
|
+
: `The read marker is already at or past message ${target.id}; it never moves backwards, so nothing was changed.`,
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
const to = target.id;
|
|
193
|
+
const gate = await confirmWrite(ctx, {
|
|
194
|
+
tool: TOOL,
|
|
195
|
+
action: 'chat.mark_read',
|
|
196
|
+
message: 'Review and confirm marking this Teams conversation read:',
|
|
197
|
+
// The title is someone else's text: JSON-quoted so it cannot break out of its quotes.
|
|
198
|
+
summary: `Mark ${summary.kind} ${JSON.stringify(summary.title)} read up to message ${to}`,
|
|
199
|
+
// The signed-in user, so an approval minted under one account never marks another's chats.
|
|
200
|
+
account: me,
|
|
201
|
+
target: `${summary.id}/${to}`,
|
|
202
|
+
// The client time in the body is minted when the marker moves, so it is not bound.
|
|
203
|
+
request: { method: 'PUT', path: horizonPath(summary.id) },
|
|
204
|
+
preview: {
|
|
205
|
+
conversation: untrustedField({ id: summary.id, title: summary.title, kind: summary.kind }),
|
|
206
|
+
up_to_message: untrustedField({
|
|
207
|
+
id: to,
|
|
208
|
+
sender: target.imdisplayname?.trim() || senderMri(target.from) || 'unknown',
|
|
209
|
+
preview: clipText(htmlToText(target.content ?? ''), PREVIEW_CHARS),
|
|
210
|
+
}),
|
|
211
|
+
previous_horizon_message_id: previous,
|
|
212
|
+
},
|
|
213
|
+
confirmToken,
|
|
214
|
+
});
|
|
215
|
+
if (gate)
|
|
216
|
+
return gate;
|
|
217
|
+
// What the page shows past the new marker: anything from someone else is still unread.
|
|
218
|
+
const stillUnread = page.some((m) => isUnread(m, Number(to), me));
|
|
219
|
+
const after = confirmedSummary(summary, stillUnread);
|
|
220
|
+
try {
|
|
221
|
+
await chatsvc.setConsumptionHorizon(summary.id, to);
|
|
222
|
+
}
|
|
223
|
+
catch (e) {
|
|
224
|
+
if (!(e instanceof WriteOutcomeUnknownError))
|
|
225
|
+
throw e;
|
|
226
|
+
return untrustedResult({
|
|
227
|
+
status: 'unknown',
|
|
228
|
+
conversation: summary,
|
|
229
|
+
previous_horizon_message_id: previous,
|
|
230
|
+
new_horizon_message_id: to,
|
|
231
|
+
warning: `Teams did not confirm moving the read marker (${unconfirmedWhy(e)}); it may have moved. ` +
|
|
232
|
+
'Retrying is harmless — moving it to the same message again is one move.',
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
return untrustedResult({
|
|
236
|
+
status: 'marked_read',
|
|
237
|
+
conversation: after,
|
|
238
|
+
previous_horizon_message_id: previous,
|
|
239
|
+
new_horizon_message_id: to,
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
catch (err) {
|
|
243
|
+
throw wrapApiError(err, 'mark the conversation read');
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Channel thread roots that lie outside a read's window.
|
|
3
|
+
*
|
|
4
|
+
* A channel read groups replies under their root post (`format.ts`), but the
|
|
5
|
+
* window — `since`, `limit`, a cursor, or the read horizon for unread — often
|
|
6
|
+
* ends after a thread's root while its newer replies are inside. Each such
|
|
7
|
+
* root is fetched by id (`GET …/conversations/{channelId}/messages/{rootId}`,
|
|
8
|
+
* verified live 2026-10-12: it answers for a root weeks older than the window,
|
|
9
|
+
* in ~250 ms) so the thread keeps its subject, time and sender. A fetched root
|
|
10
|
+
* is context, not part of the read: it is shown marked `outside_window` and
|
|
11
|
+
* counts toward no unread count, message count or cursor.
|
|
12
|
+
*
|
|
13
|
+
* Fetches are bounded per CALL — {@link MAX_ROOT_FETCHES}, shared by every
|
|
14
|
+
* conversation the call reads, newest threads first — and a few run at once.
|
|
15
|
+
* A root past the budget, gone, or unreadable (the service answers 403, not
|
|
16
|
+
* 404, for an id it does not hold) stays the `{ id, missing: true }`
|
|
17
|
+
* placeholder.
|
|
18
|
+
*/
|
|
19
|
+
import { mapWithConcurrency } from '@chrischall/mcp-utils';
|
|
20
|
+
import { normaliseMessage } from '../model.js';
|
|
21
|
+
/** Root fetches one tool call may make, across every conversation it reads. */
|
|
22
|
+
export const MAX_ROOT_FETCHES = 25;
|
|
23
|
+
/** Root fetches in flight at once. */
|
|
24
|
+
export const ROOT_FETCH_CONCURRENCY = 5;
|
|
25
|
+
export function rootBudget() {
|
|
26
|
+
return { remaining: MAX_ROOT_FETCHES };
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The roots of `messages` (oldest first, as normalised) that they do not
|
|
30
|
+
* themselves hold, newest thread first: the ones worth fetching first when the
|
|
31
|
+
* budget runs short.
|
|
32
|
+
*/
|
|
33
|
+
function outsideRootIds(messages) {
|
|
34
|
+
const held = new Set(messages.map((m) => m.id));
|
|
35
|
+
const ids = new Set();
|
|
36
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
37
|
+
const root = messages[i].replyTo;
|
|
38
|
+
if (root !== undefined && !held.has(root))
|
|
39
|
+
ids.add(root);
|
|
40
|
+
}
|
|
41
|
+
return [...ids];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Fetch the roots a channel read's replies point at but its window does not
|
|
45
|
+
* hold, spending from `budget`. Returns those found, by id, normalised as the
|
|
46
|
+
* read's own messages are; a root that failed, came back as some other
|
|
47
|
+
* message, or is itself a reply is left out (it stays missing).
|
|
48
|
+
*/
|
|
49
|
+
export async function fetchOutsideRoots(chatsvc, conversationId, messages, me, { budget, timeZone }) {
|
|
50
|
+
const wanted = outsideRootIds(messages);
|
|
51
|
+
// Taken synchronously, so conversations read concurrently cannot overspend it.
|
|
52
|
+
const ids = wanted.slice(0, Math.max(0, budget.remaining));
|
|
53
|
+
budget.remaining -= ids.length;
|
|
54
|
+
const roots = new Map();
|
|
55
|
+
if (ids.length === 0)
|
|
56
|
+
return roots;
|
|
57
|
+
const fetched = await mapWithConcurrency(ids, ROOT_FETCH_CONCURRENCY, async (id) => {
|
|
58
|
+
try {
|
|
59
|
+
return await chatsvc.getMessage(conversationId, id);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
fetched.forEach((raw, i) => {
|
|
66
|
+
if (raw === undefined || raw.id !== ids[i])
|
|
67
|
+
return;
|
|
68
|
+
const root = normaliseMessage(raw, me, { timeZone });
|
|
69
|
+
if (root.replyTo === undefined)
|
|
70
|
+
roots.set(root.id, root);
|
|
71
|
+
});
|
|
72
|
+
return roots;
|
|
73
|
+
}
|