@chrischall/microsoft-teams-mcp 0.4.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 +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +330 -32
- package/dist/bundle.js +2062 -457
- package/dist/chatsvc.js +35 -7
- package/dist/index.js +10 -1
- package/dist/model.js +119 -15
- package/dist/substrate-auth.js +104 -0
- package/dist/substrate-token-cache.js +64 -0
- package/dist/substrate.js +319 -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 +13 -1
- package/package.json +1 -1
- package/server.json +10 -3
- package/skills/teams-fpx/SKILL.md +6 -3
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Microsoft Substrate search client — the backend Teams' own search box
|
|
3
|
+
* uses, and the primary path of `teams_search_messages` (the client-side
|
|
4
|
+
* chat-service scan in `tools/search.ts` is the fallback).
|
|
5
|
+
*
|
|
6
|
+
* POST https://substrate.office.com/searchservice/api/v2/query
|
|
7
|
+
* [Authorization: Bearer <token>, Content-Type: application/json]
|
|
8
|
+
* { entityRequests: [{ entityType: "Message", contentSources: ["Teams"],
|
|
9
|
+
* query: { queryString, displayQueryString }, from, size,
|
|
10
|
+
* sort: [{ Field: "Time", SortDirection: "Desc" }] }],
|
|
11
|
+
* cvid, logicalId, scenario: { Name: "powerbar", … } }
|
|
12
|
+
* → { EntitySets: [{ ResultSets: [{ Total, MoreResultsAvailable,
|
|
13
|
+
* Results: [{ HitHighlightedSummary, Source: {
|
|
14
|
+
* ClientThreadId, ClientConversationId, InternetMessageId,
|
|
15
|
+
* DateTimeSent, Sender: { EmailAddress: { Name, Address } },
|
|
16
|
+
* Preview, Subject, ChannelName, TeamName, … } }] }] }] }
|
|
17
|
+
*
|
|
18
|
+
* Verified live 2026-10-12 (token captured off the Teams tab, replayed from
|
|
19
|
+
* Node; read-only queries such as "deploy"; a redacted response is
|
|
20
|
+
* `tests/fixtures/substrate-query-response.json`):
|
|
21
|
+
* - No header beyond the bearer and the JSON content type is needed. The
|
|
22
|
+
* token `substrate-auth.ts` captures off `/searchservice/*` worked (an
|
|
23
|
+
* app-GUID audience, ~1.4h lifetime); so did one captured off another
|
|
24
|
+
* substrate.office.com path (audience `https://outlook.office.com/`).
|
|
25
|
+
* - Body: `cvid`/`logicalId` and `scenario.Name` are REQUIRED (400 without);
|
|
26
|
+
* the sort must be `Field: "Time"` with capitalised keys (`DateTime`, or
|
|
27
|
+
* `field`/`sortDirection`, is a 400). `size` up to 200 works; `from`
|
|
28
|
+
* pages without overlap, newest first.
|
|
29
|
+
* - Response: the Teams conversation is `Source.ClientThreadId`;
|
|
30
|
+
* `ClientConversationId` is the same plus `;messageid=<root>` for a
|
|
31
|
+
* channel post or reply. `InternetMessageId` is the Teams message id
|
|
32
|
+
* (equal to the root id on a root post). `Sender` (= `From`) carries a
|
|
33
|
+
* display name and an SMTP address — NO MRI, and the address need not be
|
|
34
|
+
* the token's UPN, so `fromMe` cannot be decided from a hit. `Preview`
|
|
35
|
+
* (= `HitHighlightedSummary`, no highlight markup) is PLAIN TEXT capped
|
|
36
|
+
* at ~255 characters; there is no body. `Subject` is set on a channel
|
|
37
|
+
* root post with a subject. A query with no hits has no `Results` key.
|
|
38
|
+
* `Total` is an estimate (one phrase query said 86 and paged to 11).
|
|
39
|
+
* - Matching is Substrate's: words ANDed with stemming ("deploy" matches
|
|
40
|
+
* "deployed", "deployment"), `"phrases"`, `OR`; not window-bound (all
|
|
41
|
+
* history unless restricted).
|
|
42
|
+
* - Server-side restrictions in the query string, ANDed with a
|
|
43
|
+
* parenthesised user query: `ClientThreadId:"<conversation id>"` (also
|
|
44
|
+
* for `48:notes`) and `sent>=<ISO date-time, UNQUOTED>` (a quoted value
|
|
45
|
+
* was mis-read). `from:<word>` exists but matches name/address word
|
|
46
|
+
* PREFIXES, not the "display name contains" the tool promises, so `from`
|
|
47
|
+
* stays client-side.
|
|
48
|
+
* - A bad token is a 401.
|
|
49
|
+
*
|
|
50
|
+
* As with the other clients, the bridge is touched only to capture the token
|
|
51
|
+
* (`substrate-auth.ts`); every request is a plain Node `fetch`.
|
|
52
|
+
*/
|
|
53
|
+
import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
|
|
54
|
+
import { TokenManager } from '@chrischall/mcp-utils/session';
|
|
55
|
+
import { createSubstrateTokenCache } from './substrate-token-cache.js';
|
|
56
|
+
export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
|
|
57
|
+
/**
|
|
58
|
+
* How long after a failed capture (or a 401 on a freshly captured token) an
|
|
59
|
+
* unforced search skips straight to failing
|
|
60
|
+
* (so mode "auto" falls back to the scan at once) instead of holding the call
|
|
61
|
+
* for another capture window. Mode "substrate" forces a fresh attempt.
|
|
62
|
+
*/
|
|
63
|
+
export const CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1000;
|
|
64
|
+
/** Fallback lifetime for a token whose `exp` we cannot read (as in `sharepoint.ts`). */
|
|
65
|
+
const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
|
|
66
|
+
/** Stands in for a refresh token this flow does not have (see `sharepoint.ts`). */
|
|
67
|
+
const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
|
|
68
|
+
/** Per-request deadline, covering the body read. */
|
|
69
|
+
const REQUEST_TIMEOUT_MS = 30_000;
|
|
70
|
+
/** A search response is a page of summaries; anything near this is not one. */
|
|
71
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
72
|
+
function toBearerTokens(accessToken) {
|
|
73
|
+
let expiresAt;
|
|
74
|
+
try {
|
|
75
|
+
expiresAt = decodeJwtExp(accessToken) * 1000;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
|
|
79
|
+
}
|
|
80
|
+
return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
|
|
81
|
+
}
|
|
82
|
+
/** Capture lazily, so boot never loads the bridge (see `sharepoint.ts`). */
|
|
83
|
+
async function captureSubstrateTokenLazily() {
|
|
84
|
+
const mod = await import('./substrate-auth.js');
|
|
85
|
+
return mod.captureSubstrateTokenViaFetchproxy();
|
|
86
|
+
}
|
|
87
|
+
/** `sent>=` takes an unquoted ISO date-time (a quoted one was mis-read live); whole seconds, rounded down. */
|
|
88
|
+
function sentBound(ms) {
|
|
89
|
+
return new Date(Math.floor(ms / 1000) * 1000).toISOString().replace(/\.000Z$/, 'Z');
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The query string: the user's query, ANDed with the verified KQL-style
|
|
93
|
+
* property restrictions. With a restriction, the user's query is
|
|
94
|
+
* parenthesised so an `OR` in it cannot escape the filter (verified live).
|
|
95
|
+
*/
|
|
96
|
+
export function buildQueryString(req) {
|
|
97
|
+
const filters = [];
|
|
98
|
+
if (req.conversationId !== undefined) {
|
|
99
|
+
if (/["\s]/.test(req.conversationId)) {
|
|
100
|
+
throw new McpToolError('That conversation id cannot be expressed as a Substrate filter.', { kind: 'unknown' });
|
|
101
|
+
}
|
|
102
|
+
filters.push(`ClientThreadId:"${req.conversationId}"`);
|
|
103
|
+
}
|
|
104
|
+
if (req.sentAfter !== undefined && Number.isFinite(req.sentAfter))
|
|
105
|
+
filters.push(`sent>=${sentBound(req.sentAfter)}`);
|
|
106
|
+
return filters.length === 0 ? req.query : [`(${req.query})`, ...filters].join(' ');
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The query body, as verified live 2026-10-12. Required (400 without them):
|
|
110
|
+
* `cvid` + `logicalId`, and a `scenario` with a `Name`. `sort` must be
|
|
111
|
+
* `{ Field: "Time", SortDirection: "Desc" }` — `DateTime`, or lower-case keys,
|
|
112
|
+
* are a 400.
|
|
113
|
+
*/
|
|
114
|
+
export function buildQueryBody(req) {
|
|
115
|
+
const cvid = crypto.randomUUID();
|
|
116
|
+
return {
|
|
117
|
+
entityRequests: [
|
|
118
|
+
{
|
|
119
|
+
entityType: 'Message',
|
|
120
|
+
contentSources: ['Teams'],
|
|
121
|
+
query: { queryString: buildQueryString(req), displayQueryString: req.query },
|
|
122
|
+
from: req.from,
|
|
123
|
+
size: req.size,
|
|
124
|
+
sort: [{ Field: 'Time', SortDirection: 'Desc' }],
|
|
125
|
+
},
|
|
126
|
+
],
|
|
127
|
+
cvid,
|
|
128
|
+
logicalId: cvid,
|
|
129
|
+
scenario: {
|
|
130
|
+
Name: 'powerbar',
|
|
131
|
+
Dimensions: [
|
|
132
|
+
{ DimensionName: 'QueryType', DimensionValue: 'Messages' },
|
|
133
|
+
{ DimensionName: 'FormFactor', DimensionValue: 'general.web.reactSearch' },
|
|
134
|
+
],
|
|
135
|
+
},
|
|
136
|
+
QueryAlterationOptions: { EnableSuggestion: false, EnableAlteration: false },
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function obj(v) {
|
|
140
|
+
return v !== null && typeof v === 'object' && !Array.isArray(v) ? v : undefined;
|
|
141
|
+
}
|
|
142
|
+
function str(v) {
|
|
143
|
+
return typeof v === 'string' && v.trim() !== '' ? v : undefined;
|
|
144
|
+
}
|
|
145
|
+
function isoOf(v) {
|
|
146
|
+
const s = str(v);
|
|
147
|
+
if (s === undefined)
|
|
148
|
+
return undefined;
|
|
149
|
+
const ms = Date.parse(s);
|
|
150
|
+
return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
|
|
151
|
+
}
|
|
152
|
+
function mapResult(raw) {
|
|
153
|
+
const r = obj(raw);
|
|
154
|
+
const source = obj(r?.Source);
|
|
155
|
+
if (r === undefined || source === undefined)
|
|
156
|
+
return undefined;
|
|
157
|
+
// `19:x@thread.tacv2;messageid=<root>` for a channel post or reply; the bare id for a chat.
|
|
158
|
+
const clientConv = str(source.ClientConversationId) ?? str(source.ClientThreadId);
|
|
159
|
+
if (clientConv === undefined)
|
|
160
|
+
return undefined;
|
|
161
|
+
const [conversationId, ...params] = clientConv.split(';');
|
|
162
|
+
if (str(conversationId) === undefined)
|
|
163
|
+
return undefined;
|
|
164
|
+
const root = params.map((p) => /^messageid=(.+)$/i.exec(p.trim())?.[1]).find((v) => v !== undefined);
|
|
165
|
+
const messageId = str(source.InternetMessageId);
|
|
166
|
+
// `Sender` and `From` were identical on every hit seen live.
|
|
167
|
+
const from = obj(obj(source.Sender)?.EmailAddress) ?? obj(obj(source.From)?.EmailAddress);
|
|
168
|
+
const text = str(source.Preview) ?? str(r.HitHighlightedSummary) ?? '';
|
|
169
|
+
const time = isoOf(source.DateTimeSent) ?? isoOf(source.DateTimeReceived) ?? isoOf(source.DateTimeCreated);
|
|
170
|
+
const sender = str(from?.Name);
|
|
171
|
+
const senderEmail = str(from?.Address);
|
|
172
|
+
const subject = str(source.Subject);
|
|
173
|
+
return {
|
|
174
|
+
conversationId,
|
|
175
|
+
...(messageId !== undefined ? { messageId } : {}),
|
|
176
|
+
...(time !== undefined ? { time } : {}),
|
|
177
|
+
...(sender !== undefined ? { sender } : {}),
|
|
178
|
+
...(senderEmail !== undefined ? { senderEmail } : {}),
|
|
179
|
+
text,
|
|
180
|
+
...(subject !== undefined ? { subject } : {}),
|
|
181
|
+
...(root !== undefined && root !== messageId ? { replyTo: root } : {}),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** Parse a v2 query response into a page of message hits. Never throws on shape. */
|
|
185
|
+
export function parseQueryResponse(body) {
|
|
186
|
+
const sets = obj(body)?.EntitySets;
|
|
187
|
+
const firstSet = Array.isArray(sets) ? obj(sets[0]) : undefined;
|
|
188
|
+
const resultSets = firstSet?.ResultSets;
|
|
189
|
+
const rs = Array.isArray(resultSets) ? obj(resultSets[0]) : undefined;
|
|
190
|
+
if (rs === undefined)
|
|
191
|
+
return { results: [], moreAvailable: false, unmapped: 0 };
|
|
192
|
+
// A query with no hits has no `Results` key at all (seen live).
|
|
193
|
+
const raw = Array.isArray(rs.Results) ? rs.Results : [];
|
|
194
|
+
const results = [];
|
|
195
|
+
let unmapped = 0;
|
|
196
|
+
for (const r of raw) {
|
|
197
|
+
const m = mapResult(r);
|
|
198
|
+
if (m === undefined)
|
|
199
|
+
unmapped++;
|
|
200
|
+
else
|
|
201
|
+
results.push(m);
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
results,
|
|
205
|
+
...(typeof rs.Total === 'number' ? { total: rs.Total } : {}),
|
|
206
|
+
moreAvailable: rs.MoreResultsAvailable === true,
|
|
207
|
+
unmapped,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
export class SubstrateClient {
|
|
211
|
+
#fetchImpl;
|
|
212
|
+
#configError = null;
|
|
213
|
+
#manager;
|
|
214
|
+
/**
|
|
215
|
+
* When the last capture failed, or a freshly captured token was still
|
|
216
|
+
* refused (401), and how; cleared by a successful capture.
|
|
217
|
+
*/
|
|
218
|
+
#captureFailure = null;
|
|
219
|
+
constructor(opts = {}) {
|
|
220
|
+
const env = opts.env ?? process.env;
|
|
221
|
+
const capture = opts.captureToken ?? captureSubstrateTokenLazily;
|
|
222
|
+
// A receiver-safe wrapper, never the bare global (see `sharepoint.ts`).
|
|
223
|
+
this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
224
|
+
const recapture = async () => {
|
|
225
|
+
try {
|
|
226
|
+
const tokens = toBearerTokens(await capture());
|
|
227
|
+
this.#captureFailure = null;
|
|
228
|
+
return tokens;
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
this.#captureFailure = { at: Date.now(), error };
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
const persistence = createSubstrateTokenCache(env);
|
|
236
|
+
this.#manager = new TokenManager({
|
|
237
|
+
initial: recapture,
|
|
238
|
+
refresh: recapture,
|
|
239
|
+
...(persistence ? { persistence } : {}),
|
|
240
|
+
});
|
|
241
|
+
// Like SharePoint, there is no direct-token env var: the bridge is the only source.
|
|
242
|
+
if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env })) {
|
|
243
|
+
this.#configError = new McpToolError('Substrate search is disabled (no token source).', {
|
|
244
|
+
kind: 'no_credential',
|
|
245
|
+
hint: 'Unset TEAMS_DISABLE_FETCHPROXY so a Substrate token can be captured from a signed-in Teams tab.',
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** Whether a token could be obtained at all (the bridge is not disabled). */
|
|
250
|
+
isConfigured() {
|
|
251
|
+
return this.#configError === null;
|
|
252
|
+
}
|
|
253
|
+
async searchMessages(req, opts = {}) {
|
|
254
|
+
if (this.#configError)
|
|
255
|
+
throw this.#configError;
|
|
256
|
+
const failed = this.#captureFailure;
|
|
257
|
+
if (!opts.force && failed !== null && Date.now() - failed.at < CAPTURE_RETRY_COOLDOWN_MS)
|
|
258
|
+
throw failed.error;
|
|
259
|
+
let text = '';
|
|
260
|
+
const res = await this.#manager.withAuth(async (token) => {
|
|
261
|
+
const r = await fetchBounded(SUBSTRATE_QUERY_URL, {
|
|
262
|
+
method: 'POST',
|
|
263
|
+
headers: {
|
|
264
|
+
authorization: `Bearer ${token}`,
|
|
265
|
+
'content-type': 'application/json',
|
|
266
|
+
accept: 'application/json',
|
|
267
|
+
},
|
|
268
|
+
body: JSON.stringify(buildQueryBody(req)),
|
|
269
|
+
redirect: 'error',
|
|
270
|
+
}, {
|
|
271
|
+
read: 'text',
|
|
272
|
+
maxBytes: MAX_RESPONSE_BYTES,
|
|
273
|
+
service: 'Substrate',
|
|
274
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
275
|
+
fetchImpl: this.#fetchImpl,
|
|
276
|
+
});
|
|
277
|
+
text = r.body;
|
|
278
|
+
return r.res;
|
|
279
|
+
});
|
|
280
|
+
try {
|
|
281
|
+
checkStatus(res.status);
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
// A 401 here is on a token `withAuth` just re-captured: the capture itself
|
|
285
|
+
// is not yielding a usable token. Cool down like a failed capture, so each
|
|
286
|
+
// unforced search does not hold the call for another capture window.
|
|
287
|
+
if (res.status === 401)
|
|
288
|
+
this.#captureFailure = { at: Date.now(), error };
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
return parseQueryResponse(JSON.parse(text));
|
|
293
|
+
}
|
|
294
|
+
catch {
|
|
295
|
+
// Never echo the body: it holds message content.
|
|
296
|
+
throw new McpToolError('Substrate returned a response that is not JSON.', { status: res.status, kind: 'http' });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Map a non-2xx to an `McpToolError` carrying its status. The body is never included. */
|
|
301
|
+
function checkStatus(status) {
|
|
302
|
+
if (status >= 200 && status < 300)
|
|
303
|
+
return;
|
|
304
|
+
if (status === 401) {
|
|
305
|
+
throw new McpToolError('Substrate rejected the search token (401) even after a fresh capture.', {
|
|
306
|
+
status,
|
|
307
|
+
kind: 'credential_rejected',
|
|
308
|
+
hint: 'Run a search in a signed-in Teams tab to mint a fresh Substrate token, then retry.',
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
if (status === 429) {
|
|
312
|
+
throw new McpToolError('Substrate is rate-limiting searches (429).', { status, kind: 'http', hint: 'Wait a minute before retrying.' });
|
|
313
|
+
}
|
|
314
|
+
throw new McpToolError(`Substrate search returned HTTP ${status}.`, {
|
|
315
|
+
status,
|
|
316
|
+
kind: 'http',
|
|
317
|
+
...(status >= 500 ? { hint: 'A Substrate-side failure; retry shortly.' } : {}),
|
|
318
|
+
});
|
|
319
|
+
}
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { mapWithConcurrency, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
|
|
3
|
+
import { conversationSummary, isUserMessage, lastChangeMs, normaliseMessage, } from '../model.js';
|
|
4
|
+
import { isUnreachable } from './confirm.js';
|
|
5
|
+
import { includeHiddenArg } from './listing.js';
|
|
6
|
+
import { enrichTitles } from './titles.js';
|
|
7
|
+
import { wrapApiError } from './errors.js';
|
|
8
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
9
|
+
import { CURSOR_NO_CACHE_DESCRIPTION } from './cursor.js';
|
|
10
|
+
import { DEFAULT_LIMIT, limitArg } from './limit.js';
|
|
11
|
+
import { KIND_FILTERS } from './unread.js';
|
|
12
|
+
const MAX_CONVERSATIONS = 200;
|
|
13
|
+
/** How far back a call with no cursor looks. */
|
|
14
|
+
export const DEFAULT_WINDOW_MS = 86_400_000;
|
|
15
|
+
/**
|
|
16
|
+
* Raw messages read per conversation before giving up; past it the
|
|
17
|
+
* conversation is marked truncated and its count is a lower bound.
|
|
18
|
+
*/
|
|
19
|
+
const MAX_RAW_MESSAGES = 1000;
|
|
20
|
+
/** Messages per page: a conversation that changed usually changed by a few. */
|
|
21
|
+
const PAGE_SIZE = 50;
|
|
22
|
+
/** Conversations read at once. */
|
|
23
|
+
const READ_CONCURRENCY = 4;
|
|
24
|
+
/** `cursor` as handed out: base64url JSON `{ t }`, `t` epoch ms. */
|
|
25
|
+
export function encodeChangesCursor(t) {
|
|
26
|
+
return Buffer.from(JSON.stringify({ t }), 'utf8').toString('base64url');
|
|
27
|
+
}
|
|
28
|
+
function badCursor(cursor) {
|
|
29
|
+
return new McpToolError(`"${cursor}" is not a changes cursor.`, {
|
|
30
|
+
hint: "Pass a previous result's next_cursor unchanged, or an ISO 8601 time such as 2026-10-12T09:00:00Z. " +
|
|
31
|
+
'A message id (digits) is not a changes cursor: pass it to teams_read_conversation as after_message_id.',
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** The epoch ms a `cursor` names: a token from {@link encodeChangesCursor}, or an ISO 8601 time. */
|
|
35
|
+
export function decodeChangesCursor(cursor) {
|
|
36
|
+
if (/^[A-Za-z0-9_-]+$/.test(cursor)) {
|
|
37
|
+
let parsed;
|
|
38
|
+
try {
|
|
39
|
+
parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8'));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
parsed = undefined;
|
|
43
|
+
}
|
|
44
|
+
if (parsed !== undefined) {
|
|
45
|
+
const t = parsed?.t;
|
|
46
|
+
if (typeof t === 'number' && Number.isFinite(t) && t >= 0)
|
|
47
|
+
return t;
|
|
48
|
+
throw badCursor(cursor);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
// Only a string that looks like a date: Date.parse is lenient with words.
|
|
52
|
+
const t = /^\d{4}-\d{2}-\d{2}/.test(cursor) ? Date.parse(cursor) : NaN;
|
|
53
|
+
if (Number.isNaN(t))
|
|
54
|
+
throw badCursor(cursor);
|
|
55
|
+
return t;
|
|
56
|
+
}
|
|
57
|
+
/** A message's last change (epoch ms): its `version`, else its arrival (the id). */
|
|
58
|
+
function changedMs(m) {
|
|
59
|
+
const v = Number(m.version);
|
|
60
|
+
const id = Number(m.id);
|
|
61
|
+
return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
|
|
62
|
+
}
|
|
63
|
+
/** Read one conversation down to `t` and count what arrived after it. */
|
|
64
|
+
async function readChanges(chatsvc, summary, t, me) {
|
|
65
|
+
let capped = false;
|
|
66
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
67
|
+
stopAt: (m) => changedMs(m) <= t,
|
|
68
|
+
max: MAX_RAW_MESSAGES,
|
|
69
|
+
pageSize: PAGE_SIZE,
|
|
70
|
+
onCapped: () => (capped = true),
|
|
71
|
+
});
|
|
72
|
+
const arrived = fetched.filter((m) => Number(m.id) > t);
|
|
73
|
+
const maxSeen = arrived.reduce((n, m) => Math.max(n, Number(m.id)), 0);
|
|
74
|
+
const fresh = arrived
|
|
75
|
+
.filter(isUserMessage)
|
|
76
|
+
.map((m) => normaliseMessage(m, me))
|
|
77
|
+
.filter((m) => m.deleted !== true)
|
|
78
|
+
.sort((a, b) => Number(b.id) - Number(a.id));
|
|
79
|
+
let threads;
|
|
80
|
+
if (summary.kind === 'channel') {
|
|
81
|
+
// Newest first, so threads come in order of their newest new message.
|
|
82
|
+
const byRoot = new Map();
|
|
83
|
+
for (const m of fresh) {
|
|
84
|
+
const rootId = m.replyTo ?? m.id;
|
|
85
|
+
let thread = byRoot.get(rootId);
|
|
86
|
+
if (thread === undefined)
|
|
87
|
+
byRoot.set(rootId, (thread = { root_id: rootId, new_root: false, new_reply_count: 0 }));
|
|
88
|
+
if (m.replyTo === undefined)
|
|
89
|
+
thread.new_root = true;
|
|
90
|
+
else
|
|
91
|
+
thread.new_reply_count++;
|
|
92
|
+
}
|
|
93
|
+
threads = [...byRoot.values()];
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
count: fresh.length,
|
|
97
|
+
fromOthers: fresh.filter((m) => !m.fromMe).length,
|
|
98
|
+
newest: fresh.length > 0 ? Number(fresh[0].id) : 0,
|
|
99
|
+
...(fresh.length > 0 ? { newestTime: fresh[0].time } : {}),
|
|
100
|
+
maxSeen,
|
|
101
|
+
...(threads !== undefined ? { threads } : {}),
|
|
102
|
+
truncated: capped,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export function registerChangesTools(server, { chatsvc }) {
|
|
106
|
+
server.registerTool('teams_get_changes', {
|
|
107
|
+
title: 'Get Teams conversations with new messages',
|
|
108
|
+
description: 'List the chats and channels that got new messages since a cursor, most recent first — counts, not ' +
|
|
109
|
+
'the messages: each with its summary (id, kind, title, team), new_message_count (real messages ' +
|
|
110
|
+
'only — call recordings and other system events, and deleted messages, are not counted), ' +
|
|
111
|
+
'new_from_others_count, newest_time and, for a channel, threads: one { root_id, new_root, ' +
|
|
112
|
+
'new_reply_count } per thread the new messages landed in, including a thread whose root post is ' +
|
|
113
|
+
'older than the cursor, and after_message_id: read the messages it counted with ' +
|
|
114
|
+
'teams_read_conversation({ conversation: <its id>, after_message_id: <its after_message_id> }). ' +
|
|
115
|
+
'Two cursor kinds, not interchangeable: this tool\'s cursor/next_cursor is a time token for ' +
|
|
116
|
+
'teams_get_changes only and is not a message id; after_message_id is a message-id cursor (ids are ' +
|
|
117
|
+
'arrival ms, so it is the cursor time as an id) for teams_read_conversation (or teams_get_unread ' +
|
|
118
|
+
'cursors). Without cursor it looks back 24 hours. next_cursor is an opaque token — pass it back as ' +
|
|
119
|
+
'cursor to get only what arrived since this call (cursor also takes a plain ISO 8601 time). It is ' +
|
|
120
|
+
'at-least-once: a conversation can come back again but none is skipped; it stays at the input ' +
|
|
121
|
+
'time when a read failed. Use the same kinds and include_hidden with a cursor as the call that ' +
|
|
122
|
+
'returned it. Channels hidden in Teams are left out unless include_hidden (then every hidden channel ' +
|
|
123
|
+
'is read, since Teams stops updating their listing); one that is gone or no ' +
|
|
124
|
+
'longer readable (404/403) is skipped and counted in skipped_unreachable; one whose read failed ' +
|
|
125
|
+
'is listed in errors. limit caps the conversations returned; the rest are named, with their ' +
|
|
126
|
+
'new_message_count and after_message_id, in more_conversations, and total_new_messages counts them all. A conversation ' +
|
|
127
|
+
`with more than ${MAX_RAW_MESSAGES} new messages is marked truncated (its count is a lower bound). ` +
|
|
128
|
+
CURSOR_NO_CACHE_DESCRIPTION +
|
|
129
|
+
'This does NOT mark anything read — the user\'s Teams unread badges are unaffected. ' +
|
|
130
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
131
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
132
|
+
inputSchema: {
|
|
133
|
+
cursor: z
|
|
134
|
+
.string()
|
|
135
|
+
.min(1)
|
|
136
|
+
.optional()
|
|
137
|
+
.describe("A previous teams_get_changes result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): " +
|
|
138
|
+
'only messages that arrived after it count. Default: 24 hours ago. Not a message id, and not ' +
|
|
139
|
+
"teams_read_conversation's next_cursor."),
|
|
140
|
+
kinds: z
|
|
141
|
+
.array(z.enum(Object.keys(KIND_FILTERS)))
|
|
142
|
+
.min(1)
|
|
143
|
+
.optional()
|
|
144
|
+
.describe('Only these kinds of conversation (default all): chat = every group, meeting and 1:1 ' +
|
|
145
|
+
'chat; channel; meeting = meeting chats only; oneOnOne = 1:1 chats only.'),
|
|
146
|
+
include_hidden: includeHiddenArg.describe('Also include channels the user has hidden in Teams (default false: Teams shows them nowhere).'),
|
|
147
|
+
limit: limitArg(MAX_CONVERSATIONS, 'conversations', 'most recent activity first kept'),
|
|
148
|
+
},
|
|
149
|
+
}, async ({ cursor, kinds, include_hidden, limit }) => {
|
|
150
|
+
try {
|
|
151
|
+
const t = cursor !== undefined ? decodeChangesCursor(cursor) : Date.now() - DEFAULT_WINDOW_MS;
|
|
152
|
+
const fetched_at = new Date().toISOString();
|
|
153
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
154
|
+
const allowed = new Set((kinds ?? ['chat', 'channel']).flatMap((k) => KIND_FILTERS[k]));
|
|
155
|
+
const lastChange = new Map(raw.map((c) => [c.id, lastChangeMs(c)]));
|
|
156
|
+
// Summaries are built against the FULL listing so a channel can find its team's name. A
|
|
157
|
+
// hidden channel's listing entry stops moving (live: days stale while posts arrived), so
|
|
158
|
+
// with include_hidden every hidden channel is read; otherwise the listing nominates.
|
|
159
|
+
const candidates = raw
|
|
160
|
+
.map((c) => conversationSummary(c, me, raw))
|
|
161
|
+
.filter((s) => allowed.has(s.kind))
|
|
162
|
+
.filter((s) => (s.hidden === true ? include_hidden === true : (lastChange.get(s.id) ?? 0) > t));
|
|
163
|
+
const results = await mapWithConcurrency(candidates, READ_CONCURRENCY, async (summary) => {
|
|
164
|
+
try {
|
|
165
|
+
return { kind: 'read', read: await readChanges(chatsvc, summary, t, me) };
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
let skipped_unreachable = 0;
|
|
172
|
+
let maxSeen = t;
|
|
173
|
+
let anyRead = false;
|
|
174
|
+
const changed = [];
|
|
175
|
+
const failed = [];
|
|
176
|
+
results.forEach((r, i) => {
|
|
177
|
+
if (r.kind === 'unreachable')
|
|
178
|
+
skipped_unreachable++;
|
|
179
|
+
else if (r.kind === 'failed')
|
|
180
|
+
failed.push({ summary: candidates[i], error: r.error });
|
|
181
|
+
else {
|
|
182
|
+
anyRead = true;
|
|
183
|
+
maxSeen = Math.max(maxSeen, r.read.maxSeen);
|
|
184
|
+
if (r.read.count > 0)
|
|
185
|
+
changed.push({ summary: candidates[i], read: r.read });
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
// Every read failed: a failure of the call (a revoked token, a rate limit), not of one conversation.
|
|
189
|
+
if (failed.length > 0 && !anyRead)
|
|
190
|
+
throw failed[0].error;
|
|
191
|
+
changed.sort((a, b) => b.read.newest - a.read.newest);
|
|
192
|
+
// Never past the newest change the listing saw: a quiet conversation's mid-call message stays ahead.
|
|
193
|
+
const listed = Math.max(t, ...[...lastChange.values()].map((n) => n ?? 0));
|
|
194
|
+
const next = failed.length > 0 ? t : Math.min(maxSeen, listed);
|
|
195
|
+
const cap = limit ?? DEFAULT_LIMIT;
|
|
196
|
+
const shown = changed.slice(0, cap);
|
|
197
|
+
const rest = changed.slice(cap);
|
|
198
|
+
const titled = await enrichTitles(chatsvc, raw, me, [
|
|
199
|
+
...shown.map((c) => c.summary),
|
|
200
|
+
...rest.map((c) => c.summary),
|
|
201
|
+
...failed.map((f) => f.summary),
|
|
202
|
+
]);
|
|
203
|
+
// The read_conversation hand-off: a message id is its arrival ms, so the cursor time as an id
|
|
204
|
+
// stops that read exactly where this one stopped counting.
|
|
205
|
+
const after_message_id = String(Math.floor(t));
|
|
206
|
+
const conversations = shown.map(({ read }, i) => ({
|
|
207
|
+
conversation: titled[i],
|
|
208
|
+
new_message_count: read.count,
|
|
209
|
+
new_from_others_count: read.fromOthers,
|
|
210
|
+
...(read.newestTime !== undefined ? { newest_time: read.newestTime } : {}),
|
|
211
|
+
after_message_id,
|
|
212
|
+
...(read.threads !== undefined ? { threads: read.threads } : {}),
|
|
213
|
+
...(read.truncated ? { truncated: true } : {}),
|
|
214
|
+
}));
|
|
215
|
+
const more = rest.map(({ read }, i) => ({
|
|
216
|
+
id: titled[shown.length + i].id,
|
|
217
|
+
title: titled[shown.length + i].title,
|
|
218
|
+
new_message_count: read.count,
|
|
219
|
+
after_message_id,
|
|
220
|
+
}));
|
|
221
|
+
const errors = failed.map((f, i) => ({
|
|
222
|
+
conversation: titled[changed.length + i],
|
|
223
|
+
error: wrapApiError(f.error, 'read this conversation').message,
|
|
224
|
+
}));
|
|
225
|
+
return untrustedResult({
|
|
226
|
+
since: new Date(t).toISOString(),
|
|
227
|
+
total_new_messages: changed.reduce((n, c) => n + c.read.count, 0),
|
|
228
|
+
conversations,
|
|
229
|
+
...(more.length > 0 ? { more_conversations: more } : {}),
|
|
230
|
+
skipped_unreachable,
|
|
231
|
+
...(errors.length > 0 ? { errors } : {}),
|
|
232
|
+
next_cursor: next === t && cursor !== undefined ? cursor : encodeChangesCursor(next),
|
|
233
|
+
next_cursor_time: new Date(next).toISOString(),
|
|
234
|
+
fetched_at,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
throw wrapApiError(err, 'get changed conversations');
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
package/dist/tools/channels.js
CHANGED
|
@@ -2,7 +2,7 @@ import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
|
2
2
|
import { wrapApiError } from './errors.js';
|
|
3
3
|
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
4
4
|
import { limitArg, trimRows } from './limit.js';
|
|
5
|
-
import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
|
|
5
|
+
import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, MATCH_REASON_DESCRIPTION, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
|
|
6
6
|
/** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
|
|
7
7
|
const MAX_CHANNELS = 500;
|
|
8
8
|
/**
|
|
@@ -38,7 +38,9 @@ export function registerChannelTools(server, { chatsvc }) {
|
|
|
38
38
|
'keeps only channels whose newest unread post is from the last 14 days (since_days widens ' +
|
|
39
39
|
'it); older ones are counted in older_unread_skipped, not listed. ' +
|
|
40
40
|
UNREAD_HINT_DESCRIPTION +
|
|
41
|
-
' Listing never marks anything read. query matches the channel title or
|
|
41
|
+
' Listing never marks anything read (teams_mark_read does). query matches the channel title, team name or last-message preview. ' +
|
|
42
|
+
MATCH_REASON_DESCRIPTION +
|
|
43
|
+
' ' +
|
|
42
44
|
FAVORITES_DESCRIPTION +
|
|
43
45
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
44
46
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
@@ -46,7 +48,7 @@ export function registerChannelTools(server, { chatsvc }) {
|
|
|
46
48
|
unread_only: unreadOnlyArg,
|
|
47
49
|
since_days: listSinceDaysArg,
|
|
48
50
|
include_hidden: includeHiddenArg,
|
|
49
|
-
query: queryArg('channel title or
|
|
51
|
+
query: queryArg('channel title, team name or last-message preview'),
|
|
50
52
|
limit: limitArg(MAX_CHANNELS, 'channels', 'favorites and pinned first, then by team and title, kept'),
|
|
51
53
|
},
|
|
52
54
|
}, async ({ unread_only, include_hidden, since_days, query, limit }) => {
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `teams_list_chats`' opt-in `search_messages`: a query matched against what
|
|
3
|
+
* was said in each chat, not only what the chat is called.
|
|
4
|
+
*
|
|
5
|
+
* The chat service has no search call this server can reach, so each chat no
|
|
6
|
+
* name or last-message preview matched is read here — one page of its
|
|
7
|
+
* {@link SEARCH_FETCH_MESSAGES} most recent messages, {@link SEARCH_CONCURRENCY}
|
|
8
|
+
* chats at a time, the same bounded fan-out `titles.ts` uses. Only messages a
|
|
9
|
+
* person wrote count (not deleted ones or system events), matched on their
|
|
10
|
+
* plain text. A read that fails leaves its chat out and is counted — it never
|
|
11
|
+
* fails the call. Nothing is cached: a search wants the newest messages.
|
|
12
|
+
*/
|
|
13
|
+
import { mapWithConcurrency } from '@chrischall/mcp-utils';
|
|
14
|
+
import { isUserMessage, normaliseMessage } from '../model.js';
|
|
15
|
+
/** Recent messages read per chat — one page. */
|
|
16
|
+
export const SEARCH_FETCH_MESSAGES = 50;
|
|
17
|
+
/** Chats read at once. */
|
|
18
|
+
export const SEARCH_CONCURRENCY = 4;
|
|
19
|
+
/** Longest matched-message text returned, centred on the match. */
|
|
20
|
+
const SNIPPET_CHARS = 200;
|
|
21
|
+
/** Context kept before the match when the text has to be cut. */
|
|
22
|
+
const SNIPPET_LEAD = 60;
|
|
23
|
+
/**
|
|
24
|
+
* Read the recent messages of each chat in `ids` and keep, per chat, the
|
|
25
|
+
* newest whose text contains `query` (case-insensitive).
|
|
26
|
+
*/
|
|
27
|
+
export async function searchRecentMessages(chatsvc, me, ids, query) {
|
|
28
|
+
const q = query.trim().toLowerCase();
|
|
29
|
+
const hits = new Map();
|
|
30
|
+
let failed = 0;
|
|
31
|
+
if (q === '')
|
|
32
|
+
return { hits, failed };
|
|
33
|
+
await mapWithConcurrency([...new Set(ids)], SEARCH_CONCURRENCY, async (id) => {
|
|
34
|
+
let messages;
|
|
35
|
+
try {
|
|
36
|
+
messages = await chatsvc.getMessages(id, { max: SEARCH_FETCH_MESSAGES, pageSize: SEARCH_FETCH_MESSAGES });
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
failed++;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
// Served newest first, so the first match is the newest.
|
|
43
|
+
for (const m of messages) {
|
|
44
|
+
if (!isUserMessage(m))
|
|
45
|
+
continue;
|
|
46
|
+
const n = normaliseMessage(m, me);
|
|
47
|
+
if (n.deleted)
|
|
48
|
+
continue;
|
|
49
|
+
const at = n.text.toLowerCase().indexOf(q);
|
|
50
|
+
if (at === -1)
|
|
51
|
+
continue;
|
|
52
|
+
hits.set(id, { id: n.id, time: n.time, sender: n.sender, text: snippet(n.text, at) });
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
return { hits, failed };
|
|
57
|
+
}
|
|
58
|
+
/** `text` whole when short, else a window of it that starts a little before index `at`. */
|
|
59
|
+
function snippet(text, at) {
|
|
60
|
+
if (text.length <= SNIPPET_CHARS)
|
|
61
|
+
return text;
|
|
62
|
+
const start = Math.max(0, Math.min(at - SNIPPET_LEAD, text.length - SNIPPET_CHARS));
|
|
63
|
+
const end = start + SNIPPET_CHARS;
|
|
64
|
+
return `${start > 0 ? '…' : ''}${text.slice(start, end)}${end < text.length ? '…' : ''}`;
|
|
65
|
+
}
|