@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,426 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { mapWithConcurrency, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
|
|
3
|
+
import { conversationKind, conversationSummary, isUserMessage, newestActivityMs, normaliseMessage, } from '../model.js';
|
|
4
|
+
import { arrivalMs, resolveListed } from './conversation.js';
|
|
5
|
+
import { CONFIRM_CONCURRENCY, isUnreachable } from './confirm.js';
|
|
6
|
+
import { enrichTitles } from './titles.js';
|
|
7
|
+
import { wrapApiError } from './errors.js';
|
|
8
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
9
|
+
const DEFAULT_LIMIT = 25;
|
|
10
|
+
const MAX_LIMIT = 200;
|
|
11
|
+
/** The window searched when `since` is not given. */
|
|
12
|
+
export const DEFAULT_SINCE_DAYS = 30;
|
|
13
|
+
const DAY_MS = 86_400_000;
|
|
14
|
+
/**
|
|
15
|
+
* Conversations read per call, most recently active first, unless
|
|
16
|
+
* `max_conversations` says otherwise. Live 2026-10-12, 100 reads took ~15s;
|
|
17
|
+
* the listing had ~500 conversations with some activity in 30 days, most of it
|
|
18
|
+
* system events (call recordings, member changes) in channels and meeting chats.
|
|
19
|
+
*/
|
|
20
|
+
export const DEFAULT_SCANNED_CONVERSATIONS = 100;
|
|
21
|
+
export const MAX_SCANNED_CONVERSATIONS = 500;
|
|
22
|
+
/**
|
|
23
|
+
* Raw messages read per conversation before giving up on it (5 pages of 200).
|
|
24
|
+
* The real bound is the `since` cutoff; this caps one very busy conversation.
|
|
25
|
+
*/
|
|
26
|
+
const MAX_RAW_PER_CONVERSATION = 1000;
|
|
27
|
+
/** Substrate results asked for per request. */
|
|
28
|
+
export const SUBSTRATE_PAGE_SIZE = 50;
|
|
29
|
+
/** Substrate pages one call reads at most (so 500 results before filtering). */
|
|
30
|
+
export const MAX_SUBSTRATE_PAGES = 10;
|
|
31
|
+
const MODES = ['auto', 'substrate', 'scan'];
|
|
32
|
+
/**
|
|
33
|
+
* The query's terms, lowercased: whitespace-separated words, a `"quoted
|
|
34
|
+
* phrase"` kept whole.
|
|
35
|
+
*/
|
|
36
|
+
function queryTerms(query) {
|
|
37
|
+
const terms = [];
|
|
38
|
+
for (const [, phrase, word] of query.toLowerCase().matchAll(/"([^"]*)"|(\S+)/g)) {
|
|
39
|
+
const t = (phrase ?? word ?? '').replace(/"/g, '').trim();
|
|
40
|
+
if (t !== '')
|
|
41
|
+
terms.push(t);
|
|
42
|
+
}
|
|
43
|
+
return terms;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Whether `text` matches `query`: every term (word or `"quoted phrase"`)
|
|
47
|
+
* appears in it, in any order, ignoring case. A query with no terms matches
|
|
48
|
+
* nothing.
|
|
49
|
+
*/
|
|
50
|
+
export function matchesQuery(text, query) {
|
|
51
|
+
const terms = queryTerms(query);
|
|
52
|
+
if (terms.length === 0)
|
|
53
|
+
return false;
|
|
54
|
+
const haystack = text.toLowerCase();
|
|
55
|
+
return terms.every((t) => haystack.includes(t));
|
|
56
|
+
}
|
|
57
|
+
function hitMessage(m) {
|
|
58
|
+
const { attachments: _a, reactions: _r, deleted: _d, ...rest } = m;
|
|
59
|
+
return rest;
|
|
60
|
+
}
|
|
61
|
+
function hitConversation(s) {
|
|
62
|
+
return { id: s.id, title: s.title, kind: s.kind, ...(s.team !== undefined ? { team: s.team } : {}) };
|
|
63
|
+
}
|
|
64
|
+
export function registerSearchTools(server, { chatsvc, substrate }) {
|
|
65
|
+
server.registerTool('teams_search_messages', {
|
|
66
|
+
title: 'Search Teams messages',
|
|
67
|
+
description: 'Find messages by text across the chats and channels the signed-in user is in. Hits come ' +
|
|
68
|
+
'newest first, each with its conversation (id, title, kind, team) and the message (id, time ' +
|
|
69
|
+
'ISO 8601, sender, fromMe (scan only), text, subject, replyTo for a channel reply); read a hit in context ' +
|
|
70
|
+
'with teams_read_conversation. conversation narrows to one chat or channel (id or name); from ' +
|
|
71
|
+
'keeps messages whose sender display name contains it; since (ISO 8601) sets how far back to ' +
|
|
72
|
+
`look (default the last ${DEFAULT_SINCE_DAYS} days); limit caps the hits (default ` +
|
|
73
|
+
`${DEFAULT_LIMIT}, max ${MAX_LIMIT}; total_hits and truncated say when there were more). ` +
|
|
74
|
+
'source says which path answered. mode "auto" (default) uses Teams\' own search (Microsoft ' +
|
|
75
|
+
'Substrate: matched the way the Teams search box matches — words ANDed with stemming, "quoted ' +
|
|
76
|
+
'phrases", OR — and fast; conversation and since apply to it too; its text is a plain-text preview ' +
|
|
77
|
+
'of up to ~255 characters, marked excerpt: true, and its hits carry no fromMe) and falls back to a ' +
|
|
78
|
+
'scan, with fallback_reason, when Substrate is unavailable or fails — its token is captured from a Teams tab the first time, so a first ' +
|
|
79
|
+
'search may need you to run any search in the Teams search box. mode "substrate" uses only ' +
|
|
80
|
+
'Substrate (an error rather than a fallback); mode "scan" only scans. The SCAN requires every ' +
|
|
81
|
+
'word of query to appear in the message text (any order, ignoring case; "quoted words" match ' +
|
|
82
|
+
`as a phrase) and reads the ${DEFAULT_SCANNED_CONVERSATIONS} (max_conversations, up to ` +
|
|
83
|
+
`${MAX_SCANNED_CONVERSATIONS}) most recently active conversations with activity since the ` +
|
|
84
|
+
'cutoff back to it (channels hidden in Teams are skipped unless named); scan reports what was ' +
|
|
85
|
+
'read and what the bounds left out — a busy window can take a while, so narrow with ' +
|
|
86
|
+
'conversation or since when you can. Deleted messages and system events never match. This ' +
|
|
87
|
+
'does NOT mark anything read.' +
|
|
88
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
89
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
90
|
+
inputSchema: {
|
|
91
|
+
query: z
|
|
92
|
+
.string()
|
|
93
|
+
.refine((s) => queryTerms(s).length > 0, { message: 'query must contain a word to search for' })
|
|
94
|
+
.describe('Words to find in the message text, ignoring case. Substrate (the default) matches the way the ' +
|
|
95
|
+
'Teams search box does (words ANDed with stemming, "quoted phrases", OR). The scan requires ' +
|
|
96
|
+
'every word to appear verbatim, any order; words in double quotes match as one phrase.'),
|
|
97
|
+
conversation: z
|
|
98
|
+
.string()
|
|
99
|
+
.min(1)
|
|
100
|
+
.optional()
|
|
101
|
+
.describe('Search only this chat or channel: its id ("48:notes", "notes" or "self" for the self-chat), ' +
|
|
102
|
+
"or a case-insensitive substring of its title, channel name, team name or an untitled chat's " +
|
|
103
|
+
'participant names (it must name exactly one).'),
|
|
104
|
+
from: z
|
|
105
|
+
.string()
|
|
106
|
+
.min(1)
|
|
107
|
+
.optional()
|
|
108
|
+
.describe("Only messages whose sender's display name contains this, ignoring case."),
|
|
109
|
+
since: z
|
|
110
|
+
.string()
|
|
111
|
+
.refine((s) => !Number.isNaN(Date.parse(s)), { message: 'since must be an ISO 8601 date-time' })
|
|
112
|
+
.optional()
|
|
113
|
+
.describe(`Only messages at or after this ISO 8601 date-time (default ${DEFAULT_SINCE_DAYS} days ago). ` +
|
|
114
|
+
'An older since makes a scan search further back and take longer.'),
|
|
115
|
+
limit: z
|
|
116
|
+
.number()
|
|
117
|
+
.int()
|
|
118
|
+
.min(1)
|
|
119
|
+
.max(MAX_LIMIT)
|
|
120
|
+
.optional()
|
|
121
|
+
.describe(`Maximum hits to return, newest kept (default ${DEFAULT_LIMIT}, max ${MAX_LIMIT}).`),
|
|
122
|
+
max_conversations: z
|
|
123
|
+
.number()
|
|
124
|
+
.int()
|
|
125
|
+
.min(1)
|
|
126
|
+
.max(MAX_SCANNED_CONVERSATIONS)
|
|
127
|
+
.optional()
|
|
128
|
+
.describe(`Scan only: most conversations to read, most recently active first (default ${DEFAULT_SCANNED_CONVERSATIONS}, ` +
|
|
129
|
+
`max ${MAX_SCANNED_CONVERSATIONS}). More finds hits in quieter conversations but takes longer ` +
|
|
130
|
+
'(roughly 15s per 100).'),
|
|
131
|
+
mode: z
|
|
132
|
+
.enum(MODES)
|
|
133
|
+
.optional()
|
|
134
|
+
.describe('"auto" (default): Teams\' own search (Substrate), falling back to a scan when it is ' +
|
|
135
|
+
'unavailable or fails. "substrate": Substrate only, failing instead of falling back. ' +
|
|
136
|
+
'"scan": the client-side scan only.'),
|
|
137
|
+
},
|
|
138
|
+
}, async ({ query, conversation, from, since, limit, max_conversations, mode }) => {
|
|
139
|
+
try {
|
|
140
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
141
|
+
const cutoff = since !== undefined ? Date.parse(since) : Date.now() - DEFAULT_SINCE_DAYS * DAY_MS;
|
|
142
|
+
const target = conversation !== undefined ? await resolveListed(chatsvc, raw, me, conversation, 'search') : undefined;
|
|
143
|
+
const args = {
|
|
144
|
+
query,
|
|
145
|
+
...(target !== undefined ? { target } : {}),
|
|
146
|
+
...(from !== undefined ? { fromLc: from.trim().toLowerCase() } : {}),
|
|
147
|
+
cutoff,
|
|
148
|
+
cap: limit ?? DEFAULT_LIMIT,
|
|
149
|
+
};
|
|
150
|
+
const m = mode ?? 'auto';
|
|
151
|
+
let fallbackReason;
|
|
152
|
+
if (m !== 'scan') {
|
|
153
|
+
const unavailable = substrate === undefined
|
|
154
|
+
? 'Substrate search is not available in this server.'
|
|
155
|
+
: !substrate.isConfigured()
|
|
156
|
+
? 'Substrate search is disabled: TEAMS_DISABLE_FETCHPROXY is set, and the browser bridge is its only token source.'
|
|
157
|
+
: undefined;
|
|
158
|
+
if (unavailable !== undefined || substrate === undefined) {
|
|
159
|
+
const reason = unavailable ?? 'Substrate search is not available in this server.';
|
|
160
|
+
if (m === 'substrate') {
|
|
161
|
+
throw new McpToolError(reason, { kind: 'no_credential', hint: 'Use mode "auto" or "scan" to search by scanning instead.' });
|
|
162
|
+
}
|
|
163
|
+
fallbackReason = reason;
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
try {
|
|
167
|
+
return untrustedResult({
|
|
168
|
+
query,
|
|
169
|
+
source: 'substrate',
|
|
170
|
+
...(await substrateSearch(substrate, chatsvc, raw, me, args, m === 'substrate')),
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
catch (err) {
|
|
174
|
+
if (m === 'substrate')
|
|
175
|
+
throw err;
|
|
176
|
+
fallbackReason = wrapApiError(err, 'search with Substrate').message;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return untrustedResult({
|
|
181
|
+
query,
|
|
182
|
+
source: 'scan',
|
|
183
|
+
...(fallbackReason !== undefined ? { fallback_reason: fallbackReason } : {}),
|
|
184
|
+
...(await scanSearch(chatsvc, raw, me, args, max_conversations)),
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
throw wrapApiError(err, 'search messages');
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/** A conversation's summary from the listing, or a bare one named by its id when the listing lacks it. */
|
|
193
|
+
function summaryFor(id, listed, raw, me) {
|
|
194
|
+
const c = listed.get(id);
|
|
195
|
+
if (c !== undefined)
|
|
196
|
+
return conversationSummary(c, me, raw);
|
|
197
|
+
return { id, kind: conversationKind({ id }), title: id, unread: false, unread_confirmed: false };
|
|
198
|
+
}
|
|
199
|
+
/** The Substrate path: page through Teams' own search, filter, and map hits to the scan's shape. */
|
|
200
|
+
async function substrateSearch(substrate, chatsvc, raw, me, { query, target, fromLc, cutoff, cap }, force) {
|
|
201
|
+
const found = [];
|
|
202
|
+
let pages = 0;
|
|
203
|
+
let resultsRead = 0;
|
|
204
|
+
let filteredOut = 0;
|
|
205
|
+
let unmapped = 0;
|
|
206
|
+
let total;
|
|
207
|
+
let more = false;
|
|
208
|
+
for (let offset = 0; pages < MAX_SUBSTRATE_PAGES; offset += SUBSTRATE_PAGE_SIZE) {
|
|
209
|
+
const page = await substrate.searchMessages({
|
|
210
|
+
query,
|
|
211
|
+
from: offset,
|
|
212
|
+
size: SUBSTRATE_PAGE_SIZE,
|
|
213
|
+
// Both restrictions are verified server-side; the checks below stay as a backstop.
|
|
214
|
+
...(target !== undefined ? { conversationId: target.id } : {}),
|
|
215
|
+
sentAfter: cutoff,
|
|
216
|
+
}, force ? { force } : undefined);
|
|
217
|
+
pages++;
|
|
218
|
+
resultsRead += page.results.length;
|
|
219
|
+
unmapped += page.unmapped;
|
|
220
|
+
total ??= page.total;
|
|
221
|
+
more = page.moreAvailable;
|
|
222
|
+
let anyInWindow = false;
|
|
223
|
+
for (const r of page.results) {
|
|
224
|
+
const at = r.time !== undefined ? Date.parse(r.time) : NaN;
|
|
225
|
+
if (Number.isFinite(at) && at < cutoff) {
|
|
226
|
+
filteredOut++;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
// An undated hit counts as inside the window: Substrate returned it, and dropping it would hide it.
|
|
230
|
+
anyInWindow = true;
|
|
231
|
+
if (target !== undefined && r.conversationId !== target.id)
|
|
232
|
+
filteredOut++;
|
|
233
|
+
else if (fromLc !== undefined && !(r.sender ?? '').toLowerCase().includes(fromLc))
|
|
234
|
+
filteredOut++;
|
|
235
|
+
else
|
|
236
|
+
found.push({ hit: r, at });
|
|
237
|
+
}
|
|
238
|
+
// Newest first, so a page wholly before the cutoff means everything after it is too.
|
|
239
|
+
if (!more || page.results.length === 0 || found.length > cap || !anyInWindow)
|
|
240
|
+
break;
|
|
241
|
+
}
|
|
242
|
+
found.sort((a, b) => (Number.isFinite(b.at) ? b.at : 0) - (Number.isFinite(a.at) ? a.at : 0));
|
|
243
|
+
const kept = found.slice(0, cap);
|
|
244
|
+
const listed = new Map(raw.map((c) => [c.id, c]));
|
|
245
|
+
const summaries = [...new Map(kept.map(({ hit }) => [hit.conversationId, summaryFor(hit.conversationId, listed, raw, me)])).values()];
|
|
246
|
+
// Only listed conversations are titled (an unlisted one has no listing entry to title from).
|
|
247
|
+
const titled = new Map((await enrichTitles(chatsvc, raw, me, summaries.filter((s) => listed.has(s.id)))).map((s) => [s.id, s]));
|
|
248
|
+
const bySummary = new Map(summaries.map((s) => [s.id, titled.get(s.id) ?? s]));
|
|
249
|
+
const hits = kept.map(({ hit }) => ({
|
|
250
|
+
conversation: hitConversation(bySummary.get(hit.conversationId) ?? summaryFor(hit.conversationId, listed, raw, me)),
|
|
251
|
+
message: {
|
|
252
|
+
...(hit.messageId !== undefined ? { id: hit.messageId } : {}),
|
|
253
|
+
...(hit.time !== undefined ? { time: hit.time } : {}),
|
|
254
|
+
sender: hit.sender ?? '',
|
|
255
|
+
// No fromMe: a Substrate hit names its sender by display name and SMTP address only.
|
|
256
|
+
text: hit.text,
|
|
257
|
+
excerpt: true,
|
|
258
|
+
...(hit.subject !== undefined ? { subject: hit.subject } : {}),
|
|
259
|
+
...(hit.replyTo !== undefined ? { replyTo: hit.replyTo } : {}),
|
|
260
|
+
},
|
|
261
|
+
}));
|
|
262
|
+
// Exact when Substrate ran out; otherwise its own (approximate) count, which
|
|
263
|
+
// only means anything when nothing was filtered out of what it returned.
|
|
264
|
+
const totalHits = more && filteredOut === 0 && total !== undefined ? Math.max(total, found.length) : found.length;
|
|
265
|
+
const sinceIso = new Date(cutoff).toISOString();
|
|
266
|
+
const pageCapped = pages >= MAX_SUBSTRATE_PAGES && more && found.length <= cap;
|
|
267
|
+
return {
|
|
268
|
+
total_hits: totalHits,
|
|
269
|
+
hits,
|
|
270
|
+
...(totalHits > kept.length
|
|
271
|
+
? {
|
|
272
|
+
truncated: {
|
|
273
|
+
total: totalHits,
|
|
274
|
+
returned: kept.length,
|
|
275
|
+
hint: `Only the newest ${kept.length} hits were returned; pass a larger limit (max ${MAX_LIMIT}) or narrow with conversation, from or since.`,
|
|
276
|
+
},
|
|
277
|
+
}
|
|
278
|
+
: {}),
|
|
279
|
+
substrate: {
|
|
280
|
+
since: sinceIso,
|
|
281
|
+
pages_read: pages,
|
|
282
|
+
results_read: resultsRead,
|
|
283
|
+
results_filtered_out: filteredOut,
|
|
284
|
+
...(unmapped > 0 ? { results_unmapped: unmapped } : {}),
|
|
285
|
+
more_available: more,
|
|
286
|
+
...(pageCapped
|
|
287
|
+
? {
|
|
288
|
+
hint: `Read the first ${MAX_SUBSTRATE_PAGES * SUBSTRATE_PAGE_SIZE} Substrate results and stopped; ` +
|
|
289
|
+
'narrow with conversation, from or a later since, or a more specific query.',
|
|
290
|
+
}
|
|
291
|
+
: {}),
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
/** The scan path: read the most recently active conversations back to the cutoff and match locally. */
|
|
296
|
+
async function scanSearch(chatsvc, raw, me, { query, target, fromLc, cutoff, cap }, maxConversations) {
|
|
297
|
+
// The conversations to read: the one named, else every one with activity
|
|
298
|
+
// inside the window, most recent first, hidden channels left out.
|
|
299
|
+
let targets;
|
|
300
|
+
let outsideWindow = 0;
|
|
301
|
+
if (target !== undefined) {
|
|
302
|
+
targets = [target];
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
const inWindow = [];
|
|
306
|
+
// Only what the listing carries: the self-chat is searched when Teams lists it, or when named.
|
|
307
|
+
for (const c of raw) {
|
|
308
|
+
const summary = conversationSummary(c, me, raw);
|
|
309
|
+
if (summary.hidden === true)
|
|
310
|
+
continue;
|
|
311
|
+
const newest = newestActivityMs(c);
|
|
312
|
+
// A conversation the listing gives no time for is read anyway, last.
|
|
313
|
+
if (newest !== undefined && newest < cutoff)
|
|
314
|
+
outsideWindow++;
|
|
315
|
+
else
|
|
316
|
+
inWindow.push({ summary, newest: newest ?? 0 });
|
|
317
|
+
}
|
|
318
|
+
inWindow.sort((a, b) => b.newest - a.newest);
|
|
319
|
+
targets = inWindow.map((c) => c.summary);
|
|
320
|
+
}
|
|
321
|
+
const maxScanned = maxConversations ?? DEFAULT_SCANNED_CONVERSATIONS;
|
|
322
|
+
const scanned = targets.slice(0, maxScanned);
|
|
323
|
+
const notScanned = targets.length - scanned.length;
|
|
324
|
+
const reads = await mapWithConcurrency(scanned, CONFIRM_CONCURRENCY, async (summary) => {
|
|
325
|
+
let capped = false;
|
|
326
|
+
try {
|
|
327
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
328
|
+
stopAt: (m) => {
|
|
329
|
+
const at = arrivalMs(m);
|
|
330
|
+
return Number.isFinite(at) && at < cutoff;
|
|
331
|
+
},
|
|
332
|
+
max: MAX_RAW_PER_CONVERSATION,
|
|
333
|
+
onCapped: () => (capped = true),
|
|
334
|
+
});
|
|
335
|
+
const hits = fetched.filter((m) => {
|
|
336
|
+
if (!isUserMessage(m))
|
|
337
|
+
return false;
|
|
338
|
+
const n = normaliseMessage(m, me);
|
|
339
|
+
if (n.deleted)
|
|
340
|
+
return false;
|
|
341
|
+
if (fromLc !== undefined && !n.sender.toLowerCase().includes(fromLc))
|
|
342
|
+
return false;
|
|
343
|
+
return matchesQuery(n.subject !== undefined ? `${n.subject}\n${n.text}` : n.text, query);
|
|
344
|
+
});
|
|
345
|
+
return { kind: 'read', hits, seen: fetched.length, capped };
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
const found = [];
|
|
352
|
+
const failed = [];
|
|
353
|
+
const partial = [];
|
|
354
|
+
let unreachable = 0;
|
|
355
|
+
let messagesScanned = 0;
|
|
356
|
+
let anyRead = false;
|
|
357
|
+
reads.forEach((r, i) => {
|
|
358
|
+
const summary = scanned[i];
|
|
359
|
+
if (r.kind === 'unreachable')
|
|
360
|
+
unreachable++;
|
|
361
|
+
else if (r.kind === 'failed')
|
|
362
|
+
failed.push({ summary, error: r.error });
|
|
363
|
+
else {
|
|
364
|
+
anyRead = true;
|
|
365
|
+
messagesScanned += r.seen;
|
|
366
|
+
if (r.capped)
|
|
367
|
+
partial.push(summary);
|
|
368
|
+
for (const m of r.hits)
|
|
369
|
+
found.push({ summary, message: normaliseMessage(m, me), at: arrivalMs(m) });
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
// Every read failing is a failure of the call (a revoked token, a rate limit), not of one conversation.
|
|
373
|
+
if (failed.length > 0 && !anyRead)
|
|
374
|
+
throw failed[0].error;
|
|
375
|
+
found.sort((a, b) => (Number.isFinite(b.at) ? b.at : 0) - (Number.isFinite(a.at) ? a.at : 0));
|
|
376
|
+
const kept = found.slice(0, cap);
|
|
377
|
+
// Only conversations that are returned are titled (an untitled chat's title costs a read).
|
|
378
|
+
const named = [...new Map([...kept.map((h) => h.summary), ...partial, ...failed.map((f) => f.summary)].map((s) => [s.id, s])).values()];
|
|
379
|
+
const titled = new Map((await enrichTitles(chatsvc, raw, me, named)).map((s) => [s.id, s]));
|
|
380
|
+
const final = (s) => titled.get(s.id) ?? s;
|
|
381
|
+
const hits = kept.map((h) => ({ conversation: hitConversation(final(h.summary)), message: hitMessage(h.message) }));
|
|
382
|
+
const sinceIso = new Date(cutoff).toISOString();
|
|
383
|
+
const leftOut = notScanned > 0 || partial.length > 0;
|
|
384
|
+
return {
|
|
385
|
+
total_hits: found.length,
|
|
386
|
+
hits,
|
|
387
|
+
...(found.length > kept.length
|
|
388
|
+
? {
|
|
389
|
+
truncated: {
|
|
390
|
+
total: found.length,
|
|
391
|
+
returned: kept.length,
|
|
392
|
+
hint: `Only the newest ${kept.length} of ${found.length} hits were returned; pass a larger limit (max ${MAX_LIMIT}) or narrow with conversation, from or since.`,
|
|
393
|
+
},
|
|
394
|
+
}
|
|
395
|
+
: {}),
|
|
396
|
+
scan: {
|
|
397
|
+
method: 'client_scan',
|
|
398
|
+
since: sinceIso,
|
|
399
|
+
conversations_scanned: scanned.length,
|
|
400
|
+
conversations_outside_window: outsideWindow,
|
|
401
|
+
conversations_not_scanned: notScanned,
|
|
402
|
+
messages_scanned: messagesScanned,
|
|
403
|
+
skipped_unreachable: unreachable,
|
|
404
|
+
...(partial.length > 0 ? { partially_scanned: partial.map((s) => ({ id: s.id, title: final(s).title })) } : {}),
|
|
405
|
+
...(leftOut
|
|
406
|
+
? {
|
|
407
|
+
hint: (notScanned > 0
|
|
408
|
+
? `${notScanned} less recently active conversation${notScanned === 1 ? ' was' : 's were'} not scanned (max_conversations ${maxScanned}; up to ${MAX_SCANNED_CONVERSATIONS}). `
|
|
409
|
+
: '') +
|
|
410
|
+
(partial.length > 0
|
|
411
|
+
? `${partial.length} conversation${partial.length === 1 ? ' was' : 's were'} only read back ${MAX_RAW_PER_CONVERSATION} messages, short of ${sinceIso}. `
|
|
412
|
+
: '') +
|
|
413
|
+
'Raise max_conversations, or narrow with conversation or a later since, to search everything in range.',
|
|
414
|
+
}
|
|
415
|
+
: {}),
|
|
416
|
+
},
|
|
417
|
+
...(failed.length > 0
|
|
418
|
+
? {
|
|
419
|
+
errors: failed.map((f) => ({
|
|
420
|
+
conversation: hitConversation(final(f.summary)),
|
|
421
|
+
error: wrapApiError(f.error, 'search this conversation').message,
|
|
422
|
+
})),
|
|
423
|
+
}
|
|
424
|
+
: {}),
|
|
425
|
+
};
|
|
426
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The optional `tz` argument of the message-reading tools. Every message's
|
|
3
|
+
* `time` stays UTC (ISO 8601); a time zone adds `time_local` beside it, the
|
|
4
|
+
* same instant as wall-clock time there with its offset. `TEAMS_TIME_ZONE`
|
|
5
|
+
* supplies the default, so a user can set their zone once.
|
|
6
|
+
*/
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { McpToolError, readEnvVar } from '@chrischall/mcp-utils';
|
|
9
|
+
import { isTimeZone } from '../model.js';
|
|
10
|
+
export const TIME_ZONE_ENV = 'TEAMS_TIME_ZONE';
|
|
11
|
+
/** The tool-description sentence every `tz`-taking tool carries. */
|
|
12
|
+
export const TIME_ZONE_DESCRIPTION = 'tz (an IANA time zone, e.g. America/New_York; default TEAMS_TIME_ZONE) adds time_local — ' +
|
|
13
|
+
'ISO 8601 with its offset — next to each message\'s UTC time.';
|
|
14
|
+
export const tzArg = z
|
|
15
|
+
.string()
|
|
16
|
+
.refine(isTimeZone, { message: 'tz must be an IANA time zone such as America/New_York' })
|
|
17
|
+
.optional()
|
|
18
|
+
.describe('IANA time zone (e.g. America/New_York, Europe/London, UTC) to add each message\'s time_local in, ' +
|
|
19
|
+
`ISO 8601 with its offset; time stays UTC. Defaults to ${TIME_ZONE_ENV} when set, else no time_local.`);
|
|
20
|
+
/**
|
|
21
|
+
* The time zone to render `time_local` in: `tz` when given (already validated
|
|
22
|
+
* by {@link tzArg}), else `TEAMS_TIME_ZONE`, else none. A `TEAMS_TIME_ZONE`
|
|
23
|
+
* that is not a time zone is an `McpToolError` naming it, rather than being
|
|
24
|
+
* silently ignored.
|
|
25
|
+
*/
|
|
26
|
+
export function resolveTimeZone(tz, env = process.env) {
|
|
27
|
+
if (tz !== undefined)
|
|
28
|
+
return tz;
|
|
29
|
+
const fromEnv = readEnvVar(TIME_ZONE_ENV, { env });
|
|
30
|
+
if (fromEnv === undefined)
|
|
31
|
+
return undefined;
|
|
32
|
+
if (!isTimeZone(fromEnv)) {
|
|
33
|
+
throw new McpToolError(`${TIME_ZONE_ENV} "${fromEnv}" is not an IANA time zone.`, {
|
|
34
|
+
hint: `Set ${TIME_ZONE_ENV} to a name such as America/New_York, or unset it.`,
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
return fromEnv;
|
|
38
|
+
}
|