@chrischall/microsoft-teams-mcp 0.6.1 → 0.7.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 (41) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/README.md +126 -66
  4. package/dist/auth-fetchproxy.js +25 -63
  5. package/dist/bundle.js +2185 -661
  6. package/dist/capture-window.js +4 -19
  7. package/dist/chatsvc.js +19 -81
  8. package/dist/index.js +2 -0
  9. package/dist/network-error.js +20 -149
  10. package/dist/sharepoint-auth.js +19 -64
  11. package/dist/sharepoint-token-cache.js +2 -12
  12. package/dist/sharepoint.js +7 -33
  13. package/dist/substrate-auth.js +14 -47
  14. package/dist/substrate-token-cache.js +2 -12
  15. package/dist/substrate.js +7 -23
  16. package/dist/token-cache.js +2 -11
  17. package/dist/tools/activity.js +34 -4
  18. package/dist/tools/attachment.js +24 -11
  19. package/dist/tools/changes.js +10 -9
  20. package/dist/tools/channels.js +2 -2
  21. package/dist/tools/chat-search.js +1 -1
  22. package/dist/tools/chat.js +3 -3
  23. package/dist/tools/conversation.js +17 -12
  24. package/dist/tools/cursor.js +6 -6
  25. package/dist/tools/export-attachments.js +114 -0
  26. package/dist/tools/export-format.js +101 -0
  27. package/dist/tools/export.js +550 -0
  28. package/dist/tools/format.js +3 -3
  29. package/dist/tools/from.js +1 -1
  30. package/dist/tools/limit.js +1 -1
  31. package/dist/tools/listing.js +9 -8
  32. package/dist/tools/markread.js +14 -9
  33. package/dist/tools/react.js +10 -11
  34. package/dist/tools/search.js +5 -4
  35. package/dist/tools/send.js +17 -34
  36. package/dist/tools/titles.js +103 -20
  37. package/dist/tools/unread.js +7 -6
  38. package/dist/version.js +1 -1
  39. package/mint.yaml +18 -0
  40. package/package.json +6 -2
  41. package/server.json +9 -2
@@ -28,9 +28,9 @@
28
28
  * `sharepoint-auth.ts` is, so a server run with `TEAMS_DISABLE_FETCHPROXY`
29
29
  * never has to load the bridge to boot.
30
30
  */
31
- import { createBootstrapOpts, createFetchproxyTransport } from '@chrischall/mcp-utils/fetchproxy';
32
- import { bridgeDeadlineMs, captureWindowMs } from './capture-window.js';
33
- import { getWsPort, stripBearer } from './auth-fetchproxy.js';
31
+ import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
32
+ import { captureWindowMs } from './capture-window.js';
33
+ import { createCaptureTransport, getWsPort } from './auth-fetchproxy.js';
34
34
  import { PACKAGE_NAME, VERSION } from './version.js';
35
35
  /** The one request we capture from: a search-service call the Teams tab makes. */
36
36
  export const SUBSTRATE_CAPTURE_DECL = {
@@ -46,59 +46,26 @@ export const SUBSTRATE_CAPTURE_DECL = {
46
46
  * back to the client-side scan.
47
47
  */
48
48
  export const SUBSTRATE_TRUST_DOMAINS = [SUBSTRATE_CAPTURE_DECL.host];
49
- /** Shortest plausible token; guards against an empty or echoed header only. */
50
- const MIN_TOKEN_LENGTH = 100;
51
49
  /**
52
50
  * Capture a Substrate search token from the user's signed-in Teams tab.
53
51
  * Returns the bare token (no `Bearer ` prefix).
54
52
  */
55
53
  export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
56
- // Read per capture, not at import: see `capture-window.ts`.
57
- const windowMs = captureWindowMs(env);
58
- const transport = createFetchproxyTransport({
54
+ return captureBearerHeader({
59
55
  // Same verb set as the other two captures (`capture_request_header` beside
60
56
  // the always-on `fetch`); only the trusted domain differs.
61
- ...createBootstrapOpts({
62
- domains: [...SUBSTRATE_TRUST_DOMAINS],
63
- bootstrap: { captureHeaders: [{ ...SUBSTRATE_CAPTURE_DECL }] },
64
- }),
57
+ captures: [SUBSTRATE_CAPTURE_DECL],
58
+ domains: SUBSTRATE_TRUST_DOMAINS,
59
+ // Read per capture, not at import: see `capture-window.ts`.
60
+ windowMs: captureWindowMs(env),
65
61
  port: getWsPort(),
66
- fetchTimeoutMs: bridgeDeadlineMs(windowMs),
67
- captureWindowMs: windowMs,
68
62
  serverName: PACKAGE_NAME,
69
63
  version: VERSION,
64
+ what: 'a Substrate search token',
65
+ guidance: 'In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top ' +
66
+ 'and press Enter — that is what makes Teams call substrate.office.com, where the token ' +
67
+ 'is read from — then retry. A "not in declared set" error means the ContextMint Bridge ' +
68
+ 'pairing does not trust substrate.office.com yet: re-pair microsoft-teams-mcp once.',
69
+ createTransport: createCaptureTransport,
70
70
  });
71
- try {
72
- // Loads the identity keypair; skipping it makes the first verb throw
73
- // "ensureConnected called before listen()" (see `auth-fetchproxy.ts`).
74
- await transport.start();
75
- try {
76
- const raw = await transport.server.captureRequestHeader({ ...SUBSTRATE_CAPTURE_DECL, timeoutMs: windowMs });
77
- if (typeof raw !== 'string') {
78
- throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: capture returned no header`);
79
- }
80
- const token = stripBearer(raw);
81
- if (token.length < MIN_TOKEN_LENGTH) {
82
- throw new Error(`${SUBSTRATE_CAPTURE_DECL.host}: authorization header was present but too short to be a ` +
83
- `token (${token.length} chars)`);
84
- }
85
- return token;
86
- }
87
- catch (e) {
88
- const detail = e.message;
89
- throw new Error(`could not capture a Substrate search token from the browser (${detail}). ` +
90
- 'In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top ' +
91
- 'and press Enter — that is what makes Teams call substrate.office.com, where the token ' +
92
- 'is read from — then retry. A "not in declared set" error means the ContextMint Bridge ' +
93
- 'pairing does not trust substrate.office.com yet: re-pair microsoft-teams-mcp once.');
94
- }
95
- }
96
- finally {
97
- try {
98
- await transport.close();
99
- }
100
- catch {
101
- /* the token, or the original failure, is what matters */
102
- }
103
- }
104
71
  }
@@ -1,4 +1,4 @@
1
- import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
1
+ import { createFileStatePersistence, isBearerTokens, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
2
  import { parseBoolEnv } from '@chrischall/mcp-utils';
3
3
  import { reportCacheWriteFailure } from './token-cache.js';
4
4
  /**
@@ -16,16 +16,6 @@ export function substrateTokenCachePath(env = process.env) {
16
16
  fileName: 'substrate-token.json',
17
17
  });
18
18
  }
19
- /** Same `BearerTokens` guard as the other caches; copied, as it is module-private there. */
20
- function isToken(raw) {
21
- if (raw === null || typeof raw !== 'object')
22
- return false;
23
- const t = raw;
24
- return (typeof t.accessToken === 'string' &&
25
- t.accessToken !== '' &&
26
- typeof t.expiresAt === 'number' &&
27
- (t.refreshToken === undefined || typeof t.refreshToken === 'string'));
28
- }
29
19
  /**
30
20
  * The Substrate token cache, or `null` when it is off or there is nothing to
31
21
  * cache. Gated like the SharePoint cache: `TEAMS_TOKEN_CACHE` (default on), and
@@ -40,7 +30,7 @@ export function createSubstrateTokenCache(env = process.env) {
40
30
  const file = createFileStatePersistence({
41
31
  filePath: substrateTokenCachePath(env),
42
32
  boundTo: 'fetchproxy',
43
- validate: (raw) => (isToken(raw) ? raw : null),
33
+ validate: (raw) => (isBearerTokens(raw) ? raw : null),
44
34
  });
45
35
  return {
46
36
  load: () => file.load(),
package/dist/substrate.js CHANGED
@@ -50,9 +50,9 @@
50
50
  * As with the other clients, the bridge is touched only to capture the token
51
51
  * (`substrate-auth.ts`); every request is a plain Node `fetch`.
52
52
  */
53
- import { decodeJwtExp, fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
53
+ import { fetchBounded, McpToolError, parseBoolEnv } from '@chrischall/mcp-utils';
54
54
  import { describeTransportFailure } from './network-error.js';
55
- import { TokenManager } from '@chrischall/mcp-utils/session';
55
+ import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
56
56
  import { createSubstrateTokenCache } from './substrate-token-cache.js';
57
57
  export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/api/v2/query';
58
58
  /**
@@ -62,24 +62,10 @@ export const SUBSTRATE_QUERY_URL = 'https://substrate.office.com/searchservice/a
62
62
  * for another capture window. Mode "substrate" forces a fresh attempt.
63
63
  */
64
64
  export const CAPTURE_RETRY_COOLDOWN_MS = 10 * 60 * 1000;
65
- /** Fallback lifetime for a token whose `exp` we cannot read (as in `sharepoint.ts`). */
66
- const UNKNOWN_TOKEN_TTL_MS = 10 * 60 * 1000;
67
- /** Stands in for a refresh token this flow does not have (see `sharepoint.ts`). */
68
- const RECAPTURE_SENTINEL = 'fetchproxy:recapture';
69
65
  /** Per-request deadline, covering the body read. */
70
66
  const REQUEST_TIMEOUT_MS = 30_000;
71
67
  /** A search response is a page of summaries; anything near this is not one. */
72
68
  const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
73
- function toBearerTokens(accessToken) {
74
- let expiresAt;
75
- try {
76
- expiresAt = decodeJwtExp(accessToken) * 1000;
77
- }
78
- catch {
79
- expiresAt = Date.now() + UNKNOWN_TOKEN_TTL_MS;
80
- }
81
- return { accessToken, refreshToken: RECAPTURE_SENTINEL, expiresAt };
82
- }
83
69
  /** Capture lazily, so boot never loads the bridge (see `sharepoint.ts`). */
84
70
  async function captureSubstrateTokenLazily() {
85
71
  const mod = await import('./substrate-auth.js');
@@ -224,20 +210,18 @@ export class SubstrateClient {
224
210
  this.#fetchImpl = opts.fetchImpl ?? ((input, init) => fetch(input, init));
225
211
  const recapture = async () => {
226
212
  try {
227
- const tokens = toBearerTokens(await capture());
213
+ const token = await capture();
228
214
  this.#captureFailure = null;
229
- return tokens;
215
+ return token;
230
216
  }
231
217
  catch (error) {
232
218
  this.#captureFailure = { at: Date.now(), error };
233
219
  throw error;
234
220
  }
235
221
  };
236
- const persistence = createSubstrateTokenCache(env);
237
- this.#manager = new TokenManager({
238
- initial: recapture,
239
- refresh: recapture,
240
- ...(persistence ? { persistence } : {}),
222
+ this.#manager = createCapturedTokenManager({
223
+ capture: recapture,
224
+ persistence: createSubstrateTokenCache(env),
241
225
  });
242
226
  // Like SharePoint, there is no direct-token env var: the bridge is the only source.
243
227
  if (parseBoolEnv('TEAMS_DISABLE_FETCHPROXY', { env })) {
@@ -1,4 +1,4 @@
1
- import { createFileStatePersistence, resolveStateFile, } from '@chrischall/mcp-utils/session';
1
+ import { createFileStatePersistence, isBearerTokens, resolveStateFile, } from '@chrischall/mcp-utils/session';
2
2
  import { readEnvVar, parseBoolEnv } from '@chrischall/mcp-utils';
3
3
  /**
4
4
  * Where the captured chat-service access token is cached between runs.
@@ -15,15 +15,6 @@ export function tokenCachePath(env = process.env) {
15
15
  fileName: 'token.json',
16
16
  });
17
17
  }
18
- function isToken(raw) {
19
- if (raw === null || typeof raw !== 'object')
20
- return false;
21
- const t = raw;
22
- return (typeof t.accessToken === 'string' &&
23
- t.accessToken !== '' &&
24
- typeof t.expiresAt === 'number' &&
25
- (t.refreshToken === undefined || typeof t.refreshToken === 'string'));
26
- }
27
18
  /**
28
19
  * What a cached token is bound to, or `null` when there is nothing worth
29
20
  * caching.
@@ -50,7 +41,7 @@ export function createTokenCache(env = process.env) {
50
41
  return createFileStatePersistence({
51
42
  filePath: tokenCachePath(env),
52
43
  boundTo,
53
- validate: (raw) => (isToken(raw) ? raw : null),
44
+ validate: (raw) => (isBearerTokens(raw) ? raw : null),
54
45
  });
55
46
  }
56
47
  /**
@@ -4,6 +4,7 @@ import { htmlToText } from '../model.js';
4
4
  import { arrivalMs } from './conversation.js';
5
5
  import { sinceCutoff, DEFAULT_SINCE_DAYS, MAX_SINCE_DAYS } from './confirm.js';
6
6
  import { limitArg, trimRows } from './limit.js';
7
+ import { conversationNamer } from './titles.js';
7
8
  import { wrapApiError } from './errors.js';
8
9
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
10
  /** The chat-service conversation that holds the Activity feed. */
@@ -89,18 +90,43 @@ export function activityRow(m) {
89
90
  preview: clip(htmlToText(str(a.messagePreview) ?? '')),
90
91
  };
91
92
  }
93
+ /**
94
+ * `rows` with each conversation named as the listing tools name it
95
+ * (`conversationNamer`): only the conversations of the rows returned, and a
96
+ * conversation the listing does not carry — or a listing that cannot be read —
97
+ * keeps the feed's own topic.
98
+ */
99
+ async function nameRows(name, rows) {
100
+ const names = await name(rows.flatMap((r) => (r.where.conversation_id !== undefined ? [r.where.conversation_id] : [])));
101
+ return rows.map((r) => {
102
+ const n = r.where.conversation_id !== undefined ? names.get(r.where.conversation_id) : undefined;
103
+ if (n === undefined)
104
+ return r;
105
+ return {
106
+ ...r,
107
+ where: {
108
+ ...r.where,
109
+ title: n.title,
110
+ ...(n.team !== undefined ? { team: n.team } : {}),
111
+ ...(n.participants !== undefined ? { participants: n.participants } : {}),
112
+ },
113
+ };
114
+ });
115
+ }
92
116
  const newestFirst = (a, b) => (b.time ?? '').localeCompare(a.time ?? '');
93
117
  export function registerActivityTools(server, { chatsvc }) {
94
- server.registerTool('teams_get_activity', {
118
+ server.registerTool('teams_list_activity', {
95
119
  title: 'Read the Activity feed',
96
120
  description: 'Read the Teams Activity feed (the bell icon) — mentions, reactions, replies, meeting ' +
97
121
  'notices and missed calls across every chat and channel — newest first, through the ' +
98
122
  'Teams chat-service API, so it works without the Activity view (or any particular view) ' +
99
123
  'open in the browser. Each row has id, time (ISO 8601), kind (mention, reaction, reply, ' +
100
124
  'meeting, call or other) with the raw type/subtype, read, from (who did it), where ' +
101
- '(conversation_id, title, type), message_id, reply_chain_id (a channel thread\'s root, when there is one), ' +
125
+ '(conversation_id; title — named as teams_list_conversations names it, so an untitled group chat is ' +
126
+ '"Group chat: A; B; C +N" with its participants and a 1:1 is the other person; type; team for a channel), ' +
127
+ 'message_id, reply_chain_id (a channel thread\'s root, when there is one), ' +
102
128
  'and a plain-text preview (at most 200 characters). Pass where.conversation_id to ' +
103
- 'teams_read_conversation to read the message in context. unread_only keeps rows the user ' +
129
+ 'teams_list_messages to read the message in context. unread_only keeps rows the user ' +
104
130
  'has not seen; kinds narrows to some buckets; since_days (default 14) sets how far back ' +
105
131
  'to look. This does NOT mark anything read — the user\'s Activity badge is unaffected.' +
106
132
  UNTRUSTED_DESCRIPTION_SUFFIX,
@@ -127,6 +153,8 @@ export function registerActivityTools(server, { chatsvc }) {
127
153
  },
128
154
  }, async ({ unread_only, kinds, since_days, limit }) => {
129
155
  try {
156
+ // The listing that names the rows is read alongside the feed scan, not after it.
157
+ const name = conversationNamer(chatsvc);
130
158
  const cutoff = sinceCutoff(since_days);
131
159
  let scanCapped = false;
132
160
  const entries = await chatsvc.getMessages(ACTIVITY_FEED_ID, {
@@ -147,8 +175,10 @@ export function registerActivityTools(server, { chatsvc }) {
147
175
  .filter((r) => !unread_only || !r.read)
148
176
  .filter((r) => wanted === undefined || wanted.has(r.kind))
149
177
  .sort(newestFirst);
178
+ const trimmed = trimRows(rows, limit, 'start', MAX_ROWS);
150
179
  return untrustedResult({
151
- ...trimRows(rows, limit, 'start', MAX_ROWS),
180
+ ...trimmed,
181
+ rows: await nameRows(name, trimmed.rows),
152
182
  ...(scanCapped
153
183
  ? {
154
184
  scan_capped: {
@@ -3,6 +3,7 @@ import { McpToolError, errorKindOf, errorStatusOf, toolAnnotations } from '@chri
3
3
  import { normaliseMessage } from '../model.js';
4
4
  import { wrapApiError } from './errors.js';
5
5
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
6
+ import { nameConversations } from './titles.js';
6
7
  /**
7
8
  * Raw messages read looking for the one asked for (20 pages of 200). The
8
9
  * `stopAt` boundary — paging past the message's arrival time — is the real
@@ -14,7 +15,7 @@ const MAX_RAW_MESSAGES = 4000;
14
15
  * this the bounded read in `SharePointClient` aborts and the file degrades to
15
16
  * metadata + link — a file this big belongs behind its link, not in a result.
16
17
  */
17
- const MAX_FILE_BYTES = 25 * 1024 * 1024;
18
+ export const MAX_FILE_BYTES = 25 * 1024 * 1024;
18
19
  const FILE_HINT = 'A shared file is downloaded from SharePoint and returned as its contents (an image as an image, ' +
19
20
  'anything else as an embedded resource). The first file from a given SharePoint host may need ' +
20
21
  'opening once in Teams to mint a short-lived token; a file your account cannot open comes back as ' +
@@ -23,20 +24,22 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
23
24
  server.registerTool('teams_get_attachment', {
24
25
  title: 'Get a Teams message attachment',
25
26
  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
+ 'teams_list_messages / teams_list_unread_messages. An inline image (attachments.images[].ref) ' +
27
28
  'is returned as the image itself. A shared file (attachments.files[].name) is downloaded ' +
28
29
  'from SharePoint and returned as its contents: an image as the image, anything else as an ' +
29
30
  'embedded resource carrying the bytes. The first file from a given SharePoint host in a ' +
30
31
  'session may need opening once in Teams to mint a short-lived token; a file your account ' +
31
32
  '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
+ 'instead of failing. Its caption names the conversation beside its id: title (as teams_list_conversations ' +
34
+ 'names it — an untitled group chat by its participants, a 1:1 by the other person) and participants. ' +
35
+ 'Does not mark anything read.' +
33
36
  UNTRUSTED_DESCRIPTION_SUFFIX,
34
37
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
35
38
  inputSchema: {
36
39
  conversation: z
37
40
  .string()
38
41
  .min(1)
39
- .describe('The conversation id the message is in (from teams_read_conversation or teams_get_unread).'),
42
+ .describe('The conversation id the message is in (from teams_list_messages or teams_list_unread_messages).'),
40
43
  message_id: z.string().min(1).describe('The message id, exactly as a message listing returned it.'),
41
44
  ref: z
42
45
  .string()
@@ -53,11 +56,13 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
53
56
  const raw = fetched.find((m) => m.id === message_id);
54
57
  if (raw === undefined) {
55
58
  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.',
59
+ hint: 'Pass the conversation id and message id exactly as teams_list_messages returned them.',
57
60
  });
58
61
  }
59
62
  // Only the attachments are read, so whose message it is does not matter.
60
63
  const message = normaliseMessage(raw, '');
64
+ // Named while the attachment is fetched; naming never throws, so it never fails the call.
65
+ const naming = nameConversations(chatsvc, [conversation]).then((names) => nameFields(names.get(conversation)));
61
66
  const image = message.attachments.images.find((i) => i.ref === ref);
62
67
  if (image !== undefined) {
63
68
  const { mimeType, data } = await chatsvc.fetchImage(image.url);
@@ -68,6 +73,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
68
73
  ref,
69
74
  message_id,
70
75
  conversation,
76
+ ...(await naming),
71
77
  sender: message.sender,
72
78
  time: message.time,
73
79
  mimeType,
@@ -79,12 +85,12 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
79
85
  }
80
86
  const file = message.attachments.files.find((f) => f.name === ref);
81
87
  if (file !== undefined) {
82
- return downloadSharedFile(sharepoint, file, message, { conversation, message_id });
88
+ return downloadSharedFile(sharepoint, file, message, { conversation, message_id }, naming);
83
89
  }
84
90
  const { images, files } = message.attachments;
85
91
  throw new McpToolError(`Message ${message_id} has no attachment "${ref}".`, {
86
92
  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.',
93
+ 'image ref or a file name exactly as teams_list_messages listed it.',
88
94
  });
89
95
  }
90
96
  catch (err) {
@@ -99,7 +105,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
99
105
  * `downloadFile` error and returns today's metadata result with a hint saying
100
106
  * why. A file with no `url` at all (nothing to download) takes the same path.
101
107
  */
102
- async function downloadSharedFile(sharepoint, file, message, ids) {
108
+ async function downloadSharedFile(sharepoint, file, message, ids, naming) {
103
109
  if (file.url === undefined) {
104
110
  return untrustedResult({ ...file, content_available: false, hint: FILE_HINT });
105
111
  }
@@ -119,6 +125,7 @@ async function downloadSharedFile(sharepoint, file, message, ids) {
119
125
  time: message.time,
120
126
  message_id: ids.message_id,
121
127
  conversation: ids.conversation,
128
+ ...(await naming),
122
129
  });
123
130
  if (mimeType.startsWith('image/')) {
124
131
  return { content: [{ type: 'image', data: data.toString('base64'), mimeType }, ...caption.content] };
@@ -144,8 +151,13 @@ async function downloadSharedFile(sharepoint, file, message, ids) {
144
151
  return untrustedResult({ ...file, content_available: false, hint: degradeHint(err, hostOf(file.url)) });
145
152
  }
146
153
  }
154
+ function nameFields(n) {
155
+ if (n === undefined)
156
+ return {};
157
+ return { title: n.title, ...(n.participants !== undefined ? { participants: n.participants } : {}) };
158
+ }
147
159
  /** The host of the file's url, for the degrade hint; a stand-in if it will not parse. */
148
- function hostOf(url) {
160
+ export function hostOf(url) {
149
161
  try {
150
162
  return new URL(url).hostname;
151
163
  }
@@ -154,12 +166,13 @@ function hostOf(url) {
154
166
  }
155
167
  }
156
168
  /**
157
- * Why a shared file degraded to metadata + link, as a user-facing hint.
169
+ * Why a shared file degraded to metadata + link, as a user-facing hint (also
170
+ * why `teams_export_messages` skipped one).
158
171
  * `SharePointClient` throws `McpToolError`s carrying `status`/`kind`/`hint`; a
159
172
  * token-capture failure arrives as a plain `Error`. Branch on structure, not
160
173
  * message text (fleet convention).
161
174
  */
162
- function degradeHint(err, host) {
175
+ export function degradeHint(err, host) {
163
176
  if (errorStatusOf(err) === 403) {
164
177
  return (`Your account cannot open this file, or it is on a SharePoint host (${host}) your captured ` +
165
178
  'token does not cover. Open it once in a signed-in Teams tab, then retry.');
@@ -3,7 +3,7 @@ import { mapWithConcurrency, McpToolError, toolAnnotations } from '@chrischall/m
3
3
  import { conversationSummary, changedMs, isUserMessage, lastChangeMs, normaliseMessage, } from '../model.js';
4
4
  import { isUnreachable } from './confirm.js';
5
5
  import { includeHiddenArg } from './listing.js';
6
- import { enrichTitles } from './titles.js';
6
+ import { enrichTitles, participantsOf } from './titles.js';
7
7
  import { wrapApiError } from './errors.js';
8
8
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
9
  import { CURSOR_NO_CACHE_DESCRIPTION } from './cursor.js';
@@ -28,7 +28,7 @@ export function encodeChangesCursor(t) {
28
28
  function badCursor(cursor) {
29
29
  return new McpToolError(`"${cursor}" is not a changes cursor.`, {
30
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.',
31
+ 'A message id (digits) is not a changes cursor: pass it to teams_list_messages as after_message_id.',
32
32
  });
33
33
  }
34
34
  /** The epoch ms a `cursor` names: a token from {@link encodeChangesCursor}, or an ISO 8601 time. */
@@ -97,7 +97,7 @@ async function readChanges(chatsvc, summary, t, me) {
97
97
  };
98
98
  }
99
99
  export function registerChangesTools(server, { chatsvc }) {
100
- server.registerTool('teams_get_changes', {
100
+ server.registerTool('teams_list_changed_conversations', {
101
101
  title: 'Get Teams conversations with new messages',
102
102
  description: 'List the chats and channels that got new messages since a cursor, most recent first — counts, not ' +
103
103
  'the messages: each with its summary (id, kind, title, team), new_message_count (real messages ' +
@@ -105,10 +105,10 @@ export function registerChangesTools(server, { chatsvc }) {
105
105
  'new_from_others_count, newest_time and, for a channel, threads: one { root_id, new_root, ' +
106
106
  'new_reply_count } per thread the new messages landed in, including a thread whose root post is ' +
107
107
  'older than the cursor, and after_message_id: read the messages it counted with ' +
108
- 'teams_read_conversation({ conversation: <its id>, after_message_id: <its after_message_id> }). ' +
108
+ 'teams_list_messages({ conversation: <its id>, after_message_id: <its after_message_id> }). ' +
109
109
  'Two cursor kinds, not interchangeable: this tool\'s cursor/next_cursor is a time token for ' +
110
- 'teams_get_changes only and is not a message id; after_message_id is a message-id cursor (ids are ' +
111
- 'arrival ms, so it is the cursor time as an id) for teams_read_conversation (or teams_get_unread ' +
110
+ 'teams_list_changed_conversations only and is not a message id; after_message_id is a message-id cursor (ids are ' +
111
+ 'arrival ms, so it is the cursor time as an id) for teams_list_messages (or teams_list_unread_messages ' +
112
112
  'cursors). Without cursor it looks back 24 hours. next_cursor is an opaque token — pass it back as ' +
113
113
  'cursor to get only what arrived since this call (cursor also takes a plain ISO 8601 time). It is ' +
114
114
  'at-least-once: a conversation can come back again but none is skipped; it stays at the input ' +
@@ -128,9 +128,9 @@ export function registerChangesTools(server, { chatsvc }) {
128
128
  .string()
129
129
  .min(1)
130
130
  .optional()
131
- .describe("A previous teams_get_changes result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): " +
131
+ .describe("A previous teams_list_changed_conversations result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): " +
132
132
  'only messages that arrived after it count. Default: 24 hours ago. Not a message id, and not ' +
133
- "teams_read_conversation's next_cursor."),
133
+ "teams_list_messages's next_cursor."),
134
134
  kinds: z
135
135
  .array(z.enum(Object.keys(KIND_FILTERS)))
136
136
  .min(1)
@@ -194,7 +194,7 @@ export function registerChangesTools(server, { chatsvc }) {
194
194
  ...rest.map((c) => c.summary),
195
195
  ...failed.map((f) => f.summary),
196
196
  ]);
197
- // The read_conversation hand-off: a message id is its arrival ms, so the cursor time as an id
197
+ // The list_messages hand-off: a message id is its arrival ms, so the cursor time as an id
198
198
  // stops that read exactly where this one stopped counting.
199
199
  const after_message_id = String(Math.floor(t));
200
200
  const conversations = shown.map(({ read }, i) => ({
@@ -209,6 +209,7 @@ export function registerChangesTools(server, { chatsvc }) {
209
209
  const more = rest.map(({ read }, i) => ({
210
210
  id: titled[shown.length + i].id,
211
211
  title: titled[shown.length + i].title,
212
+ ...participantsOf(titled[shown.length + i]),
212
213
  new_message_count: read.count,
213
214
  after_message_id,
214
215
  }));
@@ -24,13 +24,13 @@ function byTeamThenTitle(a, b) {
24
24
  return a.title.localeCompare(b.title, undefined, { sensitivity: 'base' });
25
25
  }
26
26
  export function registerChannelTools(server, { chatsvc }) {
27
- server.registerTool('teams_list_teams_and_channels', {
27
+ server.registerTool('teams_list_channels', {
28
28
  title: 'List Teams channels',
29
29
  description: 'List every channel the signed-in user is in, across all their teams, sorted by team ' +
30
30
  'name then channel title. Each has an id, title, team (when Teams makes it ' +
31
31
  'determinable), unread hint, last-activity time (ISO 8601), and a last-message preview ' +
32
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 ' +
33
+ 'hidden: true. Pass an id (or the channel name) to teams_list_messages to read its ' +
34
34
  'posts and replies. Use unread_only for channels with real posts the user has not read, ' +
35
35
  'each confirmed by reading past the read marker (a channel that is gone or no longer ' +
36
36
  'readable is skipped and counted in skipped_unreachable); hidden channels are left out ' +
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `teams_list_chats`' opt-in `search_messages`: a query matched against what
2
+ * `teams_list_conversations`' opt-in `search_messages`: a query matched against what
3
3
  * was said in each chat, not only what the chat is called.
4
4
  *
5
5
  * The chat service has no search call this server can reach, so each chat no
@@ -49,7 +49,7 @@ function sortChats(rows, sort, unreadOnly) {
49
49
  rows.sort(favoritesFirst);
50
50
  }
51
51
  export function registerChatTools(server, { chatsvc }) {
52
- server.registerTool('teams_list_chats', {
52
+ server.registerTool('teams_list_conversations', {
53
53
  title: 'List Teams chats',
54
54
  description: 'List every chat the signed-in user is in — 1:1s, group chats and meeting chats, not ' +
55
55
  'just the ones visible in the Teams sidebar — favorites and pinned first, then most recent activity. Each has an ' +
@@ -61,7 +61,7 @@ export function registerChatTools(server, { chatsvc }) {
61
61
  ' search_messages extends the match to each chat\'s recent messages. ' +
62
62
  FAVORITES_DESCRIPTION +
63
63
  ' ' +
64
- 'Pass an id (or the title) to teams_read_conversation to read the messages. Use ' +
64
+ 'Pass an id (or the title) to teams_list_messages to read the messages. Use ' +
65
65
  'unread_only to find chats with messages the user has not read, exactly as Teams counts ' +
66
66
  'them: each candidate is confirmed by reading its messages past the read marker, so a ' +
67
67
  'call recording, transcript or other system event never makes a chat unread. By default ' +
@@ -73,7 +73,7 @@ export function registerChatTools(server, { chatsvc }) {
73
73
  ' since / until (ISO 8601 date-times) keep chats whose last activity falls in that window; ' +
74
74
  'sort picks the order: activity (default, as above), activity_only (most recent first, ' +
75
75
  'ignoring favorites and pinned) or title (alphabetical, case-insensitive).' +
76
- ' Listing never marks anything read (teams_mark_read does). Channels are listed by teams_list_teams_and_channels instead.' +
76
+ ' Listing never marks anything read (teams_mark_read does). Channels are listed by teams_list_channels instead.' +
77
77
  UNTRUSTED_DESCRIPTION_SUFFIX,
78
78
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
79
79
  inputSchema: {
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, McpToolError, toolAnnotations, } from '@chrischall/mcp-utils';
3
3
  import { isUnread, isUserMessage, matchConversations, normaliseMessage, oldestFirst, readHorizon, SELF_CHAT_ALIASES, summariseAll, } from '../model.js';
4
4
  import { confirmedSummary } from './confirm.js';
5
- import { enrichTitles } from './titles.js';
5
+ import { conversationName, enrichTitles } from './titles.js';
6
6
  import { wrapApiError } from './errors.js';
7
7
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
8
8
  import { DEFAULT_LIMIT, limitArg, makeLimitedStopAt, sinceArg } from './limit.js';
@@ -45,7 +45,7 @@ function describeCandidate(s) {
45
45
  /**
46
46
  * A name that matched several conversations. It is an `McpToolError` — the
47
47
  * write tools let it through, as a write must never guess — that also carries
48
- * every match, so `teams_read_conversation` can return the candidates as data.
48
+ * every match, so `teams_list_messages` can return the candidates as data.
49
49
  */
50
50
  export class AmbiguousConversationError extends McpToolError {
51
51
  query;
@@ -94,7 +94,7 @@ export function resolveConversation(summaries, conversation, verb) {
94
94
  const matches = matchConversations(summaries, conversation);
95
95
  if (matches.length === 0) {
96
96
  throw new McpToolError(`No chat or channel matches "${conversation}".`, {
97
- hint: 'List them with teams_list_chats or teams_list_teams_and_channels and pass an id.',
97
+ hint: 'List them with teams_list_conversations or teams_list_channels and pass an id.',
98
98
  });
99
99
  }
100
100
  if (matches.length > 1)
@@ -110,7 +110,7 @@ export function resolveConversation(summaries, conversation, verb) {
110
110
  * share a last sender, or a 1:1 the user wrote in last. The whole-listing
111
111
  * titling runs once, however many names the resolver is asked for.
112
112
  */
113
- function listedResolver(chatsvc, raw, me, verb) {
113
+ export function listedResolver(chatsvc, raw, me, verb) {
114
114
  const summaries = summariseAll(raw, me);
115
115
  let titled;
116
116
  return async (conversation) => {
@@ -250,11 +250,15 @@ async function readOne(chatsvc, raw, me, summary, opts) {
250
250
  };
251
251
  return { summary, conv, newest, ...(skip !== undefined ? { skip } : {}), result };
252
252
  }
253
- function readError(conversation, err, id) {
253
+ /**
254
+ * A failed read, as `errors` lists it: the argument as passed and, once it
255
+ * resolved, the conversation's id and name (title, kind, team, participants).
256
+ */
257
+ function readError(conversation, err, resolved) {
254
258
  const e = wrapApiError(err, 'read this conversation');
255
259
  return {
256
260
  conversation,
257
- ...(id !== undefined ? { id } : {}),
261
+ ...(resolved !== undefined ? conversationName(resolved) : {}),
258
262
  error: e.message,
259
263
  ...(e.hint !== undefined ? { hint: e.hint } : {}),
260
264
  };
@@ -295,7 +299,7 @@ async function readMany(chatsvc, raw, me, conversations, opts) {
295
299
  return { ok: true, result: await readOne(chatsvc, raw, me, slot.summary, opts) };
296
300
  }
297
301
  catch (err) {
298
- return { ok: false, error: readError(slot.asked, err, slot.summary.id) };
302
+ return { ok: false, error: readError(slot.asked, err, slot.summary) };
299
303
  }
300
304
  });
301
305
  const results = [];
@@ -311,10 +315,10 @@ async function readMany(chatsvc, raw, me, conversations, opts) {
311
315
  return { reads: results, errors };
312
316
  }
313
317
  export function registerConversationTools(server, { chatsvc }) {
314
- server.registerTool('teams_read_conversation', {
318
+ server.registerTool('teams_list_messages', {
315
319
  title: 'Read a Teams chat or channel',
316
320
  description: 'Read the messages of any chat or channel the signed-in user is in, by id (from ' +
317
- 'teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in ' +
321
+ 'teams_list_conversations / teams_list_channels) or by name, without opening it in ' +
318
322
  'Teams. "48:notes" (or the name "notes" / "self") is the user\'s own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, ' +
319
323
  'text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, ' +
320
324
  'each root post with its replies. A root older than the window is fetched and marked outside_window: ' +
@@ -326,14 +330,15 @@ export function registerConversationTools(server, { chatsvc }) {
326
330
  'unread_count only covers what limit/since/after_message_id let through). after_message_id returns only ' +
327
331
  'messages newer than that id; next_cursor is the newest returned message id (or after_message_id ' +
328
332
  'when nothing is new) — pass it back as after_message_id to read only what arrived since. ' +
329
- 'after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that ' +
330
- "row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). " +
333
+ 'after_message_id takes message-id cursors only: to read what teams_list_changed_conversations counted, pass that ' +
334
+ "row's after_message_id, never teams_list_changed_conversations' next_cursor (a time token for teams_list_changed_conversations). " +
331
335
  CURSOR_NO_CACHE_DESCRIPTION +
332
336
  FORMAT_DESCRIPTION +
333
337
  `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then ` +
334
338
  '{ conversations: [...], errors, fetched_at }, one single-read result per conversation (the other ' +
335
339
  'arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ' +
336
340
  '... } object a single read returns, and one that cannot be resolved or read is listed in errors ' +
341
+ '(the argument as passed and, once it resolved, its id, title, kind, team and participants) ' +
337
342
  'while the rest still come back. ' +
338
343
  FROM_DESCRIPTION +
339
344
  'With from, limit keeps the OLDEST messages, unread_only pages only unread ones, and since, ' +
@@ -417,7 +422,7 @@ export function registerConversationTools(server, { chatsvc }) {
417
422
  plans.push({ summary, previous: horizonMessageId(conv), target: newest });
418
423
  }
419
424
  if (plans.length > 0) {
420
- const gate = await confirmMarks(ctx, { tool: 'teams_read_conversation', me, plans, confirmToken });
425
+ const gate = await confirmMarks(ctx, { tool: 'teams_list_messages', me, plans, confirmToken });
421
426
  if (gate)
422
427
  return gate;
423
428
  }