@chrischall/microsoft-teams-mcp 0.2.7 → 0.4.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 +3 -3
- package/README.md +281 -87
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +42668 -37351
- package/dist/capture-window.js +41 -0
- package/dist/chatsvc.js +552 -0
- package/dist/compose.js +241 -0
- package/dist/deps.js +1 -0
- package/dist/index.js +26 -6
- package/dist/model.js +499 -0
- package/dist/sharepoint-auth.js +162 -0
- package/dist/sharepoint-token-cache.js +105 -0
- package/dist/sharepoint.js +289 -0
- package/dist/token-cache.js +67 -0
- package/dist/tools/activity.js +156 -13
- package/dist/tools/attachment.js +174 -0
- package/dist/tools/channels.js +62 -38
- package/dist/tools/chat.js +48 -35
- package/dist/tools/confirm.js +145 -0
- package/dist/tools/conversation.js +172 -26
- package/dist/tools/errors.js +18 -17
- package/dist/tools/healthcheck.js +86 -12
- package/dist/tools/limit.js +83 -0
- package/dist/tools/listing.js +116 -0
- package/dist/tools/react.js +217 -0
- package/dist/tools/send.js +309 -0
- package/dist/tools/titles.js +180 -0
- package/dist/tools/unread.js +162 -0
- package/dist/tools/untrusted.js +16 -1
- package/dist/version.js +1 -1
- package/mint.yaml +63 -20
- package/package.json +3 -4
- package/server.json +96 -4
- package/skills/teams-fpx/SKILL.md +108 -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 -281
- package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
|
@@ -1,32 +1,178 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { 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
|
+
const MAX_MESSAGES = 500;
|
|
7
10
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
11
|
+
* Raw messages read before giving up (20 pages of 200). The real bound is the
|
|
12
|
+
* `stopAt` boundary; this only caps a conversation of nothing but system events.
|
|
10
13
|
*/
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
const MAX_RAW_MESSAGES = 4000;
|
|
15
|
+
/** Candidates an ambiguous-name error lists. */
|
|
16
|
+
const MAX_CANDIDATES = 10;
|
|
17
|
+
/** Arrival time in epoch ms: a message's id IS its arrival ms; the ISO fields are the fallback. */
|
|
18
|
+
export function arrivalMs(m) {
|
|
19
|
+
const n = Number(m.id);
|
|
20
|
+
if (Number.isFinite(n) && n > 0)
|
|
21
|
+
return n;
|
|
22
|
+
return Date.parse(m.originalarrivaltime ?? m.composetime ?? '');
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Group oldest-first channel messages under their root post, in order of first
|
|
26
|
+
* appearance. A reply whose root is older than the window still appears, under
|
|
27
|
+
* a `{ id, missing: true }` placeholder root.
|
|
28
|
+
*/
|
|
29
|
+
export function groupThreads(messages) {
|
|
30
|
+
const byRoot = new Map();
|
|
31
|
+
for (const m of messages) {
|
|
32
|
+
const rootId = m.replyTo ?? m.id;
|
|
33
|
+
let thread = byRoot.get(rootId);
|
|
34
|
+
if (thread === undefined) {
|
|
35
|
+
thread = { root: { id: rootId, missing: true }, replies: [] };
|
|
36
|
+
byRoot.set(rootId, thread);
|
|
37
|
+
}
|
|
38
|
+
if (m.replyTo === undefined)
|
|
39
|
+
thread.root = m;
|
|
40
|
+
else
|
|
41
|
+
thread.replies.push(m);
|
|
15
42
|
}
|
|
16
|
-
|
|
17
|
-
|
|
43
|
+
return [...byRoot.values()];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Settle a listing's unread hint with what the read actually found: an unread
|
|
47
|
+
* message confirms it, and a read that saw everything past the horizon without
|
|
48
|
+
* one refutes it. A window-cut read with none proves nothing, so the hint stays.
|
|
49
|
+
*/
|
|
50
|
+
export function confirmUnread(summary, unreadCount, exact) {
|
|
51
|
+
if (unreadCount > 0)
|
|
52
|
+
return confirmedSummary(summary, true);
|
|
53
|
+
return exact ? confirmedSummary(summary, false) : summary;
|
|
54
|
+
}
|
|
55
|
+
function describeCandidate(s) {
|
|
56
|
+
const where = s.team !== undefined ? ` in ${s.team}` : '';
|
|
57
|
+
return `"${s.title}"${where} (${s.kind}, id ${s.id})`;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The one conversation a `conversation` argument names: an exact id, else a
|
|
61
|
+
* unique title/team substring. None, or several, is an `McpToolError` — the
|
|
62
|
+
* latter naming up to 10 candidates so the caller can pass an id. `verb` fills
|
|
63
|
+
* the hint ("Pass the id of the one to read").
|
|
64
|
+
*/
|
|
65
|
+
export function resolveConversation(summaries, conversation, verb) {
|
|
66
|
+
const matches = matchConversations(summaries, conversation);
|
|
67
|
+
if (matches.length === 0) {
|
|
68
|
+
throw new McpToolError(`No chat or channel matches "${conversation}".`, {
|
|
69
|
+
hint: 'List them with teams_list_chats or teams_list_teams_and_channels and pass an id.',
|
|
70
|
+
});
|
|
18
71
|
}
|
|
19
|
-
if (
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
};
|
|
72
|
+
if (matches.length > 1) {
|
|
73
|
+
const named = matches.slice(0, MAX_CANDIDATES).map(describeCandidate).join('; ');
|
|
74
|
+
const more = matches.length > MAX_CANDIDATES ? ` (first ${MAX_CANDIDATES} shown)` : '';
|
|
75
|
+
throw new McpToolError(`"${conversation}" matches ${matches.length} conversations${more}: ${named}.`, {
|
|
76
|
+
hint: `Pass the id of the one to ${verb} as conversation.`,
|
|
77
|
+
});
|
|
25
78
|
}
|
|
26
|
-
return
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
79
|
+
return matches[0];
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* {@link resolveConversation} against the whole listing, with untitled group
|
|
83
|
+
* chats titled by their participants and 1:1s by the other person
|
|
84
|
+
* (`titles.ts`) so a name can pick one of several chats that share a last
|
|
85
|
+
* sender, or a 1:1 the user wrote in last. An exact id titles just that one,
|
|
86
|
+
* and a self-chat alias (`notes`, `self`) titles nothing.
|
|
87
|
+
*/
|
|
88
|
+
export async function resolveListed(chatsvc, raw, me, conversation, verb) {
|
|
89
|
+
const summaries = summariseAll(raw, me);
|
|
90
|
+
if (SELF_CHAT_ALIASES.has(conversation.trim().toLowerCase()))
|
|
91
|
+
return resolveConversation(summaries, conversation, verb);
|
|
92
|
+
const exact = summaries.find((s) => s.id === conversation);
|
|
93
|
+
return resolveConversation(await enrichTitles(chatsvc, raw, me, exact ? [exact] : summaries), conversation, verb);
|
|
94
|
+
}
|
|
95
|
+
export function registerConversationTools(server, { chatsvc }) {
|
|
96
|
+
server.registerTool('teams_read_conversation', {
|
|
97
|
+
title: 'Read a Teams chat or channel',
|
|
98
|
+
description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
|
|
99
|
+
'teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in ' +
|
|
100
|
+
'Teams. "48:notes" (or the name "notes" / "self") is the user\'s own notes self-chat. Messages come oldest first, each with id, time (ISO 8601), sender, fromMe, ' +
|
|
101
|
+
'text, subject, edited/deleted flags and attachments; a channel is returned as threads, ' +
|
|
102
|
+
'each root post with its replies (a root older than the window is marked missing). ' +
|
|
103
|
+
'unread_only returns just the messages the user has not read; since stops at a time; ' +
|
|
104
|
+
'limit keeps the newest (truncated says when more exist; unread_count_scope "window" says ' +
|
|
105
|
+
'unread_count only covers what limit/since let through). This does NOT mark anything ' +
|
|
106
|
+
'read — the user\'s Teams unread badges are unaffected. Attachments are listed per message (images by ref, files by ' +
|
|
107
|
+
'name) and fetched with teams_get_attachment.' +
|
|
108
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
109
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
110
|
+
inputSchema: {
|
|
111
|
+
conversation: z
|
|
112
|
+
.string()
|
|
113
|
+
.min(1)
|
|
114
|
+
.describe('The conversation id ("48:notes", "notes" or "self" for the self-chat), or a case-insensitive ' +
|
|
115
|
+
"substring of the chat title, channel name, team name or an untitled chat's participant names."),
|
|
116
|
+
unread_only: z
|
|
117
|
+
.boolean()
|
|
118
|
+
.optional()
|
|
119
|
+
.describe('Only return messages the user has not read yet (default false). Never marks them read.'),
|
|
120
|
+
since: sinceArg,
|
|
121
|
+
limit: limitArg(MAX_MESSAGES, 'messages'),
|
|
122
|
+
},
|
|
123
|
+
}, async ({ conversation, unread_only, since, limit }) => {
|
|
124
|
+
try {
|
|
125
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
126
|
+
const summary = await resolveListed(chatsvc, raw, me, conversation, 'read');
|
|
127
|
+
// The self-chat resolves even when the listing does not carry it.
|
|
128
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
129
|
+
const horizon = readHorizon(conv);
|
|
130
|
+
const cutoff = since !== undefined ? Date.parse(since) : undefined;
|
|
131
|
+
const wanted = (m) => isUserMessage(m) && (!unread_only || isUnread(m, horizon, me));
|
|
132
|
+
const limited = makeLimitedStopAt(unread_only ? horizon : undefined, wanted, limit ?? DEFAULT_LIMIT);
|
|
133
|
+
// A `since` cutoff above the read horizon leaves unread messages unseen.
|
|
134
|
+
let sinceCut = false;
|
|
135
|
+
let capped = false;
|
|
136
|
+
const stopAt = (m) => {
|
|
137
|
+
// The read horizon (checked inside `limited`) wins over `since`, as it is the nearer boundary.
|
|
138
|
+
const atHorizon = unread_only && Number(m.id) <= horizon;
|
|
139
|
+
const at = arrivalMs(m);
|
|
140
|
+
if (!atHorizon && cutoff !== undefined && Number.isFinite(at) && at < cutoff) {
|
|
141
|
+
if (Number(m.id) > horizon)
|
|
142
|
+
sinceCut = true;
|
|
143
|
+
return true;
|
|
144
|
+
}
|
|
145
|
+
return limited.stopAt(m);
|
|
146
|
+
};
|
|
147
|
+
const fetched = await chatsvc.getMessages(summary.id, {
|
|
148
|
+
stopAt,
|
|
149
|
+
max: MAX_RAW_MESSAGES,
|
|
150
|
+
onCapped: () => (capped = true),
|
|
151
|
+
});
|
|
152
|
+
const messages = oldestFirst(fetched.filter(wanted)).map((m) => normaliseMessage(m, me));
|
|
153
|
+
const unread_count = fetched.filter((m) => wanted(m) && isUnread(m, horizon, me)).length;
|
|
154
|
+
const body = summary.kind === 'channel' ? { threads: groupThreads(messages) } : { messages };
|
|
155
|
+
const truncated = limited.truncated || capped;
|
|
156
|
+
// Whether every message past the read horizon was seen, so unread_count is the whole count.
|
|
157
|
+
const exact = !truncated && !sinceCut;
|
|
158
|
+
return untrustedResult({
|
|
159
|
+
conversation: confirmUnread(summary, unread_count, exact),
|
|
160
|
+
unread_count,
|
|
161
|
+
...(exact ? {} : { unread_count_scope: 'window' }),
|
|
162
|
+
...body,
|
|
163
|
+
...(truncated
|
|
164
|
+
? {
|
|
165
|
+
truncated: {
|
|
166
|
+
returned: messages.length,
|
|
167
|
+
hint: `Only the newest ${messages.length} messages were returned; pass a larger limit ` +
|
|
168
|
+
`(max ${MAX_MESSAGES}) or a since time to read further back.`,
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
: {}),
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
throw wrapApiError(err, 'read the conversation');
|
|
176
|
+
}
|
|
177
|
+
});
|
|
32
178
|
}
|
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
|
}
|
|
@@ -1,14 +1,88 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
1
|
+
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
|
+
import { credentialHealthcheckDescription, runCredentialHealthcheck } from '@chrischall/mcp-utils/healthcheck';
|
|
3
|
+
const HOST_LABEL = 'teams.cloud.microsoft';
|
|
4
|
+
const TITLE = 'Verify the Teams chat-service token and API end-to-end';
|
|
5
|
+
/**
|
|
6
|
+
* Static note on the SharePoint path: a separate token, captured on demand per
|
|
7
|
+
* host and short-lived, that `teams_get_attachment` uses for shared-file
|
|
8
|
+
* download. Not probed here — a healthy result never depends on it existing.
|
|
9
|
+
*/
|
|
10
|
+
const SHAREPOINT_NOTE = 'Shared-file download (teams_get_attachment) uses a separate SharePoint token, captured on ' +
|
|
11
|
+
'demand per SharePoint host and short-lived (~53 min). None is held until you open a file, and ' +
|
|
12
|
+
'this healthcheck neither mints nor requires one.';
|
|
13
|
+
export function registerHealthcheckTool(server, { chatsvc }) {
|
|
14
|
+
server.registerTool('teams_healthcheck', {
|
|
15
|
+
title: TITLE,
|
|
16
|
+
description: `${credentialHealthcheckDescription(HOST_LABEL)} The credential is the Teams chat-service ` +
|
|
17
|
+
'token behind every tool; the probe is one conversations listing. Also reports the ' +
|
|
18
|
+
'token\'s source (browser capture through the ContextMint Bridge, or TEAMS_ACCESS_TOKEN), ' +
|
|
19
|
+
'its expiry, and how many conversations the listing returned — never the token itself. ' +
|
|
20
|
+
'Call this when a real tool fails and you want to know which hop broke.',
|
|
21
|
+
annotations: toolAnnotations({ title: TITLE, readOnly: true, idempotent: true, openWorld: true }),
|
|
22
|
+
inputSchema: {},
|
|
23
|
+
}, async () => {
|
|
24
|
+
// Set only by a probe that got as far as a listing.
|
|
25
|
+
let conversations = null;
|
|
26
|
+
// TEAMS_CHATSVC_BASE can point the client elsewhere; report what it really talks to.
|
|
27
|
+
const base = new URL(chatsvc.apiBase);
|
|
28
|
+
const result = await runCredentialHealthcheck({
|
|
29
|
+
server,
|
|
30
|
+
prefix: 'teams',
|
|
31
|
+
hostLabel: base.host,
|
|
32
|
+
probePath: `${base.pathname}/users/ME/conversations`,
|
|
33
|
+
// Resolves the token the way every tool does — same cache, same capture.
|
|
34
|
+
resolveCredential: async () => {
|
|
35
|
+
await chatsvc.ensureToken();
|
|
36
|
+
return { source: chatsvc.tokenSource };
|
|
37
|
+
},
|
|
38
|
+
probeFn: async () => {
|
|
39
|
+
conversations = (await chatsvc.listConversations()).length;
|
|
40
|
+
return `${conversations} conversation(s) listed`;
|
|
41
|
+
},
|
|
42
|
+
classifyThrown: (err) => /could not capture a Teams token/i.test(err instanceof Error ? err.message : String(err))
|
|
43
|
+
? { kind: 'token_capture', hint: TOKEN_CAPTURE_HINT }
|
|
44
|
+
: undefined,
|
|
45
|
+
});
|
|
46
|
+
// Read after the resolve, which is what loads (or captures) the token.
|
|
47
|
+
const expiresAt = chatsvc.tokenExpiresAt();
|
|
48
|
+
const chatService = {
|
|
49
|
+
api_base: chatsvc.apiBase,
|
|
50
|
+
token_source: chatsvc.tokenSource,
|
|
51
|
+
token_expires_at: expiresAt === null ? null : new Date(expiresAt).toISOString(),
|
|
52
|
+
token_minutes_remaining: expiresAt === null ? null : Math.round((expiresAt - Date.now()) / 60_000),
|
|
53
|
+
conversations,
|
|
54
|
+
};
|
|
55
|
+
const first = result.content[0];
|
|
56
|
+
let body;
|
|
57
|
+
try {
|
|
58
|
+
body = first === undefined ? undefined : JSON.parse(first.text);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
body = undefined;
|
|
62
|
+
}
|
|
63
|
+
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
|
|
64
|
+
// Not the JSON envelope this expects: keep its text as-is and report the
|
|
65
|
+
// chat service beside it rather than failing the healthcheck.
|
|
66
|
+
return {
|
|
67
|
+
content: [
|
|
68
|
+
...result.content,
|
|
69
|
+
{
|
|
70
|
+
type: 'text',
|
|
71
|
+
text: JSON.stringify({ chat_service: chatService, sharepoint: SHAREPOINT_NOTE }, null, 2),
|
|
72
|
+
},
|
|
73
|
+
],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
content: [
|
|
78
|
+
{
|
|
79
|
+
type: 'text',
|
|
80
|
+
text: JSON.stringify({ ...body, chat_service: chatService, sharepoint: SHAREPOINT_NOTE }, null, 2),
|
|
81
|
+
},
|
|
82
|
+
],
|
|
83
|
+
};
|
|
13
84
|
});
|
|
14
85
|
}
|
|
86
|
+
const TOKEN_CAPTURE_HINT = 'No Teams access token could be captured. Open a signed-in teams.cloud.microsoft tab and click ' +
|
|
87
|
+
'into any chat (that is what makes Teams call its chat service, where the token is read from), ' +
|
|
88
|
+
'then retry.';
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side trimming for every list/read tool. A chat-service read or conversation
|
|
3
|
+
* listing returns hundreds of rows at once; dumping all of them into one
|
|
4
|
+
* result fills the context window with other people's messages the question
|
|
5
|
+
* did not need. Each tool takes an optional `limit` (default
|
|
6
|
+
* {@link DEFAULT_LIMIT}) and keeps the rows that lead its ordering — the
|
|
7
|
+
* NEWEST for anything time-ordered (the END of an oldest-first thread, the
|
|
8
|
+
* START of a newest-first feed), the first for an alphabetical listing.
|
|
9
|
+
*/
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
export const DEFAULT_LIMIT = 50;
|
|
12
|
+
/**
|
|
13
|
+
* The optional `limit` argument, capped at what the source can return. `kept`
|
|
14
|
+
* says which rows survive, for a listing that is not newest-first.
|
|
15
|
+
*/
|
|
16
|
+
export function limitArg(max, what, kept = 'newest first kept') {
|
|
17
|
+
return z
|
|
18
|
+
.number()
|
|
19
|
+
.int()
|
|
20
|
+
.min(1)
|
|
21
|
+
.max(max)
|
|
22
|
+
.optional()
|
|
23
|
+
.describe(`Maximum ${what} to return, ${kept} (default ${DEFAULT_LIMIT}, max ${max}).`);
|
|
24
|
+
}
|
|
25
|
+
/** `which` names the kept rows in the hint ("newest", or "first" for a non-time ordering). */
|
|
26
|
+
export function trimRows(rows, limit, newestAt, max, which = 'newest') {
|
|
27
|
+
const n = limit ?? DEFAULT_LIMIT;
|
|
28
|
+
if (rows.length <= n)
|
|
29
|
+
return { rows };
|
|
30
|
+
const kept = newestAt === 'end' ? rows.slice(rows.length - n) : rows.slice(0, n);
|
|
31
|
+
return {
|
|
32
|
+
rows: kept,
|
|
33
|
+
truncated: {
|
|
34
|
+
total: rows.length,
|
|
35
|
+
returned: kept.length,
|
|
36
|
+
hint: `Only the ${which} ${kept.length} of ${rows.length} were returned; pass a larger limit (max ${max}) to read more.`,
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** The optional `since` argument (ISO 8601 date-time) for ISO-timed rows. */
|
|
41
|
+
export const sinceArg = z
|
|
42
|
+
.string()
|
|
43
|
+
.refine((s) => !Number.isNaN(Date.parse(s)), { message: 'since must be an ISO 8601 date-time' })
|
|
44
|
+
.optional()
|
|
45
|
+
.describe('Only return messages at or after this ISO 8601 date-time (e.g. 2026-09-21T09:00:00Z). ' +
|
|
46
|
+
'Messages whose time cannot be read are kept.');
|
|
47
|
+
/** Drop rows whose ISO `time` is before `since`; rows with no readable time are kept. */
|
|
48
|
+
export function filterSince(rows, since) {
|
|
49
|
+
if (since === undefined)
|
|
50
|
+
return rows;
|
|
51
|
+
const cutoff = Date.parse(since);
|
|
52
|
+
return rows.filter((row) => {
|
|
53
|
+
const t = row.time === undefined ? Number.NaN : Date.parse(row.time);
|
|
54
|
+
return Number.isNaN(t) || t >= cutoff;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The `stopAt` behind `teams_read_conversation` and `teams_get_unread`. It
|
|
59
|
+
* sees each message once, newest first, so it can count: the first wanted
|
|
60
|
+
* message past `limit` is the boundary, and its existence is what says the
|
|
61
|
+
* result was truncated. `horizon` (when given) ends the read at the first
|
|
62
|
+
* message the user had already read — checked first, so a boundary there is
|
|
63
|
+
* never a truncation.
|
|
64
|
+
*/
|
|
65
|
+
export function makeLimitedStopAt(horizon, wanted, limit) {
|
|
66
|
+
let kept = 0;
|
|
67
|
+
let truncated = false;
|
|
68
|
+
return {
|
|
69
|
+
stopAt: (m) => {
|
|
70
|
+
if (horizon !== undefined && Number(m.id) <= horizon)
|
|
71
|
+
return true;
|
|
72
|
+
if (!wanted(m))
|
|
73
|
+
return false;
|
|
74
|
+
if (kept >= limit)
|
|
75
|
+
return (truncated = true);
|
|
76
|
+
kept++;
|
|
77
|
+
return false;
|
|
78
|
+
},
|
|
79
|
+
get truncated() {
|
|
80
|
+
return truncated;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The conversation listing shared by `teams_list_chats` and
|
|
3
|
+
* `teams_list_teams_and_channels`: one `listConversations` call, normalised
|
|
4
|
+
* against the signed-in user, then filtered by kind, unread state and query.
|
|
5
|
+
* With `unread_only`, the listing's unread flag only nominates candidates; each
|
|
6
|
+
* is confirmed by reading past its horizon (`confirm.ts`).
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { confirmedSummary, confirmUnreadCandidates, olderUnreadReport, sinceCutoff, sinceDaysArg } from './confirm.js';
|
|
10
|
+
import { wrapApiError } from './errors.js';
|
|
11
|
+
import { enrichTitles } from './titles.js';
|
|
12
|
+
import { conversationSummary, matchConversations, } from '../model.js';
|
|
13
|
+
/** The list tools' `since_days`: it narrows `unread_only` only. */
|
|
14
|
+
export const listSinceDaysArg = sinceDaysArg('With unread_only: ');
|
|
15
|
+
export const unreadOnlyArg = z
|
|
16
|
+
.boolean()
|
|
17
|
+
.optional()
|
|
18
|
+
.describe('Only return conversations with a real message (not a call recording or other system event) ' +
|
|
19
|
+
'the user has not read yet, each with its unread_count (default false). Exact: every candidate ' +
|
|
20
|
+
'is confirmed by reading its messages past the read marker. Never marks anything read.');
|
|
21
|
+
/** Description text shared by the list tools on what their unread flag means. */
|
|
22
|
+
export const UNREAD_HINT_DESCRIPTION = 'Without unread_only, unread is only a hint from the listing (unread_confirmed: false): it can ' +
|
|
23
|
+
'flag a conversation whose only news is a call recording or other system event. For an exact ' +
|
|
24
|
+
'answer use unread_only (confirmed rows carry unread_confirmed: true and unread_count) or ' +
|
|
25
|
+
'teams_get_unread.';
|
|
26
|
+
/** Real unread messages counted per candidate before unread_count is reported as a lower bound. */
|
|
27
|
+
const CONFIRM_LIMIT = 50;
|
|
28
|
+
/** Raw messages read per candidate — one page; the horizon is usually much nearer. */
|
|
29
|
+
const CONFIRM_MAX_RAW = 50;
|
|
30
|
+
export const includeHiddenArg = z
|
|
31
|
+
.boolean()
|
|
32
|
+
.optional()
|
|
33
|
+
.describe('Also count channels the user has hidden in Teams as unread (default false: Teams shows no ' +
|
|
34
|
+
'unread badge for a hidden channel, so neither does this).');
|
|
35
|
+
/**
|
|
36
|
+
* Whether a conversation is an unread candidate worth confirming: the listing
|
|
37
|
+
* flags it, and it is not a channel hidden in Teams (unless the caller asked
|
|
38
|
+
* for hidden ones — Teams shows a hidden channel no badge).
|
|
39
|
+
*/
|
|
40
|
+
export function isUnreadCandidateFor(s, includeHidden) {
|
|
41
|
+
return s.unread && (includeHidden === true || s.hidden !== true);
|
|
42
|
+
}
|
|
43
|
+
export function queryArg(what) {
|
|
44
|
+
return z
|
|
45
|
+
.string()
|
|
46
|
+
.min(1)
|
|
47
|
+
.optional()
|
|
48
|
+
.describe(`Case-insensitive substring of the ${what}, or an exact conversation id.`);
|
|
49
|
+
}
|
|
50
|
+
/** Description text on how an untitled group chat or 1:1 is titled. */
|
|
51
|
+
export const GROUP_TITLE_DESCRIPTION = 'A group chat with no topic is titled "Group chat: " and up to three of its recent senders other ' +
|
|
52
|
+
'than the user, most recent first ("; " between names, "+N" for more), and carries every such ' +
|
|
53
|
+
'recent sender as participants; it is "(untitled group chat)" when no one else wrote recently. ' +
|
|
54
|
+
'A 1:1 is titled by the other person, who is its one participant; it is "(1:1 chat)" when they ' +
|
|
55
|
+
'wrote nothing recently.';
|
|
56
|
+
/**
|
|
57
|
+
* Favorites, then pinned conversations, ahead of the rest — the plain list
|
|
58
|
+
* tools' first sort key, as in the Teams sidebar. 0 between two of a kind, so
|
|
59
|
+
* a stable sort keeps each tool's own order within them.
|
|
60
|
+
*/
|
|
61
|
+
export function favoritesFirst(a, b) {
|
|
62
|
+
const rank = (s) => (s.favorite ? 0 : s.pinned ? 1 : 2);
|
|
63
|
+
return rank(a) - rank(b);
|
|
64
|
+
}
|
|
65
|
+
/** Description text on the favorite / pinned flags and order. */
|
|
66
|
+
export const FAVORITES_DESCRIPTION = 'Conversations the user marked a favorite or pinned in Teams carry favorite: true / pinned: true ' +
|
|
67
|
+
'and, without unread_only, are listed first (favorites, then pinned); unread_only keeps its usual order.';
|
|
68
|
+
/**
|
|
69
|
+
* Every conversation of the given kinds, as summaries. Unsorted: each tool
|
|
70
|
+
* orders its own result. A team's name comes from its own thread, so the
|
|
71
|
+
* summaries are built against the FULL listing before any filtering. With
|
|
72
|
+
* `unread_only`, only candidates a read confirms are kept.
|
|
73
|
+
*/
|
|
74
|
+
export async function listSummaries(chatsvc, filter) {
|
|
75
|
+
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
76
|
+
let rows = raw.map((c) => conversationSummary(c, me, raw)).filter((s) => filter.kinds.includes(s.kind));
|
|
77
|
+
if (filter.unread_only)
|
|
78
|
+
rows = rows.filter((s) => isUnreadCandidateFor(s, filter.include_hidden));
|
|
79
|
+
// A query can name a group chat or 1:1 by a participant, so every untitled one is titled first.
|
|
80
|
+
if (filter.query !== undefined)
|
|
81
|
+
rows = matchConversations(await enrichTitles(chatsvc, raw, me, rows), filter.query);
|
|
82
|
+
if (!filter.unread_only)
|
|
83
|
+
return { rows, retitle: async (kept) => ({ rows: await enrichTitles(chatsvc, raw, me, kept) }) };
|
|
84
|
+
const outcome = await confirmUnreadCandidates(chatsvc, raw, me, rows, {
|
|
85
|
+
limit: CONFIRM_LIMIT,
|
|
86
|
+
maxRaw: CONFIRM_MAX_RAW,
|
|
87
|
+
since: sinceCutoff(filter.since_days),
|
|
88
|
+
});
|
|
89
|
+
const errors = (titled) => outcome.failed.length > 0
|
|
90
|
+
? outcome.failed.map((f, i) => ({
|
|
91
|
+
conversation: { id: f.summary.id, title: titled[i].title },
|
|
92
|
+
error: wrapApiError(f.error, 'confirm this conversation is unread').message,
|
|
93
|
+
}))
|
|
94
|
+
: undefined;
|
|
95
|
+
const failedSummaries = outcome.failed.map((f) => f.summary);
|
|
96
|
+
const retitle = async (kept) => {
|
|
97
|
+
const [rows, failed] = await Promise.all([
|
|
98
|
+
enrichTitles(chatsvc, raw, me, kept),
|
|
99
|
+
enrichTitles(chatsvc, raw, me, failedSummaries),
|
|
100
|
+
]);
|
|
101
|
+
const errs = errors(failed);
|
|
102
|
+
return { rows, ...(errs ? { errors: errs } : {}) };
|
|
103
|
+
};
|
|
104
|
+
const errs = errors(failedSummaries);
|
|
105
|
+
return {
|
|
106
|
+
retitle,
|
|
107
|
+
rows: outcome.confirmed.map(({ summary, read }) => ({
|
|
108
|
+
...confirmedSummary(summary, true),
|
|
109
|
+
unread_count: read.messages.length,
|
|
110
|
+
...(read.truncated ? { unread_count_exact: false } : {}),
|
|
111
|
+
})),
|
|
112
|
+
skipped_unreachable: outcome.skippedUnreachable,
|
|
113
|
+
...olderUnreadReport(outcome.olderSkipped, filter.since_days),
|
|
114
|
+
...(errs ? { errors: errs } : {}),
|
|
115
|
+
};
|
|
116
|
+
}
|