@chrischall/microsoft-teams-mcp 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/README.md +577 -93
  4. package/dist/auth-fetchproxy.js +138 -0
  5. package/dist/bundle.js +44324 -37483
  6. package/dist/capture-window.js +41 -0
  7. package/dist/chatsvc.js +580 -0
  8. package/dist/compose.js +241 -0
  9. package/dist/deps.js +1 -0
  10. package/dist/index.js +35 -6
  11. package/dist/model.js +603 -0
  12. package/dist/sharepoint-auth.js +162 -0
  13. package/dist/sharepoint-token-cache.js +105 -0
  14. package/dist/sharepoint.js +289 -0
  15. package/dist/substrate-auth.js +104 -0
  16. package/dist/substrate-token-cache.js +64 -0
  17. package/dist/substrate.js +319 -0
  18. package/dist/token-cache.js +67 -0
  19. package/dist/tools/activity.js +155 -19
  20. package/dist/tools/attachment.js +174 -0
  21. package/dist/tools/changes.js +241 -0
  22. package/dist/tools/channels.js +62 -44
  23. package/dist/tools/chat-search.js +65 -0
  24. package/dist/tools/chat.js +121 -41
  25. package/dist/tools/confirm.js +188 -0
  26. package/dist/tools/conversation.js +394 -30
  27. package/dist/tools/cursor.js +43 -0
  28. package/dist/tools/errors.js +18 -17
  29. package/dist/tools/format.js +135 -0
  30. package/dist/tools/healthcheck.js +91 -27
  31. package/dist/tools/limit.js +43 -12
  32. package/dist/tools/listing.js +180 -0
  33. package/dist/tools/markread.js +246 -0
  34. package/dist/tools/react.js +217 -0
  35. package/dist/tools/roots.js +73 -0
  36. package/dist/tools/search.js +426 -0
  37. package/dist/tools/send.js +309 -0
  38. package/dist/tools/timezone.js +38 -0
  39. package/dist/tools/titles.js +180 -0
  40. package/dist/tools/unread.js +263 -0
  41. package/dist/tools/untrusted.js +16 -1
  42. package/dist/version.js +1 -1
  43. package/mint.yaml +75 -20
  44. package/package.json +1 -2
  45. package/server.json +87 -3
  46. package/skills/teams-fpx/SKILL.md +111 -92
  47. package/skills/teams-fpx/references/chatsvc-recipes.md +151 -0
  48. package/skills/teams-fpx/references/teams-env.sh +146 -0
  49. package/dist/client.js +0 -290
  50. 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
+ }
@@ -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
+ }
@@ -1,56 +1,74 @@
1
1
  import { toolAnnotations } from '@chrischall/mcp-utils';
2
- import { wrapBridgeError } from './errors.js';
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
- export function registerChannelTools(server, client) {
5
+ import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, MATCH_REASON_DESCRIPTION, 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 and their channels',
9
- description: 'List the Teams the signed-in user belongs to and their channels, from the ' +
10
- '"Teams" nav section\'s sidebar (a DIFFERENT view from Chat). Each row is a team or ' +
11
- 'a channel — itemType distinguishes them; a channel row\'s teamName names its parent ' +
12
- 'team. Requires the user\'s browser to have the Teams-and-Channels view open (not ' +
13
- 'Chat) — if it returns nothing, ask them to click "Teams" in the left nav.' +
14
- UNTRUSTED_DESCRIPTION_SUFFIX,
15
- annotations: toolAnnotations({ readOnly: true, openWorld: true }),
16
- inputSchema: { limit: limitArg(300, 'team and channel rows') },
17
- }, async ({ limit }) => {
18
- try {
19
- const rows = await client.listTeamsAndChannels();
20
- return untrustedResult(rows.length > 0
21
- ? trimRows(rows, limit, 'start', 300)
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 (teams_mark_read does). query matches the channel title, team name or last-message preview. ' +
42
+ MATCH_REASON_DESCRIPTION +
43
+ ' ' +
44
+ FAVORITES_DESCRIPTION +
42
45
  UNTRUSTED_DESCRIPTION_SUFFIX,
43
46
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
44
- inputSchema: { limit: limitArg(200, 'posts') },
45
- }, async ({ limit }) => {
47
+ inputSchema: {
48
+ unread_only: unreadOnlyArg,
49
+ since_days: listSinceDaysArg,
50
+ include_hidden: includeHiddenArg,
51
+ query: queryArg('channel title, team name or last-message preview'),
52
+ limit: limitArg(MAX_CHANNELS, 'channels', 'favorites and pinned first, then by team and title, kept'),
53
+ },
54
+ }, async ({ unread_only, include_hidden, since_days, query, limit }) => {
46
55
  try {
47
- const all = await client.getOpenChannelPosts();
48
- const identity = await readOpenConversation(client, 'channel');
49
- const { rows: posts, truncated } = trimRows(all, limit, 'end', 200);
50
- return untrustedResult({ ...identity, posts, ...(truncated ? { truncated } : {}) });
56
+ // Channels are never untitled group chats, so there is nothing to retitle.
57
+ const { rows, retitle: _retitle, ...unreadInfo } = await listSummaries(chatsvc, {
58
+ kinds: ['channel'],
59
+ unread_only,
60
+ include_hidden,
61
+ since_days,
62
+ query,
63
+ });
64
+ rows.sort(byTeamThenTitle);
65
+ if (!unread_only)
66
+ rows.sort(favoritesFirst);
67
+ const { rows: channels, truncated } = trimRows(rows, limit, 'start', MAX_CHANNELS, 'first');
68
+ return untrustedResult({ channels, ...unreadInfo, ...(truncated ? { truncated } : {}) });
51
69
  }
52
70
  catch (err) {
53
- throw wrapBridgeError(err, 'read the open channel');
71
+ throw wrapApiError(err, 'list channels');
54
72
  }
55
73
  });
56
74
  }
@@ -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
+ }