@chrischall/microsoft-teams-mcp 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +4 -4
- package/.claude-plugin/plugin.json +2 -2
- package/README.md +577 -93
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +44324 -37483
- package/dist/capture-window.js +41 -0
- package/dist/chatsvc.js +580 -0
- package/dist/compose.js +241 -0
- package/dist/deps.js +1 -0
- package/dist/index.js +35 -6
- package/dist/model.js +603 -0
- package/dist/sharepoint-auth.js +162 -0
- package/dist/sharepoint-token-cache.js +105 -0
- package/dist/sharepoint.js +289 -0
- package/dist/substrate-auth.js +104 -0
- package/dist/substrate-token-cache.js +64 -0
- package/dist/substrate.js +319 -0
- package/dist/token-cache.js +67 -0
- package/dist/tools/activity.js +155 -19
- package/dist/tools/attachment.js +174 -0
- package/dist/tools/changes.js +241 -0
- package/dist/tools/channels.js +62 -44
- package/dist/tools/chat-search.js +65 -0
- package/dist/tools/chat.js +121 -41
- package/dist/tools/confirm.js +188 -0
- package/dist/tools/conversation.js +394 -30
- package/dist/tools/cursor.js +43 -0
- package/dist/tools/errors.js +18 -17
- package/dist/tools/format.js +135 -0
- package/dist/tools/healthcheck.js +91 -27
- package/dist/tools/limit.js +43 -12
- package/dist/tools/listing.js +180 -0
- package/dist/tools/markread.js +246 -0
- package/dist/tools/react.js +217 -0
- package/dist/tools/roots.js +73 -0
- package/dist/tools/search.js +426 -0
- package/dist/tools/send.js +309 -0
- package/dist/tools/timezone.js +38 -0
- package/dist/tools/titles.js +180 -0
- package/dist/tools/unread.js +263 -0
- package/dist/tools/untrusted.js +16 -1
- package/dist/version.js +1 -1
- package/mint.yaml +75 -20
- package/package.json +1 -2
- package/server.json +87 -3
- package/skills/teams-fpx/SKILL.md +111 -92
- package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
- package/skills/teams-fpx/references/teams-env.sh +146 -0
- package/dist/client.js +0 -290
- package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
|
@@ -1,38 +1,402 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, McpToolError, toolAnnotations, } from '@chrischall/mcp-utils';
|
|
3
|
+
import { isUnread, isUserMessage, matchConversations, normaliseMessage, oldestFirst, readHorizon, SELF_CHAT_ALIASES, summariseAll, } from '../model.js';
|
|
4
|
+
import { confirmedSummary } from './confirm.js';
|
|
5
|
+
import { enrichTitles } from './titles.js';
|
|
6
|
+
import { wrapApiError } from './errors.js';
|
|
7
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
8
|
+
import { DEFAULT_LIMIT, limitArg, makeLimitedStopAt, sinceArg } from './limit.js';
|
|
9
|
+
import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
|
|
10
|
+
import { afterMessageIdArg, CURSOR_NO_CACHE_DESCRIPTION, newestId } from './cursor.js';
|
|
11
|
+
import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
|
|
12
|
+
import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
|
|
13
|
+
import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
|
|
14
|
+
const MAX_MESSAGES = 500;
|
|
7
15
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* Only a selected row whose `itemType` matches `kind` counts: the selector
|
|
12
|
-
* spans both sidebars, so a channel row left selected while a chat is open
|
|
13
|
-
* must not be reported as "the chat". If no row matches, more than one does,
|
|
14
|
-
* or the row carries no `itemType`, the conversation is unidentified.
|
|
16
|
+
* Raw messages read before giving up (20 pages of 200). The real bound is the
|
|
17
|
+
* `stopAt` boundary; this only caps a conversation of nothing but system events.
|
|
15
18
|
*/
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
19
|
+
const MAX_RAW_MESSAGES = 4000;
|
|
20
|
+
/** Candidates an ambiguous name lists, as an error or as data. */
|
|
21
|
+
const MAX_CANDIDATES = 10;
|
|
22
|
+
/** Arrival time in epoch ms: a message's id IS its arrival ms; the ISO fields are the fallback. */
|
|
23
|
+
export function arrivalMs(m) {
|
|
24
|
+
const n = Number(m.id);
|
|
25
|
+
if (Number.isFinite(n) && n > 0)
|
|
26
|
+
return n;
|
|
27
|
+
return Date.parse(m.originalarrivaltime ?? m.composetime ?? '');
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Settle a listing's unread hint with what the read actually found: an unread
|
|
31
|
+
* message confirms it, and a read that saw everything past the horizon without
|
|
32
|
+
* one refutes it. A window-cut read with none proves nothing, so the hint stays.
|
|
33
|
+
*/
|
|
34
|
+
export function confirmUnread(summary, unreadCount, exact) {
|
|
35
|
+
if (unreadCount > 0)
|
|
36
|
+
return confirmedSummary(summary, true);
|
|
37
|
+
return exact ? confirmedSummary(summary, false) : summary;
|
|
38
|
+
}
|
|
39
|
+
function describeCandidate(s) {
|
|
40
|
+
const where = s.team !== undefined ? ` in ${s.team}` : '';
|
|
41
|
+
const how = s.match_reason !== undefined ? `, matched by ${s.match_reason}` : '';
|
|
42
|
+
return `"${s.title}"${where} (${s.kind}, id ${s.id}${how})`;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A name that matched several conversations. It is an `McpToolError` — the
|
|
46
|
+
* write tools let it through, as a write must never guess — that also carries
|
|
47
|
+
* every match, so `teams_read_conversation` can return the candidates as data.
|
|
48
|
+
*/
|
|
49
|
+
export class AmbiguousConversationError extends McpToolError {
|
|
50
|
+
query;
|
|
51
|
+
matches;
|
|
52
|
+
constructor(query, matches, verb) {
|
|
53
|
+
const named = matches.slice(0, MAX_CANDIDATES).map(describeCandidate).join('; ');
|
|
54
|
+
const more = matches.length > MAX_CANDIDATES ? ` (first ${MAX_CANDIDATES} shown)` : '';
|
|
55
|
+
super(`"${query}" matches ${matches.length} conversations${more}: ${named}.`, {
|
|
56
|
+
hint: `Pass the id of the one to ${verb} as conversation.`,
|
|
57
|
+
});
|
|
58
|
+
this.query = query;
|
|
59
|
+
this.matches = matches;
|
|
60
|
+
this.name = 'AmbiguousConversationError';
|
|
24
61
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* An ambiguous name as a read's result: the first 10 candidates, each with
|
|
65
|
+
* what tells them apart and how it matched, and how many matched in all.
|
|
66
|
+
*/
|
|
67
|
+
export function ambiguousResult(err) {
|
|
68
|
+
return {
|
|
69
|
+
ambiguous: true,
|
|
70
|
+
query: err.query,
|
|
71
|
+
match_count: err.matches.length,
|
|
72
|
+
candidates: err.matches.slice(0, MAX_CANDIDATES).map((s) => ({
|
|
73
|
+
id: s.id,
|
|
74
|
+
title: s.title,
|
|
75
|
+
kind: s.kind,
|
|
76
|
+
...(s.team !== undefined ? { team: s.team } : {}),
|
|
77
|
+
...(s.lastActivity !== undefined ? { lastActivity: s.lastActivity } : {}),
|
|
78
|
+
...(s.match_reason !== undefined ? { match_reason: s.match_reason } : {}),
|
|
79
|
+
})),
|
|
80
|
+
hint: 'pass one id as conversation',
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The one conversation a `conversation` argument names: an exact id, else a
|
|
85
|
+
* unique title/team/participant substring — never what was said in a chat,
|
|
86
|
+
* since this names the target of sends and reactions too. The match carries
|
|
87
|
+
* its `match_reason`. None is an `McpToolError`; several is an
|
|
88
|
+
* {@link AmbiguousConversationError} naming up to 10 candidates, each with how
|
|
89
|
+
* it matched, so the caller can pass an id. `verb` fills the hint ("Pass the
|
|
90
|
+
* id of the one to read").
|
|
91
|
+
*/
|
|
92
|
+
export function resolveConversation(summaries, conversation, verb) {
|
|
93
|
+
const matches = matchConversations(summaries, conversation);
|
|
94
|
+
if (matches.length === 0) {
|
|
95
|
+
throw new McpToolError(`No chat or channel matches "${conversation}".`, {
|
|
96
|
+
hint: 'List them with teams_list_chats or teams_list_teams_and_channels and pass an id.',
|
|
97
|
+
});
|
|
31
98
|
}
|
|
99
|
+
if (matches.length > 1)
|
|
100
|
+
throw new AmbiguousConversationError(conversation, matches, verb);
|
|
101
|
+
return matches[0];
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* A resolver of `conversation` arguments against one listing: an exact id is
|
|
105
|
+
* {@link resolveConversation}d with just that one titled, a self-chat alias
|
|
106
|
+
* (`notes`, `self`) with nothing titled, and a name against the whole listing
|
|
107
|
+
* with untitled group chats titled by their participants and 1:1s by the
|
|
108
|
+
* other person (`titles.ts`) — so a name can pick one of several chats that
|
|
109
|
+
* share a last sender, or a 1:1 the user wrote in last. The whole-listing
|
|
110
|
+
* titling runs once, however many names the resolver is asked for.
|
|
111
|
+
*/
|
|
112
|
+
function listedResolver(chatsvc, raw, me, verb) {
|
|
113
|
+
const summaries = summariseAll(raw, me);
|
|
114
|
+
let titled;
|
|
115
|
+
return async (conversation) => {
|
|
116
|
+
if (SELF_CHAT_ALIASES.has(conversation.trim().toLowerCase()))
|
|
117
|
+
return resolveConversation(summaries, conversation, verb);
|
|
118
|
+
const exact = summaries.find((s) => s.id === conversation);
|
|
119
|
+
if (exact)
|
|
120
|
+
return resolveConversation(await enrichTitles(chatsvc, raw, me, [exact]), conversation, verb);
|
|
121
|
+
titled ??= enrichTitles(chatsvc, raw, me, summaries);
|
|
122
|
+
return resolveConversation(await titled, conversation, verb);
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** {@link resolveConversation} against the whole listing, titled as {@link listedResolver} says. */
|
|
126
|
+
export async function resolveListed(chatsvc, raw, me, conversation, verb) {
|
|
127
|
+
return listedResolver(chatsvc, raw, me, verb)(conversation);
|
|
128
|
+
}
|
|
129
|
+
/** Conversations one call may read. */
|
|
130
|
+
export const MAX_CONVERSATIONS = 20;
|
|
131
|
+
/** Conversations read at once in a multi-conversation read. */
|
|
132
|
+
export const READ_CONCURRENCY = 4;
|
|
133
|
+
/** Read one resolved conversation. */
|
|
134
|
+
async function readOne(chatsvc, raw, me, summary, { unreadOnly, since, afterMessageId, limit, timeZone, format, roots }) {
|
|
135
|
+
// The self-chat resolves even when the listing does not carry it.
|
|
136
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
137
|
+
const horizon = readHorizon(conv);
|
|
138
|
+
const cutoff = since !== undefined ? Date.parse(since) : undefined;
|
|
139
|
+
const cursor = afterMessageId !== undefined ? Number(afterMessageId) : undefined;
|
|
140
|
+
const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
|
|
141
|
+
const limited = makeLimitedStopAt(unreadOnly ? horizon : undefined, wanted, limit);
|
|
142
|
+
// A cursor or `since` cutoff above the read horizon leaves unread messages unseen.
|
|
143
|
+
let windowCut = false;
|
|
144
|
+
// Only `since` leaves out messages the caller has not seen: a cursor's were returned by an earlier read.
|
|
145
|
+
let sinceCut = false;
|
|
146
|
+
let capped = false;
|
|
147
|
+
// The oldest message paging looked at — where a limit or the raw cap cut the read.
|
|
148
|
+
let lastSeen;
|
|
149
|
+
const stopAt = (m) => {
|
|
150
|
+
lastSeen = Number(m.id);
|
|
151
|
+
// The read horizon (checked inside `limited`) wins over the cursor and `since`, as the nearer boundary.
|
|
152
|
+
const atHorizon = unreadOnly && Number(m.id) <= horizon;
|
|
153
|
+
const at = arrivalMs(m);
|
|
154
|
+
const atCursor = cursor !== undefined && Number(m.id) <= cursor;
|
|
155
|
+
const atSince = cutoff !== undefined && Number.isFinite(at) && at < cutoff;
|
|
156
|
+
if (!atHorizon && (atCursor || atSince)) {
|
|
157
|
+
if (Number(m.id) > horizon) {
|
|
158
|
+
windowCut = true;
|
|
159
|
+
if (atSince && !atCursor)
|
|
160
|
+
sinceCut = true;
|
|
161
|
+
}
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
return limited.stopAt(m);
|
|
165
|
+
};
|
|
166
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
167
|
+
stopAt,
|
|
168
|
+
max: MAX_RAW_MESSAGES,
|
|
169
|
+
onCapped: () => (capped = true),
|
|
170
|
+
});
|
|
171
|
+
const returned = fetched.filter(wanted);
|
|
172
|
+
const newest = newestId(returned);
|
|
173
|
+
const next_cursor = newest ?? afterMessageId;
|
|
174
|
+
const messages = oldestFirst(returned).map((m) => normaliseMessage(m, me, { timeZone }));
|
|
175
|
+
const unread_count = fetched.filter((m) => wanted(m) && isUnread(m, horizon, me)).length;
|
|
176
|
+
const outsideRoots = summary.kind === 'channel'
|
|
177
|
+
? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone })
|
|
178
|
+
: undefined;
|
|
179
|
+
const truncated = limited.truncated || capped;
|
|
180
|
+
// Whether every message past the read horizon was seen, so unread_count is the whole count.
|
|
181
|
+
const exact = !truncated && !windowCut;
|
|
182
|
+
// A limit or cap that cut past the read horizon may have left out older unread messages.
|
|
183
|
+
const limitCut = truncated && (lastSeen === undefined || !(lastSeen <= horizon));
|
|
184
|
+
const skip = limitCut
|
|
185
|
+
? {
|
|
186
|
+
skipped: 'truncated',
|
|
187
|
+
hint: 'The read marker was left where it was: the limit cut this read, so unread messages older than those ' +
|
|
188
|
+
`returned were not returned. Read again with a larger limit (max ${MAX_MESSAGES}) to mark it read, or ` +
|
|
189
|
+
'use teams_mark_read to mark it all read deliberately.',
|
|
190
|
+
}
|
|
191
|
+
: sinceCut
|
|
192
|
+
? {
|
|
193
|
+
skipped: 'since',
|
|
194
|
+
hint: 'The read marker was left where it was: the since cutoff left out unread messages older than those ' +
|
|
195
|
+
'returned. Read again with an earlier since (or without it) to mark it read, or use teams_mark_read ' +
|
|
196
|
+
'to mark it all read deliberately.',
|
|
197
|
+
}
|
|
198
|
+
: undefined;
|
|
199
|
+
const result = {
|
|
200
|
+
conversation: formatConversation(confirmUnread(summary, unread_count, exact), format),
|
|
201
|
+
unread_count,
|
|
202
|
+
...(exact ? {} : { unread_count_scope: 'window' }),
|
|
203
|
+
...formatBody(summary.kind, messages, format, outsideRoots),
|
|
204
|
+
...(truncated
|
|
205
|
+
? {
|
|
206
|
+
truncated: {
|
|
207
|
+
returned: messages.length,
|
|
208
|
+
hint: `Only the newest ${messages.length} messages were returned; pass a larger limit ` +
|
|
209
|
+
`(max ${MAX_MESSAGES}) or a since time to read further back.`,
|
|
210
|
+
},
|
|
211
|
+
}
|
|
212
|
+
: {}),
|
|
213
|
+
...(next_cursor !== undefined ? { next_cursor } : {}),
|
|
214
|
+
};
|
|
215
|
+
return { summary, conv, newest, ...(skip !== undefined ? { skip } : {}), result };
|
|
216
|
+
}
|
|
217
|
+
function readError(conversation, err, id) {
|
|
218
|
+
const e = wrapApiError(err, 'read this conversation');
|
|
32
219
|
return {
|
|
33
220
|
conversation,
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
221
|
+
...(id !== undefined ? { id } : {}),
|
|
222
|
+
error: e.message,
|
|
223
|
+
...(e.hint !== undefined ? { hint: e.hint } : {}),
|
|
37
224
|
};
|
|
38
225
|
}
|
|
226
|
+
/**
|
|
227
|
+
* Read several conversations: each argument resolved against one listing, the
|
|
228
|
+
* distinct conversations read {@link READ_CONCURRENCY} at a time, in the order
|
|
229
|
+
* asked. An ambiguous name takes its place among them as the same
|
|
230
|
+
* {@link ambiguousResult} a single read returns; one that cannot be resolved
|
|
231
|
+
* or read goes into `errors`; the rest still come back.
|
|
232
|
+
*/
|
|
233
|
+
async function readMany(chatsvc, raw, me, conversations, opts) {
|
|
234
|
+
const resolve = listedResolver(chatsvc, raw, me, 'read');
|
|
235
|
+
const errors = [];
|
|
236
|
+
/** One slot per distinct conversation asked: a resolved one to read, or an ambiguous name's candidates. */
|
|
237
|
+
const slots = [];
|
|
238
|
+
const seen = new Set();
|
|
239
|
+
for (const asked of new Set(conversations)) {
|
|
240
|
+
try {
|
|
241
|
+
const summary = await resolve(asked);
|
|
242
|
+
// A conversation named twice (by id and by name, say) is read once.
|
|
243
|
+
if (seen.has(summary.id))
|
|
244
|
+
continue;
|
|
245
|
+
seen.add(summary.id);
|
|
246
|
+
slots.push({ asked, summary });
|
|
247
|
+
}
|
|
248
|
+
catch (err) {
|
|
249
|
+
if (err instanceof AmbiguousConversationError)
|
|
250
|
+
slots.push({ ambiguous: ambiguousResult(err) });
|
|
251
|
+
else
|
|
252
|
+
errors.push(readError(asked, err));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const reads = await mapWithConcurrency(slots, READ_CONCURRENCY, async (slot) => {
|
|
256
|
+
if ('ambiguous' in slot)
|
|
257
|
+
return { ok: true, result: slot };
|
|
258
|
+
try {
|
|
259
|
+
return { ok: true, result: await readOne(chatsvc, raw, me, slot.summary, opts) };
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
return { ok: false, error: readError(slot.asked, err, slot.summary.id) };
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
const results = [];
|
|
266
|
+
for (const r of reads) {
|
|
267
|
+
if (r.ok)
|
|
268
|
+
results.push(r.result);
|
|
269
|
+
else
|
|
270
|
+
errors.push(r.error);
|
|
271
|
+
}
|
|
272
|
+
// Resolution failures were found first; list every error in the order asked.
|
|
273
|
+
const order = new Map(conversations.map((c, i) => [c, i]));
|
|
274
|
+
errors.sort((a, b) => (order.get(a.conversation) ?? 0) - (order.get(b.conversation) ?? 0));
|
|
275
|
+
return { reads: results, errors };
|
|
276
|
+
}
|
|
277
|
+
export function registerConversationTools(server, { chatsvc }) {
|
|
278
|
+
server.registerTool('teams_read_conversation', {
|
|
279
|
+
title: 'Read a Teams chat or channel',
|
|
280
|
+
description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
|
|
281
|
+
'teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in ' +
|
|
282
|
+
'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, ' +
|
|
283
|
+
'text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, ' +
|
|
284
|
+
'each root post with its replies. A root older than the window is fetched and marked outside_window: ' +
|
|
285
|
+
'true (it is context, not counted or cursored); up to ' +
|
|
286
|
+
`${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is ` +
|
|
287
|
+
'{ id, missing: true }. ' +
|
|
288
|
+
'unread_only returns just the messages the user has not read; since stops at a time; ' +
|
|
289
|
+
'limit keeps the newest (truncated says when more exist; unread_count_scope "window" says ' +
|
|
290
|
+
'unread_count only covers what limit/since/after_message_id let through). after_message_id returns only ' +
|
|
291
|
+
'messages newer than that id; next_cursor is the newest returned message id (or after_message_id ' +
|
|
292
|
+
'when nothing is new) — pass it back as after_message_id to read only what arrived since. ' +
|
|
293
|
+
'after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that ' +
|
|
294
|
+
"row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). " +
|
|
295
|
+
CURSOR_NO_CACHE_DESCRIPTION +
|
|
296
|
+
FORMAT_DESCRIPTION +
|
|
297
|
+
`conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then ` +
|
|
298
|
+
'{ conversations: [...], errors, fetched_at }, one single-read result per conversation (the other ' +
|
|
299
|
+
'arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ' +
|
|
300
|
+
'... } object a single read returns, and one that cannot be resolved or read is listed in errors ' +
|
|
301
|
+
'while the rest still come back. ' +
|
|
302
|
+
MARK_READ_DESCRIPTION +
|
|
303
|
+
'With mark_read the read marker of each conversation read moves up to the newest message returned ' +
|
|
304
|
+
'(never backwards; outside_window roots do not count) and its result says marked_read; one whose limit ' +
|
|
305
|
+
'or since cut off unread messages older than those returned is not marked (marked_read: { skipped, ' +
|
|
306
|
+
'hint }), while a limit that cut only already-read messages does not stop it; the user ' +
|
|
307
|
+
'confirms first — a prompt where the client supports one, otherwise the first call returns only a ' +
|
|
308
|
+
'preview and a confirmToken, and the repeat call with it reads and marks. ' +
|
|
309
|
+
CONFIRM_INJECTION_RULE +
|
|
310
|
+
' Attachments are listed per message (images by ref, files by ' +
|
|
311
|
+
'name) and fetched with teams_get_attachment. A name that matches several conversations is ' +
|
|
312
|
+
'not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each ' +
|
|
313
|
+
'with id, title, kind, team, lastActivity and match_reason), hint} and no messages — read again ' +
|
|
314
|
+
'with one candidate\'s id. ' +
|
|
315
|
+
TIME_ZONE_DESCRIPTION +
|
|
316
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
317
|
+
// A write only with mark_read, but a write: it moves the user's read marker (never backwards, so a repeat is a no-op).
|
|
318
|
+
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
319
|
+
inputSchema: {
|
|
320
|
+
conversation: z
|
|
321
|
+
.union([z.string().min(1), z.array(z.string().min(1)).min(1).max(MAX_CONVERSATIONS)])
|
|
322
|
+
.describe('The conversation id ("48:notes", "notes" or "self" for the self-chat), or a case-insensitive ' +
|
|
323
|
+
"substring of the chat title, channel name, team name or an untitled chat's participant names; " +
|
|
324
|
+
`or an array of up to ${MAX_CONVERSATIONS} of them to read several at once.`),
|
|
325
|
+
unread_only: z
|
|
326
|
+
.boolean()
|
|
327
|
+
.optional()
|
|
328
|
+
.describe('Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set.'),
|
|
329
|
+
since: sinceArg,
|
|
330
|
+
after_message_id: afterMessageIdArg,
|
|
331
|
+
limit: limitArg(MAX_MESSAGES, 'messages'),
|
|
332
|
+
tz: tzArg,
|
|
333
|
+
format: formatArg,
|
|
334
|
+
mark_read: markReadArg,
|
|
335
|
+
confirmToken: confirmTokenParam,
|
|
336
|
+
},
|
|
337
|
+
}, async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
338
|
+
try {
|
|
339
|
+
assertMarkReadFormat(mark_read, format);
|
|
340
|
+
const opts = {
|
|
341
|
+
unreadOnly: unread_only ?? false,
|
|
342
|
+
since,
|
|
343
|
+
afterMessageId: after_message_id,
|
|
344
|
+
limit: limit ?? DEFAULT_LIMIT,
|
|
345
|
+
timeZone: resolveTimeZone(tz),
|
|
346
|
+
format: format ?? 'full',
|
|
347
|
+
roots: rootBudget(),
|
|
348
|
+
};
|
|
349
|
+
const fetched_at = new Date().toISOString();
|
|
350
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
351
|
+
const many = Array.isArray(conversation)
|
|
352
|
+
? await readMany(chatsvc, raw, me, conversation, opts)
|
|
353
|
+
: {
|
|
354
|
+
reads: [await readOne(chatsvc, raw, me, await resolveListed(chatsvc, raw, me, conversation, 'read'), opts)],
|
|
355
|
+
errors: [],
|
|
356
|
+
};
|
|
357
|
+
let marks;
|
|
358
|
+
if (mark_read) {
|
|
359
|
+
// One confirmation covers every conversation the call read; each marker moves only forwards.
|
|
360
|
+
const plans = [];
|
|
361
|
+
for (const read of many.reads) {
|
|
362
|
+
if ('ambiguous' in read)
|
|
363
|
+
continue;
|
|
364
|
+
const { summary, conv, newest, skip } = read;
|
|
365
|
+
if (skip === undefined && advancesHorizon(conv, newest))
|
|
366
|
+
plans.push({ summary, previous: horizonMessageId(conv), target: newest });
|
|
367
|
+
}
|
|
368
|
+
if (plans.length > 0) {
|
|
369
|
+
const gate = await confirmMarks(ctx, { tool: 'teams_read_conversation', me, plans, confirmToken });
|
|
370
|
+
if (gate)
|
|
371
|
+
return gate;
|
|
372
|
+
}
|
|
373
|
+
marks = await applyMarks(chatsvc, plans);
|
|
374
|
+
}
|
|
375
|
+
const results = many.reads.map((read) => 'ambiguous' in read
|
|
376
|
+
? read.ambiguous
|
|
377
|
+
: {
|
|
378
|
+
...read.result,
|
|
379
|
+
...(marks !== undefined
|
|
380
|
+
? (marks.get(read.summary.id) ??
|
|
381
|
+
(read.skip !== undefined && advancesHorizon(read.conv, read.newest)
|
|
382
|
+
? { marked_read: read.skip }
|
|
383
|
+
: { marked_read: false }))
|
|
384
|
+
: {}),
|
|
385
|
+
});
|
|
386
|
+
if (Array.isArray(conversation)) {
|
|
387
|
+
return untrustedResult({
|
|
388
|
+
conversations: results,
|
|
389
|
+
...(many.errors.length > 0 ? { errors: many.errors } : {}),
|
|
390
|
+
fetched_at,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
return untrustedResult({ ...results[0], fetched_at });
|
|
394
|
+
}
|
|
395
|
+
catch (err) {
|
|
396
|
+
// A read can safely hand back the candidates; the write tools keep refusing.
|
|
397
|
+
if (err instanceof AmbiguousConversationError)
|
|
398
|
+
return untrustedResult(ambiguousResult(err));
|
|
399
|
+
throw wrapApiError(err, 'read the conversation');
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message-id cursors: "only what is new since I last looked".
|
|
3
|
+
*
|
|
4
|
+
* A chat-service message id IS its arrival time in epoch ms (`arrivalMs`), so
|
|
5
|
+
* ids order messages, and "newer than the last one I saw" is a plain numeric
|
|
6
|
+
* comparison — a stop boundary for the newest-first read, exactly like the read
|
|
7
|
+
* horizon. The cursor handed back (`next_cursor`) is just the newest returned
|
|
8
|
+
* message's id; the caller passes it back as `after_message_id` (or, for
|
|
9
|
+
* `teams_get_unread`, inside `cursors`). The server keeps no state and no
|
|
10
|
+
* cache: every call reads live, and says when in `fetched_at`.
|
|
11
|
+
*
|
|
12
|
+
* `teams_get_changes` has a different, time cursor (an opaque token); it is
|
|
13
|
+
* not accepted here. Its rows carry the message-id cursor to hand on instead,
|
|
14
|
+
* `after_message_id` — its cursor time written as an id.
|
|
15
|
+
*/
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
/** A message id: decimal digits (its arrival epoch ms). */
|
|
18
|
+
const messageId = z.string().regex(/^\d+$/, {
|
|
19
|
+
message: 'a message id is decimal digits, e.g. "1760000000000" — a teams_get_changes next_cursor is not one; ' +
|
|
20
|
+
'pass its per-conversation after_message_id instead',
|
|
21
|
+
});
|
|
22
|
+
export const afterMessageIdArg = messageId
|
|
23
|
+
.optional()
|
|
24
|
+
.describe('Only return messages newer than this message id (a previous teams_read_conversation next_cursor, a ' +
|
|
25
|
+
"teams_get_changes row's after_message_id, or any message id); the read stops at the first message at " +
|
|
26
|
+
"or before it. Not teams_get_changes' next_cursor, which is a time token.");
|
|
27
|
+
export const cursorsArg = z
|
|
28
|
+
.record(z.string(), messageId)
|
|
29
|
+
.optional()
|
|
30
|
+
.describe('Per-conversation cursors, { conversationId: messageId } (a previous result\'s next_cursors): each ' +
|
|
31
|
+
"conversation's read stops at the later of its read marker and its cursor, so only unread messages " +
|
|
32
|
+
'newer than the cursor come back, and a conversation with none past it is left out.');
|
|
33
|
+
/** Shared description text: what next_cursor is and that nothing is cached. */
|
|
34
|
+
export const CURSOR_NO_CACHE_DESCRIPTION = 'fetched_at is when this call read Teams: the server holds no cache, so every call reads live ' +
|
|
35
|
+
'(there is nothing to refresh). ';
|
|
36
|
+
/** The id of the newest of `messages` (ids are arrival ms), or undefined when there are none. */
|
|
37
|
+
export function newestId(messages) {
|
|
38
|
+
let newest;
|
|
39
|
+
for (const m of messages)
|
|
40
|
+
if (newest === undefined || Number(m.id) > Number(newest))
|
|
41
|
+
newest = m.id;
|
|
42
|
+
return newest;
|
|
43
|
+
}
|
package/dist/tools/errors.js
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
import { McpToolError } from '@chrischall/mcp-utils';
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
cause: err,
|
|
12
|
-
});
|
|
13
|
-
}
|
|
2
|
+
/**
|
|
3
|
+
* Classify a chat-service failure. The client already raises actionable
|
|
4
|
+
* `McpToolError`s (401 after re-capture, 429, 5xx), which pass through as-is;
|
|
5
|
+
* what is left is the token capture, which fails as a plain `Error` from
|
|
6
|
+
* `auth-fetchproxy.ts`.
|
|
7
|
+
*/
|
|
8
|
+
export function wrapApiError(err, action) {
|
|
9
|
+
if (err instanceof McpToolError)
|
|
10
|
+
return err;
|
|
14
11
|
const message = err instanceof Error ? err.message : String(err);
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
hint: 'Open teams.cloud.microsoft in Chrome, make sure you are signed in, and retry.',
|
|
18
|
-
});
|
|
19
|
-
}
|
|
12
|
+
// A pairing prompt surfaces inside the capture error; approving it is the
|
|
13
|
+
// fix, not opening a tab.
|
|
20
14
|
if (/pair code|not granted|not in declared/i.test(message)) {
|
|
21
15
|
return new McpToolError(`The Teams browser bridge is not yet approved: ${message}`, {
|
|
22
16
|
hint: 'Approve the pairing request in the ContextMint Bridge extension popup, then retry.',
|
|
23
17
|
});
|
|
24
18
|
}
|
|
19
|
+
if (/could not capture a Teams token/i.test(message)) {
|
|
20
|
+
return new McpToolError(`Could not get a Teams access token to ${action}.`, {
|
|
21
|
+
hint: 'Open a signed-in teams.cloud.microsoft tab and click into any chat (that is what makes ' +
|
|
22
|
+
'Teams call its chat service, which is where the token is read from), then retry.',
|
|
23
|
+
cause: err,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
25
26
|
return new McpToolError(`Failed to ${action}: ${message}`);
|
|
26
27
|
}
|
|
@@ -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
|
+
}
|