@chrischall/microsoft-teams-mcp 0.3.0 → 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 +2 -2
- package/README.md +279 -93
- package/dist/auth-fetchproxy.js +138 -0
- package/dist/bundle.js +42380 -37144
- 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 +155 -19
- package/dist/tools/attachment.js +174 -0
- package/dist/tools/channels.js +60 -44
- package/dist/tools/chat.js +47 -42
- package/dist/tools/confirm.js +145 -0
- package/dist/tools/conversation.js +172 -32
- package/dist/tools/errors.js +18 -17
- package/dist/tools/healthcheck.js +86 -27
- package/dist/tools/limit.js +43 -12
- 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 +1 -2
- package/server.json +80 -3
- 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 -290
- package/skills/teams-fpx/references/dom-list-recipes.md +0 -81
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { McpToolError, errorKindOf, errorStatusOf, toolAnnotations } from '@chrischall/mcp-utils';
|
|
3
|
+
import { normaliseMessage } from '../model.js';
|
|
4
|
+
import { wrapApiError } from './errors.js';
|
|
5
|
+
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
6
|
+
/**
|
|
7
|
+
* Raw messages read looking for the one asked for (20 pages of 200). The
|
|
8
|
+
* `stopAt` boundary — paging past the message's arrival time — is the real
|
|
9
|
+
* bound; this only caps an id that is not an arrival time.
|
|
10
|
+
*/
|
|
11
|
+
const MAX_RAW_MESSAGES = 4000;
|
|
12
|
+
/**
|
|
13
|
+
* Largest shared file whose contents are downloaded and returned inline. Past
|
|
14
|
+
* this the bounded read in `SharePointClient` aborts and the file degrades to
|
|
15
|
+
* metadata + link — a file this big belongs behind its link, not in a result.
|
|
16
|
+
*/
|
|
17
|
+
const MAX_FILE_BYTES = 25 * 1024 * 1024;
|
|
18
|
+
const FILE_HINT = 'A shared file is downloaded from SharePoint and returned as its contents (an image as an image, ' +
|
|
19
|
+
'anything else as an embedded resource). The first file from a given SharePoint host may need ' +
|
|
20
|
+
'opening once in Teams to mint a short-lived token; a file your account cannot open comes back as ' +
|
|
21
|
+
'metadata and its link.';
|
|
22
|
+
export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
|
|
23
|
+
server.registerTool('teams_get_attachment', {
|
|
24
|
+
title: 'Get a Teams message attachment',
|
|
25
|
+
description: 'Fetch one attachment of a Teams chat or channel message, as listed by ' +
|
|
26
|
+
'teams_read_conversation / teams_get_unread. An inline image (attachments.images[].ref) ' +
|
|
27
|
+
'is returned as the image itself. A shared file (attachments.files[].name) is downloaded ' +
|
|
28
|
+
'from SharePoint and returned as its contents: an image as the image, anything else as an ' +
|
|
29
|
+
'embedded resource carrying the bytes. The first file from a given SharePoint host in a ' +
|
|
30
|
+
'session may need opening once in Teams to mint a short-lived token; a file your account ' +
|
|
31
|
+
'cannot open, or one that could not be fetched, comes back as metadata and its open link ' +
|
|
32
|
+
'instead of failing. Does not mark anything read.' +
|
|
33
|
+
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
34
|
+
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
35
|
+
inputSchema: {
|
|
36
|
+
conversation: z
|
|
37
|
+
.string()
|
|
38
|
+
.min(1)
|
|
39
|
+
.describe('The conversation id the message is in (from teams_read_conversation or teams_get_unread).'),
|
|
40
|
+
message_id: z.string().min(1).describe('The message id, exactly as a message listing returned it.'),
|
|
41
|
+
ref: z
|
|
42
|
+
.string()
|
|
43
|
+
.min(1)
|
|
44
|
+
.describe("An inline image's ref (attachments.images[].ref) or a shared file's name (attachments.files[].name)."),
|
|
45
|
+
},
|
|
46
|
+
}, async ({ conversation, message_id, ref }) => {
|
|
47
|
+
try {
|
|
48
|
+
// A message id IS its arrival ms, and pages run newest first: the first
|
|
49
|
+
// message older than it means it was not there.
|
|
50
|
+
const target = Number(message_id);
|
|
51
|
+
const stopAt = Number.isFinite(target) && target > 0 ? (m) => Number(m.id) < target : undefined;
|
|
52
|
+
const fetched = await chatsvc.getMessages(conversation, { stopAt, max: MAX_RAW_MESSAGES });
|
|
53
|
+
const raw = fetched.find((m) => m.id === message_id);
|
|
54
|
+
if (raw === undefined) {
|
|
55
|
+
throw new McpToolError(`Message ${message_id} was not found in conversation ${conversation}.`, {
|
|
56
|
+
hint: 'Pass the conversation id and message id exactly as teams_read_conversation returned them.',
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
// Only the attachments are read, so whose message it is does not matter.
|
|
60
|
+
const message = normaliseMessage(raw, '');
|
|
61
|
+
const image = message.attachments.images.find((i) => i.ref === ref);
|
|
62
|
+
if (image !== undefined) {
|
|
63
|
+
const { mimeType, data } = await chatsvc.fetchImage(image.url);
|
|
64
|
+
if (!mimeType.startsWith('image/')) {
|
|
65
|
+
throw new McpToolError(`The attachment ${ref} is not an image (the image store returned ${mimeType}).`);
|
|
66
|
+
}
|
|
67
|
+
const caption = untrustedResult({
|
|
68
|
+
ref,
|
|
69
|
+
message_id,
|
|
70
|
+
conversation,
|
|
71
|
+
sender: message.sender,
|
|
72
|
+
time: message.time,
|
|
73
|
+
mimeType,
|
|
74
|
+
bytes: data.length,
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
content: [{ type: 'image', data: data.toString('base64'), mimeType }, ...caption.content],
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const file = message.attachments.files.find((f) => f.name === ref);
|
|
81
|
+
if (file !== undefined) {
|
|
82
|
+
return downloadSharedFile(sharepoint, file, message, { conversation, message_id });
|
|
83
|
+
}
|
|
84
|
+
const { images, files } = message.attachments;
|
|
85
|
+
throw new McpToolError(`Message ${message_id} has no attachment "${ref}".`, {
|
|
86
|
+
hint: `It has ${images.length} inline image(s) and ${files.length} shared file(s); pass an ` +
|
|
87
|
+
'image ref or a file name exactly as teams_read_conversation listed it.',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
throw wrapApiError(err, 'get the attachment');
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Download a shared file's contents, degrading to metadata + link on any
|
|
97
|
+
* failure rather than throwing: a file that cannot be fetched (no token yet, a
|
|
98
|
+
* 403, a transient error) must never fail the tool, so this swallows every
|
|
99
|
+
* `downloadFile` error and returns today's metadata result with a hint saying
|
|
100
|
+
* why. A file with no `url` at all (nothing to download) takes the same path.
|
|
101
|
+
*/
|
|
102
|
+
async function downloadSharedFile(sharepoint, file, message, ids) {
|
|
103
|
+
if (file.url === undefined) {
|
|
104
|
+
return untrustedResult({ ...file, content_available: false, hint: FILE_HINT });
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const { mimeType, data, size } = await sharepoint.downloadFile(file.url, MAX_FILE_BYTES);
|
|
108
|
+
const caption = untrustedResult({
|
|
109
|
+
name: file.name,
|
|
110
|
+
...(file.type !== undefined ? { type: file.type } : {}),
|
|
111
|
+
...(file.openUrl !== undefined ? { openUrl: file.openUrl } : {}),
|
|
112
|
+
// The degrade path carries `content_available: false`; a successful
|
|
113
|
+
// download must carry the matching `true` so a caller keying on the field
|
|
114
|
+
// does not read a downloaded file as unavailable.
|
|
115
|
+
content_available: true,
|
|
116
|
+
mimeType,
|
|
117
|
+
bytes: size,
|
|
118
|
+
sender: message.sender,
|
|
119
|
+
time: message.time,
|
|
120
|
+
message_id: ids.message_id,
|
|
121
|
+
conversation: ids.conversation,
|
|
122
|
+
});
|
|
123
|
+
if (mimeType.startsWith('image/')) {
|
|
124
|
+
return { content: [{ type: 'image', data: data.toString('base64'), mimeType }, ...caption.content] };
|
|
125
|
+
}
|
|
126
|
+
// An embedded resource carries the raw bytes; the installed
|
|
127
|
+
// `@modelcontextprotocol/server` (2.3.0) accepts a `{type:'resource'}`
|
|
128
|
+
// content block with a `BlobResourceContents` body ({uri, mimeType, blob}),
|
|
129
|
+
// so no base64-text fallback is needed. The `uri` is the file's open link
|
|
130
|
+
// (its SharePoint object url otherwise) — an identifier, not a re-fetch.
|
|
131
|
+
return {
|
|
132
|
+
content: [
|
|
133
|
+
{
|
|
134
|
+
type: 'resource',
|
|
135
|
+
resource: { uri: file.openUrl ?? file.url, mimeType, blob: data.toString('base64') },
|
|
136
|
+
},
|
|
137
|
+
...caption.content,
|
|
138
|
+
],
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
// Graceful degrade: a file that could not be fetched comes back as metadata
|
|
143
|
+
// and its link, never as a tool failure (see the docblock).
|
|
144
|
+
return untrustedResult({ ...file, content_available: false, hint: degradeHint(err, hostOf(file.url)) });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/** The host of the file's url, for the degrade hint; a stand-in if it will not parse. */
|
|
148
|
+
function hostOf(url) {
|
|
149
|
+
try {
|
|
150
|
+
return new URL(url).hostname;
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return 'the SharePoint site';
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Why a shared file degraded to metadata + link, as a user-facing hint.
|
|
158
|
+
* `SharePointClient` throws `McpToolError`s carrying `status`/`kind`/`hint`; a
|
|
159
|
+
* token-capture failure arrives as a plain `Error`. Branch on structure, not
|
|
160
|
+
* message text (fleet convention).
|
|
161
|
+
*/
|
|
162
|
+
function degradeHint(err, host) {
|
|
163
|
+
if (errorStatusOf(err) === 403) {
|
|
164
|
+
return (`Your account cannot open this file, or it is on a SharePoint host (${host}) your captured ` +
|
|
165
|
+
'token does not cover. Open it once in a signed-in Teams tab, then retry.');
|
|
166
|
+
}
|
|
167
|
+
if (errorKindOf(err) === 'no_credential') {
|
|
168
|
+
return 'SharePoint file download is disabled here (no token source). Unset TEAMS_DISABLE_FETCHPROXY, then retry.';
|
|
169
|
+
}
|
|
170
|
+
if (err instanceof McpToolError && err.hint !== undefined)
|
|
171
|
+
return err.hint;
|
|
172
|
+
return (`Couldn't mint a SharePoint token for ${host} — open the shared file once in a signed-in Teams ` +
|
|
173
|
+
'tab (that browser request is where the token is captured from), then retry.');
|
|
174
|
+
}
|
package/dist/tools/channels.js
CHANGED
|
@@ -1,56 +1,72 @@
|
|
|
1
1
|
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
|
-
import {
|
|
2
|
+
import { wrapApiError } from './errors.js';
|
|
3
3
|
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
4
|
-
import { OPEN_CONVERSATION_DESCRIPTION, readOpenConversation } from './conversation.js';
|
|
5
4
|
import { limitArg, trimRows } from './limit.js';
|
|
6
|
-
|
|
5
|
+
import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
|
|
6
|
+
/** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
|
|
7
|
+
const MAX_CHANNELS = 500;
|
|
8
|
+
/**
|
|
9
|
+
* Visible channels first, then those hidden in Teams; within each, by team,
|
|
10
|
+
* then channel title, a channel whose team is unknown after every named team.
|
|
11
|
+
*/
|
|
12
|
+
function byTeamThenTitle(a, b) {
|
|
13
|
+
if ((a.hidden === true) !== (b.hidden === true))
|
|
14
|
+
return a.hidden ? 1 : -1;
|
|
15
|
+
if (a.team !== b.team) {
|
|
16
|
+
if (a.team === undefined)
|
|
17
|
+
return 1;
|
|
18
|
+
if (b.team === undefined)
|
|
19
|
+
return -1;
|
|
20
|
+
const byTeam = a.team.localeCompare(b.team, undefined, { sensitivity: 'base' });
|
|
21
|
+
if (byTeam !== 0)
|
|
22
|
+
return byTeam;
|
|
23
|
+
}
|
|
24
|
+
return a.title.localeCompare(b.title, undefined, { sensitivity: 'base' });
|
|
25
|
+
}
|
|
26
|
+
export function registerChannelTools(server, { chatsvc }) {
|
|
7
27
|
server.registerTool('teams_list_teams_and_channels', {
|
|
8
|
-
title: 'List Teams
|
|
9
|
-
description: 'List
|
|
10
|
-
'
|
|
11
|
-
'
|
|
12
|
-
'
|
|
13
|
-
'
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
rows,
|
|
24
|
-
empty_hint: 'No teams or channels are rendered. The Teams tab is probably not on the Teams view — ' +
|
|
25
|
-
'ask the user to click Teams in the left nav, then retry.',
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
catch (err) {
|
|
29
|
-
throw wrapBridgeError(err, 'list teams and channels');
|
|
30
|
-
}
|
|
31
|
-
});
|
|
32
|
-
server.registerTool('teams_get_open_channel_posts', {
|
|
33
|
-
title: 'Read the currently open channel',
|
|
34
|
-
description: 'Read the top-level posts in whichever Teams CHANNEL is CURRENTLY OPEN in the ' +
|
|
35
|
-
'user\'s signed-in browser tab — sender, time (prose, e.g. "Tuesday, August 4, 2026 ' +
|
|
36
|
-
'7:50 AM" — not ISO 8601), subject (when the post has a title), and text. Threaded ' +
|
|
37
|
-
'replies under a post are not included, only the top-level posts. There is no way ' +
|
|
38
|
-
'to choose a different channel from here: ask the user to open the channel they ' +
|
|
39
|
-
'mean first (the Teams-and-Channels view, not Chat), or use ' +
|
|
40
|
-
'teams_list_teams_and_channels to show them what is available.' +
|
|
41
|
-
OPEN_CONVERSATION_DESCRIPTION +
|
|
28
|
+
title: 'List Teams channels',
|
|
29
|
+
description: 'List every channel the signed-in user is in, across all their teams, sorted by team ' +
|
|
30
|
+
'name then channel title. Each has an id, title, team (when Teams makes it ' +
|
|
31
|
+
'determinable), unread hint, last-activity time (ISO 8601), and a last-message preview ' +
|
|
32
|
+
'and sender. Channels the user has hidden in Teams are listed after the rest with ' +
|
|
33
|
+
'hidden: true. Pass an id (or the channel name) to teams_read_conversation to read its ' +
|
|
34
|
+
'posts and replies. Use unread_only for channels with real posts the user has not read, ' +
|
|
35
|
+
'each confirmed by reading past the read marker (a channel that is gone or no longer ' +
|
|
36
|
+
'readable is skipped and counted in skipped_unreachable); hidden channels are left out ' +
|
|
37
|
+
'of it unless include_hidden is set, as Teams shows them no badge. By default unread_only ' +
|
|
38
|
+
'keeps only channels whose newest unread post is from the last 14 days (since_days widens ' +
|
|
39
|
+
'it); older ones are counted in older_unread_skipped, not listed. ' +
|
|
40
|
+
UNREAD_HINT_DESCRIPTION +
|
|
41
|
+
' Listing never marks anything read. query matches the channel title or team name. ' +
|
|
42
|
+
FAVORITES_DESCRIPTION +
|
|
42
43
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
43
44
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
44
|
-
inputSchema: {
|
|
45
|
-
|
|
45
|
+
inputSchema: {
|
|
46
|
+
unread_only: unreadOnlyArg,
|
|
47
|
+
since_days: listSinceDaysArg,
|
|
48
|
+
include_hidden: includeHiddenArg,
|
|
49
|
+
query: queryArg('channel title or team name'),
|
|
50
|
+
limit: limitArg(MAX_CHANNELS, 'channels', 'favorites and pinned first, then by team and title, kept'),
|
|
51
|
+
},
|
|
52
|
+
}, async ({ unread_only, include_hidden, since_days, query, limit }) => {
|
|
46
53
|
try {
|
|
47
|
-
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
54
|
+
// Channels are never untitled group chats, so there is nothing to retitle.
|
|
55
|
+
const { rows, retitle: _retitle, ...unreadInfo } = await listSummaries(chatsvc, {
|
|
56
|
+
kinds: ['channel'],
|
|
57
|
+
unread_only,
|
|
58
|
+
include_hidden,
|
|
59
|
+
since_days,
|
|
60
|
+
query,
|
|
61
|
+
});
|
|
62
|
+
rows.sort(byTeamThenTitle);
|
|
63
|
+
if (!unread_only)
|
|
64
|
+
rows.sort(favoritesFirst);
|
|
65
|
+
const { rows: channels, truncated } = trimRows(rows, limit, 'start', MAX_CHANNELS, 'first');
|
|
66
|
+
return untrustedResult({ channels, ...unreadInfo, ...(truncated ? { truncated } : {}) });
|
|
51
67
|
}
|
|
52
68
|
catch (err) {
|
|
53
|
-
throw
|
|
69
|
+
throw wrapApiError(err, 'list channels');
|
|
54
70
|
}
|
|
55
71
|
});
|
|
56
72
|
}
|
package/dist/tools/chat.js
CHANGED
|
@@ -1,54 +1,59 @@
|
|
|
1
1
|
import { toolAnnotations } from '@chrischall/mcp-utils';
|
|
2
|
-
import {
|
|
2
|
+
import { wrapApiError } from './errors.js';
|
|
3
3
|
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
4
|
+
import { limitArg, trimRows } from './limit.js';
|
|
5
|
+
import { FAVORITES_DESCRIPTION, favoritesFirst, GROUP_TITLE_DESCRIPTION, listSinceDaysArg, listSummaries, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
|
|
6
|
+
/** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
|
|
7
|
+
const MAX_CHATS = 500;
|
|
8
|
+
/** Newest activity first; a chat with no messages at all sorts last. */
|
|
9
|
+
function byLastActivityDesc(a, b) {
|
|
10
|
+
return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
|
|
11
|
+
}
|
|
12
|
+
export function registerChatTools(server, { chatsvc }) {
|
|
7
13
|
server.registerTool('teams_list_chats', {
|
|
8
14
|
title: 'List Teams chats',
|
|
9
|
-
description: 'List
|
|
10
|
-
'
|
|
11
|
-
'
|
|
12
|
-
'
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
catch (err) {
|
|
28
|
-
throw wrapBridgeError(err, 'list chats');
|
|
29
|
-
}
|
|
30
|
-
});
|
|
31
|
-
server.registerTool('teams_get_open_chat_messages', {
|
|
32
|
-
title: 'Read the currently open Teams chat',
|
|
33
|
-
description: 'Read the message thread of whichever Teams chat is CURRENTLY OPEN in the user\'s ' +
|
|
34
|
-
'signed-in browser tab — sender, ISO-8601 time, message id, and text for each message. ' +
|
|
35
|
-
'There is no way to choose a different chat from here (the bridge can only read the DOM, ' +
|
|
36
|
-
'not navigate it): ask the user to open the chat they mean first, or use ' +
|
|
37
|
-
'teams_list_chats to show them what is available. A quoted-reply message\'s text may ' +
|
|
38
|
-
'include the quoted preview concatenated in.' +
|
|
39
|
-
OPEN_CONVERSATION_DESCRIPTION +
|
|
15
|
+
description: 'List every chat the signed-in user is in — 1:1s, group chats and meeting chats, not ' +
|
|
16
|
+
'just the ones visible in the Teams sidebar — favorites and pinned first, then most recent activity. Each has an ' +
|
|
17
|
+
'id, kind (oneOnOne / group / meeting, or self for the user\'s own 48:notes self-chat), ' +
|
|
18
|
+
'title, unread hint, last-activity time (ISO 8601), and a last-message preview and sender. ' +
|
|
19
|
+
GROUP_TITLE_DESCRIPTION +
|
|
20
|
+
' query also matches those participant names. ' +
|
|
21
|
+
FAVORITES_DESCRIPTION +
|
|
22
|
+
' ' +
|
|
23
|
+
'Pass an id (or the title) to teams_read_conversation to read the messages. Use ' +
|
|
24
|
+
'unread_only to find chats with messages the user has not read, exactly as Teams counts ' +
|
|
25
|
+
'them: each candidate is confirmed by reading its messages past the read marker, so a ' +
|
|
26
|
+
'call recording, transcript or other system event never makes a chat unread. By default ' +
|
|
27
|
+
'unread_only keeps only chats whose newest unread message is from the last 14 days ' +
|
|
28
|
+
'(since_days widens it); older ones are counted in older_unread_skipped, not listed. ' +
|
|
29
|
+
UNREAD_HINT_DESCRIPTION +
|
|
30
|
+
' Listing never marks anything read. Channels are listed by teams_list_teams_and_channels instead.' +
|
|
40
31
|
UNTRUSTED_DESCRIPTION_SUFFIX,
|
|
41
32
|
annotations: toolAnnotations({ readOnly: true, openWorld: true }),
|
|
42
|
-
inputSchema: {
|
|
43
|
-
|
|
33
|
+
inputSchema: {
|
|
34
|
+
unread_only: unreadOnlyArg,
|
|
35
|
+
since_days: listSinceDaysArg,
|
|
36
|
+
query: queryArg('chat title or an untitled chat\'s participant names'),
|
|
37
|
+
limit: limitArg(MAX_CHATS, 'chats', 'favorites and pinned first, then most recent activity, kept'),
|
|
38
|
+
},
|
|
39
|
+
}, async ({ unread_only, since_days, query, limit }) => {
|
|
44
40
|
try {
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
41
|
+
const { rows, retitle, errors: _untitledErrors, ...unreadInfo } = await listSummaries(chatsvc, {
|
|
42
|
+
kinds: ['group', 'meeting', 'oneOnOne', 'self'],
|
|
43
|
+
unread_only,
|
|
44
|
+
since_days,
|
|
45
|
+
query,
|
|
46
|
+
});
|
|
47
|
+
rows.sort(byLastActivityDesc);
|
|
48
|
+
if (!unread_only)
|
|
49
|
+
rows.sort(favoritesFirst);
|
|
50
|
+
const { rows: kept, truncated } = trimRows(rows, limit, 'start', MAX_CHATS, unread_only ? 'most recent' : 'first');
|
|
51
|
+
// errors names conversations too, so it is retitled alongside the rows.
|
|
52
|
+
const { rows: chats, errors } = await retitle(kept);
|
|
53
|
+
return untrustedResult({ chats, ...unreadInfo, ...(errors ? { errors } : {}), ...(truncated ? { truncated } : {}) });
|
|
49
54
|
}
|
|
50
55
|
catch (err) {
|
|
51
|
-
throw
|
|
56
|
+
throw wrapApiError(err, 'list chats');
|
|
52
57
|
}
|
|
53
58
|
});
|
|
54
59
|
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Confirm-by-fetch: the one rule every unread answer goes through.
|
|
3
|
+
*
|
|
4
|
+
* The conversation listing cannot say whether a conversation is unread. Live
|
|
5
|
+
* (2026-10-10, a real tenant): `lastimreceivedtime` equals the last message's
|
|
6
|
+
* id even when that is a call recording; `lastMessage` can be stale, showing an
|
|
7
|
+
* older real message while only `Event/Call` and `ThreadActivity/*` came after
|
|
8
|
+
* the horizon; and a meeting chat never opened has no horizon at all. Reading
|
|
9
|
+
* the messages past the horizon matched Teams exactly (0 of 32 meeting-chat
|
|
10
|
+
* candidates were really unread). So the listing only nominates candidates
|
|
11
|
+
* (`isUnreadCandidate`), and a candidate counts as unread only when a read past
|
|
12
|
+
* its horizon finds a real message from someone else (`isUnread`). A candidate
|
|
13
|
+
* that answers 404 or 403 — a channel that is gone, or no longer readable — is
|
|
14
|
+
* not unread; it is skipped and counted, never reported as an error.
|
|
15
|
+
*
|
|
16
|
+
* A `since` window (`since_days`, default {@link DEFAULT_SINCE_DAYS}) keeps
|
|
17
|
+
* only conversations whose newest real unread message is inside it. Live
|
|
18
|
+
* (2026-10-10): 14 of 16 confirmed-unread channels had last moved months or
|
|
19
|
+
* years ago, in teams the user never looks at. A candidate whose newest
|
|
20
|
+
* activity of any kind is already older than the window is skipped without a
|
|
21
|
+
* read; both kinds of skip are counted in `olderSkipped`, never dropped silently.
|
|
22
|
+
*/
|
|
23
|
+
import { errorStatusOf, mapWithConcurrency } from '@chrischall/mcp-utils';
|
|
24
|
+
import { z } from 'zod';
|
|
25
|
+
import { isUnread, newestActivityMs, readHorizon } from '../model.js';
|
|
26
|
+
import { makeLimitedStopAt } from './limit.js';
|
|
27
|
+
/** Candidates read at once. */
|
|
28
|
+
export const CONFIRM_CONCURRENCY = 4;
|
|
29
|
+
export const DEFAULT_SINCE_DAYS = 14;
|
|
30
|
+
export const MAX_SINCE_DAYS = 3650;
|
|
31
|
+
const DAY_MS = 86_400_000;
|
|
32
|
+
/** The optional `since_days` argument shared by every unread answer. */
|
|
33
|
+
export function sinceDaysArg(scope = '') {
|
|
34
|
+
return z
|
|
35
|
+
.number()
|
|
36
|
+
.int()
|
|
37
|
+
.min(1)
|
|
38
|
+
.max(MAX_SINCE_DAYS)
|
|
39
|
+
.optional()
|
|
40
|
+
.describe(`${scope}Only count a conversation as unread when its newest unread message arrived in the last ` +
|
|
41
|
+
`since_days days (default ${DEFAULT_SINCE_DAYS}, max ${MAX_SINCE_DAYS}). Older unread ` +
|
|
42
|
+
'conversations are left out and counted in older_unread_skipped; pass a larger since_days ' +
|
|
43
|
+
'to include them.');
|
|
44
|
+
}
|
|
45
|
+
/** The start of the `since_days` window (epoch ms), measured from now. */
|
|
46
|
+
export function sinceCutoff(sinceDays) {
|
|
47
|
+
return Date.now() - (sinceDays ?? DEFAULT_SINCE_DAYS) * DAY_MS;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* What a result says about conversations the window left out: always the
|
|
51
|
+
* count, and a hint only when something was left out.
|
|
52
|
+
*/
|
|
53
|
+
export function olderUnreadReport(olderSkipped, sinceDays) {
|
|
54
|
+
const days = sinceDays ?? DEFAULT_SINCE_DAYS;
|
|
55
|
+
return {
|
|
56
|
+
older_unread_skipped: olderSkipped,
|
|
57
|
+
...(olderSkipped > 0
|
|
58
|
+
? {
|
|
59
|
+
older_unread_hint: `${olderSkipped} conversation${olderSkipped === 1 ? '' : 's'} with unread activity older than ` +
|
|
60
|
+
`${days} days ${olderSkipped === 1 ? 'was' : 'were'} left out; pass a larger since_days ` +
|
|
61
|
+
`(max ${MAX_SINCE_DAYS}) to include ${olderSkipped === 1 ? 'it' : 'them'}.`,
|
|
62
|
+
}
|
|
63
|
+
: {}),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** A 404 or 403: the conversation is gone or not readable, so it is not unread. */
|
|
67
|
+
export function isUnreachable(err) {
|
|
68
|
+
const status = errorStatusOf(err);
|
|
69
|
+
return status === 404 || status === 403;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Read a conversation's messages past `horizon`, newest first, keeping only
|
|
73
|
+
* the real unread ones (`isUnread`). Stops at the horizon, at the first real
|
|
74
|
+
* unread message past `limit`, or after `maxRaw` raw messages.
|
|
75
|
+
*/
|
|
76
|
+
export async function readUnread(chatsvc, id, horizon, me, { limit, maxRaw }) {
|
|
77
|
+
const wanted = (m) => isUnread(m, horizon, me);
|
|
78
|
+
const limited = makeLimitedStopAt(horizon, wanted, limit);
|
|
79
|
+
let capped = false;
|
|
80
|
+
const fetched = await chatsvc.getMessages(id, {
|
|
81
|
+
stopAt: limited.stopAt,
|
|
82
|
+
max: maxRaw,
|
|
83
|
+
onCapped: () => (capped = true),
|
|
84
|
+
});
|
|
85
|
+
return { messages: fetched.filter(wanted), truncated: limited.truncated || capped };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Read each candidate past its own horizon, {@link CONFIRM_CONCURRENCY} at a
|
|
89
|
+
* time, and keep those with a real unread message. One read failing never
|
|
90
|
+
* costs the others; when every read failed (none confirmed, none came back
|
|
91
|
+
* empty), the first failure is thrown — it is a failure of the call (a revoked
|
|
92
|
+
* token, a rate limit), not of one conversation.
|
|
93
|
+
*
|
|
94
|
+
* With `since` (epoch ms), a candidate whose newest activity predates it is
|
|
95
|
+
* not read at all, and one whose newest real unread message predates it is
|
|
96
|
+
* not kept; both are counted in `olderSkipped`.
|
|
97
|
+
*/
|
|
98
|
+
export async function confirmUnreadCandidates(chatsvc, raw, me, candidates, opts) {
|
|
99
|
+
const byId = new Map(raw.map((c) => [c.id, c]));
|
|
100
|
+
const since = opts.since ?? 0;
|
|
101
|
+
const results = await mapWithConcurrency(candidates, CONFIRM_CONCURRENCY, async (summary) => {
|
|
102
|
+
const conv = byId.get(summary.id) ?? { id: summary.id };
|
|
103
|
+
const newest = newestActivityMs(conv);
|
|
104
|
+
// Nothing at all happened inside the window, so no unread message can be in it.
|
|
105
|
+
if (newest !== undefined && newest < since)
|
|
106
|
+
return { kind: 'older' };
|
|
107
|
+
const horizon = readHorizon(conv);
|
|
108
|
+
try {
|
|
109
|
+
return { kind: 'read', read: await readUnread(chatsvc, summary.id, horizon, me, opts) };
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
const outcome = { confirmed: [], skippedUnreachable: 0, olderSkipped: 0, failed: [] };
|
|
116
|
+
let anyRead = false;
|
|
117
|
+
results.forEach((r, i) => {
|
|
118
|
+
const summary = candidates[i];
|
|
119
|
+
if (r.kind === 'older')
|
|
120
|
+
outcome.olderSkipped++;
|
|
121
|
+
else if (r.kind === 'unreachable')
|
|
122
|
+
outcome.skippedUnreachable++;
|
|
123
|
+
else if (r.kind === 'failed')
|
|
124
|
+
outcome.failed.push({ summary, error: r.error });
|
|
125
|
+
else {
|
|
126
|
+
anyRead = true;
|
|
127
|
+
// Read newest first, so the first message is the newest real unread one.
|
|
128
|
+
const newestUnread = r.read.messages[0];
|
|
129
|
+
if (newestUnread === undefined)
|
|
130
|
+
return;
|
|
131
|
+
if (Number(newestUnread.id) < since)
|
|
132
|
+
outcome.olderSkipped++;
|
|
133
|
+
else
|
|
134
|
+
outcome.confirmed.push({ summary, read: r.read });
|
|
135
|
+
}
|
|
136
|
+
});
|
|
137
|
+
const first = outcome.failed[0];
|
|
138
|
+
if (first !== undefined && !anyRead)
|
|
139
|
+
throw first.error;
|
|
140
|
+
return outcome;
|
|
141
|
+
}
|
|
142
|
+
/** A summary whose unread state a read has settled. */
|
|
143
|
+
export function confirmedSummary(summary, unread) {
|
|
144
|
+
return { ...summary, unread, unread_confirmed: true };
|
|
145
|
+
}
|