@chrischall/microsoft-teams-mcp 0.6.2 → 0.8.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/dist/chatsvc.js CHANGED
@@ -23,6 +23,7 @@ import { decodeJwtClaim, fetchBounded, errorKindOf, McpToolError, parseBoolEnv,
23
23
  import { createCapturedTokenManager } from '@chrischall/mcp-utils/session';
24
24
  import { createTokenCache, reportCacheWriteFailure } from './token-cache.js';
25
25
  import { SELF_CHAT } from './model.js';
26
+ import { isAmsObjectId, transcriptUrl } from './transcript.js';
26
27
  import { describeTransportFailure } from './network-error.js';
27
28
  /**
28
29
  * Load the bridge bootstrap lazily.
@@ -59,6 +60,8 @@ const MAX_MESSAGE_PAGES = 20;
59
60
  const DEFAULT_MESSAGE_PAGE_SIZE = 200;
60
61
  /** Largest inline image we will buffer (they measured 8–18 KB live). */
61
62
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
63
+ /** Largest meeting transcript read (a multi-hour meeting is a few hundred KB of WebVTT). */
64
+ const MAX_TRANSCRIPT_BYTES = 20 * 1024 * 1024;
62
65
  /**
63
66
  * Inline images live on Skype's AMS object store (`us-api.asm.skype.com`, the
64
67
  * host varies by region). The bearer is sent ONLY to hosts under this suffix.
@@ -101,9 +104,9 @@ function outcomeUnknown(method, e, hint) {
101
104
  return e;
102
105
  return new WriteOutcomeUnknownError('Teams', method, { cause: e, hint });
103
106
  }
104
- const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_read_conversation) before retrying; do not resend blindly.';
105
- const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_read_conversation) before retrying.';
106
- const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_read_conversation) before retrying; ' +
107
+ const SEND_OUTCOME_HINT = 'The message may already have been posted — check the conversation (teams_list_messages) before retrying; do not resend blindly.';
108
+ const REACTION_OUTCOME_HINT = 'The reaction change may already have been applied — check the message (teams_list_messages) before retrying.';
109
+ const HORIZON_OUTCOME_HINT = 'The read marker may already have moved — check the conversation (teams_list_messages) before retrying; ' +
107
110
  'moving it again to the same message is harmless.';
108
111
  export class ChatServiceClient {
109
112
  #baseUrl;
@@ -265,6 +268,8 @@ export class ChatServiceClient {
265
268
  if (stopped)
266
269
  return out;
267
270
  url = this.#nextLink(body);
271
+ if (url !== undefined)
272
+ await opts.onPage?.(page + 1, out.length);
268
273
  }
269
274
  return out;
270
275
  }
@@ -394,6 +399,38 @@ export class ChatServiceClient {
394
399
  }
395
400
  }
396
401
  }
402
+ /**
403
+ * Download a meeting transcript (WebVTT) from Teams' object store, by the
404
+ * recording's AMS object id (`transcript.ts`). The URL is built here from an
405
+ * id of the vetted shape, never taken from message content, so the bearer
406
+ * only ever goes to the Teams gateway. Served even when the meeting's
407
+ * organizer disabled transcript download (verified live 2026-11-04). A 404 is
408
+ * a transcript the store no longer holds (it expires after some weeks).
409
+ */
410
+ async fetchTranscript(objectId) {
411
+ this.#requireConfigured();
412
+ if (!isAmsObjectId(objectId)) {
413
+ throw new McpToolError(`Refusing to fetch a transcript for ${JSON.stringify(objectId)}: not a Teams object id.`, {
414
+ hint: 'Pass a recording_id exactly as teams_get_transcript listed it.',
415
+ });
416
+ }
417
+ const { status, headers, body } = await this.#send(transcriptUrl(objectId), 'bytes', MAX_TRANSCRIPT_BYTES);
418
+ if (status === 404) {
419
+ throw new McpToolError('This transcript is no longer available from Teams (404): it has expired or was removed.', {
420
+ status,
421
+ kind: 'http',
422
+ hint: "Teams' own copy of a transcript expires after some weeks. The recording's play_url may still open it " +
423
+ 'in the browser if the organizer kept the recording.',
424
+ });
425
+ }
426
+ this.#checkStatus(status);
427
+ const mimeType = (headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
428
+ const text = Buffer.from(body).toString('utf8');
429
+ if (mimeType !== 'text/vtt' && !text.replace(/^\uFEFF/, '').startsWith('WEBVTT')) {
430
+ throw new McpToolError(`Teams returned ${mimeType || 'an unknown type'} instead of a transcript.`, { status, kind: 'http' });
431
+ }
432
+ return text;
433
+ }
397
434
  async #getImage(target) {
398
435
  const { status, headers, body } = await this.#send(target.toString(), 'bytes', MAX_IMAGE_BYTES);
399
436
  this.#checkStatus(status);
package/dist/index.js CHANGED
@@ -16,6 +16,8 @@ import { registerMarkReadTools } from './tools/markread.js';
16
16
  import { registerActivityTools } from './tools/activity.js';
17
17
  import { registerSearchTools } from './tools/search.js';
18
18
  import { registerHealthcheckTool } from './tools/healthcheck.js';
19
+ import { registerExportTools } from './tools/export.js';
20
+ import { registerTranscriptTools } from './tools/transcript.js';
19
21
  loadDotenvSafely();
20
22
  /**
21
23
  * Built HERE, in the caller, not inside a registrar — see office-outlook-mcp
@@ -48,6 +50,8 @@ await runMcp({
48
50
  registerMarkReadTools,
49
51
  registerActivityTools,
50
52
  registerSearchTools,
53
+ registerExportTools,
54
+ registerTranscriptTools,
51
55
  registerHealthcheckTool,
52
56
  ],
53
57
  });
package/dist/model.js CHANGED
@@ -289,7 +289,7 @@ const NAMED_ENTITIES = {
289
289
  apos: "'",
290
290
  nbsp: ' ',
291
291
  };
292
- function decodeEntities(s) {
292
+ export function decodeEntities(s) {
293
293
  // One pass, so `&amp;lt;` becomes `&lt;` and not `<`.
294
294
  return s.replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z]+));/gi, (whole, dec, hex, name) => {
295
295
  if (name !== undefined)
@@ -32,7 +32,9 @@
32
32
  * The pairing TRUST SCOPE may still be the broad `sharepoint.com` —
33
33
  * `hostMatchesAnyDomain` accepts any `*.sharepoint.com` subdomain via
34
34
  * `endsWith('.' + domain)` — so one domain covers every tenant SP host without
35
- * re-pairing per host.
35
+ * re-pairing per host. That domain is one of the one bridge scope every capture
36
+ * of this server declares (`bridge-scope.ts`); a capture host is added to it,
37
+ * and remembered, once a capture of it succeeds.
36
38
  *
37
39
  * Import this module LAZILY (`await import('./sharepoint-auth.js')`) from the
38
40
  * code that needs a token, as `auth-fetchproxy.ts` is, so a server run with
@@ -40,24 +42,17 @@
40
42
  */
41
43
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
42
44
  import { captureWindowMs } from './capture-window.js';
43
- import { createCaptureTransport, getWsPort } from './auth-fetchproxy.js';
45
+ import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
46
+ import { BRIDGE_TRUST_DOMAINS, isSharePointHost, rememberSharePointHost, sharePointCaptureDecl } from './bridge-scope.js';
44
47
  import { PACKAGE_NAME, VERSION } from './version.js';
45
48
  /**
46
- * The extension's trust boundary for the SharePoint path: the broad family
47
- * domain. `hostMatchesAnyDomain` treats this as "any `*.sharepoint.com`", so a
48
- * single paired domain covers every tenant SP host, while the per-host capture
49
- * decl below stays a concrete hostname (the capture layer rejects a wildcard).
49
+ * The domains the SharePoint capture trusts: the one bridge scope
50
+ * (`bridge-scope.ts`), whose `sharepoint.com` covers every tenant SP host, while
51
+ * the per-host capture decl below stays a concrete hostname (the capture layer
52
+ * rejects a wildcard).
50
53
  */
51
- export const SHAREPOINT_TRUST_DOMAINS = ['sharepoint.com'];
52
- /**
53
- * True for a concrete SharePoint tenant host (`{label}.sharepoint.com`), such
54
- * as `transunion-my.sharepoint.com` or `transunion.sharepoint.com`. Rejects a
55
- * bare `sharepoint.com`, a suffix spoof (`sharepoint.com.evil.com`), and any
56
- * non-SharePoint host. Host is lowercased before matching.
57
- */
58
- export function isSharePointHost(host) {
59
- return /^[a-z0-9][a-z0-9-]*\.sharepoint\.com$/.test(host.toLowerCase());
60
- }
54
+ export const SHAREPOINT_TRUST_DOMAINS = [...BRIDGE_TRUST_DOMAINS];
55
+ export { isSharePointHost } from './bridge-scope.js';
61
56
  /**
62
57
  * The host to capture a SharePoint token FROM, for a file that lives on
63
58
  * `fileHost`.
@@ -94,14 +89,14 @@ export async function captureSharePointTokenViaFetchproxy(host, env = process.en
94
89
  throw new Error(`refusing to capture a SharePoint token for ${JSON.stringify(host)}: not a ` +
95
90
  '*.sharepoint.com host');
96
91
  }
97
- return captureBearerHeader({
92
+ const token = await captureBearerHeader({
98
93
  // The one request we capture from: any call the browser makes to this
99
94
  // OneDrive host (the caller resolves it from the file's host via
100
95
  // `captureHostFor`). A concrete host, never a wildcard — see the module note.
101
- captures: [{ host, path: '/*', headerName: 'authorization' }],
102
- // The broad family domain as the trust scope. Same verb set as the chatsvc
103
- // capture, so an existing pairing that already trusts `sharepoint.com`
104
- // needs no re-approval.
96
+ captures: [sharePointCaptureDecl(host)],
97
+ // The one bridge scope (`bridge-scope.ts`), with this host's capture added
98
+ // to the remembered ones so the hello asks for exactly what it is about to
99
+ // read.
105
100
  domains: SHAREPOINT_TRUST_DOMAINS,
106
101
  // Read per capture, not at import: see `capture-window.ts`.
107
102
  windowMs: captureWindowMs(env),
@@ -112,6 +107,9 @@ export async function captureSharePointTokenViaFetchproxy(host, env = process.en
112
107
  guidance: `Click around Teams or open one of your own OneDrive files — that makes the ` +
113
108
  `browser request ${host}, which is where the SharePoint token is captured ` +
114
109
  'from — then retry.',
115
- createTransport: createCaptureTransport,
110
+ createTransport: bridgeScopedTransport(env, host),
116
111
  });
112
+ // Granted and captured: every later hello declares this host too.
113
+ rememberSharePointHost(host, env);
114
+ return token;
117
115
  }
@@ -30,31 +30,26 @@
30
30
  */
31
31
  import { captureBearerHeader } from '@chrischall/mcp-utils/fetchproxy';
32
32
  import { captureWindowMs } from './capture-window.js';
33
- import { createCaptureTransport, getWsPort } from './auth-fetchproxy.js';
33
+ import { bridgeScopedTransport, getWsPort } from './auth-fetchproxy.js';
34
+ import { BRIDGE_TRUST_DOMAINS, SUBSTRATE_CAPTURE_DECL } from './bridge-scope.js';
34
35
  import { PACKAGE_NAME, VERSION } from './version.js';
35
- /** The one request we capture from: a search-service call the Teams tab makes. */
36
- export const SUBSTRATE_CAPTURE_DECL = {
37
- host: 'substrate.office.com',
38
- path: '/searchservice/*',
39
- headerName: 'authorization',
40
- };
36
+ /** The one request we capture from: a search-service call the Teams tab makes (see `bridge-scope.ts`). */
37
+ export { SUBSTRATE_CAPTURE_DECL } from './bridge-scope.js';
41
38
  /**
42
- * The extension's trust boundary for search: exactly the host we capture from.
43
- * A third, independent scope beside `teams.cloud.microsoft` and
44
- * `sharepoint.com` — granting it takes a one-time re-pair of
45
- * `microsoft-teams-mcp` in the ContextMint Bridge popup; until then search falls
46
- * back to the client-side scan.
39
+ * The domains this capture trusts: the one bridge scope every capture of this
40
+ * server declares (`bridge-scope.ts`), not `substrate.office.com` alone — a
41
+ * search-only domain set made the bridge re-pair on the next chat capture.
47
42
  */
48
- export const SUBSTRATE_TRUST_DOMAINS = [SUBSTRATE_CAPTURE_DECL.host];
43
+ export const SUBSTRATE_TRUST_DOMAINS = [...BRIDGE_TRUST_DOMAINS];
49
44
  /**
50
45
  * Capture a Substrate search token from the user's signed-in Teams tab.
51
46
  * Returns the bare token (no `Bearer ` prefix).
52
47
  */
53
48
  export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
54
49
  return captureBearerHeader({
55
- // Same verb set as the other two captures (`capture_request_header` beside
56
- // the always-on `fetch`); only the trusted domain differs.
57
- captures: [SUBSTRATE_CAPTURE_DECL],
50
+ // Same verb set and, through `bridgeScopedTransport`, the same declared
51
+ // scope as the other two captures; only the header read differs.
52
+ captures: [{ ...SUBSTRATE_CAPTURE_DECL }],
58
53
  domains: SUBSTRATE_TRUST_DOMAINS,
59
54
  // Read per capture, not at import: see `capture-window.ts`.
60
55
  windowMs: captureWindowMs(env),
@@ -65,7 +60,7 @@ export async function captureSubstrateTokenViaFetchproxy(env = process.env) {
65
60
  guidance: 'In a signed-in teams.cloud.microsoft tab, type anything into the search box at the top ' +
66
61
  'and press Enter — that is what makes Teams call substrate.office.com, where the token ' +
67
62
  '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,
63
+ 'pairing does not trust substrate.office.com yet: approve microsoft-teams-mcp in the bridge popup once.',
64
+ createTransport: bridgeScopedTransport(env),
70
65
  });
71
66
  }
@@ -4,8 +4,10 @@ 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';
10
+ import { workMeta } from './hints.js';
9
11
  /** The chat-service conversation that holds the Activity feed. */
10
12
  export const ACTIVITY_FEED_ID = '48:notifications';
11
13
  const MAX_ROWS = 200;
@@ -89,22 +91,48 @@ export function activityRow(m) {
89
91
  preview: clip(htmlToText(str(a.messagePreview) ?? '')),
90
92
  };
91
93
  }
94
+ /**
95
+ * `rows` with each conversation named as the listing tools name it
96
+ * (`conversationNamer`): only the conversations of the rows returned, and a
97
+ * conversation the listing does not carry — or a listing that cannot be read —
98
+ * keeps the feed's own topic.
99
+ */
100
+ async function nameRows(name, rows) {
101
+ const names = await name(rows.flatMap((r) => (r.where.conversation_id !== undefined ? [r.where.conversation_id] : [])));
102
+ return rows.map((r) => {
103
+ const n = r.where.conversation_id !== undefined ? names.get(r.where.conversation_id) : undefined;
104
+ if (n === undefined)
105
+ return r;
106
+ return {
107
+ ...r,
108
+ where: {
109
+ ...r.where,
110
+ title: n.title,
111
+ ...(n.team !== undefined ? { team: n.team } : {}),
112
+ ...(n.participants !== undefined ? { participants: n.participants } : {}),
113
+ },
114
+ };
115
+ });
116
+ }
92
117
  const newestFirst = (a, b) => (b.time ?? '').localeCompare(a.time ?? '');
93
118
  export function registerActivityTools(server, { chatsvc }) {
94
- server.registerTool('teams_get_activity', {
119
+ server.registerTool('teams_list_activity', {
95
120
  title: 'Read the Activity feed',
96
121
  description: 'Read the Teams Activity feed (the bell icon) — mentions, reactions, replies, meeting ' +
97
122
  'notices and missed calls across every chat and channel — newest first, through the ' +
98
123
  'Teams chat-service API, so it works without the Activity view (or any particular view) ' +
99
124
  'open in the browser. Each row has id, time (ISO 8601), kind (mention, reaction, reply, ' +
100
125
  '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), ' +
126
+ '(conversation_id; title — named as teams_list_conversations names it, so an untitled group chat is ' +
127
+ '"Group chat: A; B; C +N" with its participants and a 1:1 is the other person; type; team for a channel), ' +
128
+ 'message_id, reply_chain_id (a channel thread\'s root, when there is one), ' +
102
129
  '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 ' +
130
+ 'teams_list_messages to read the message in context. unread_only keeps rows the user ' +
104
131
  'has not seen; kinds narrows to some buckets; since_days (default 14) sets how far back ' +
105
132
  'to look. This does NOT mark anything read — the user\'s Activity badge is unaffected.' +
106
133
  UNTRUSTED_DESCRIPTION_SUFFIX,
107
134
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
135
+ _meta: workMeta('whats-new', { aliases: ['mentions', 'notifications', 'activity', 'missed calls', 'replies'] }),
108
136
  inputSchema: {
109
137
  unread_only: z
110
138
  .boolean()
@@ -127,6 +155,8 @@ export function registerActivityTools(server, { chatsvc }) {
127
155
  },
128
156
  }, async ({ unread_only, kinds, since_days, limit }) => {
129
157
  try {
158
+ // The listing that names the rows is read alongside the feed scan, not after it.
159
+ const name = conversationNamer(chatsvc);
130
160
  const cutoff = sinceCutoff(since_days);
131
161
  let scanCapped = false;
132
162
  const entries = await chatsvc.getMessages(ACTIVITY_FEED_ID, {
@@ -147,8 +177,10 @@ export function registerActivityTools(server, { chatsvc }) {
147
177
  .filter((r) => !unread_only || !r.read)
148
178
  .filter((r) => wanted === undefined || wanted.has(r.kind))
149
179
  .sort(newestFirst);
180
+ const trimmed = trimRows(rows, limit, 'start', MAX_ROWS);
150
181
  return untrustedResult({
151
- ...trimRows(rows, limit, 'start', MAX_ROWS),
182
+ ...trimmed,
183
+ rows: await nameRows(name, trimmed.rows),
152
184
  ...(scanCapped
153
185
  ? {
154
186
  scan_capped: {
@@ -3,6 +3,8 @@ 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';
7
+ import { workMeta } from './hints.js';
6
8
  /**
7
9
  * Raw messages read looking for the one asked for (20 pages of 200). The
8
10
  * `stopAt` boundary — paging past the message's arrival time — is the real
@@ -14,7 +16,7 @@ const MAX_RAW_MESSAGES = 4000;
14
16
  * this the bounded read in `SharePointClient` aborts and the file degrades to
15
17
  * metadata + link — a file this big belongs behind its link, not in a result.
16
18
  */
17
- const MAX_FILE_BYTES = 25 * 1024 * 1024;
19
+ export const MAX_FILE_BYTES = 25 * 1024 * 1024;
18
20
  const FILE_HINT = 'A shared file is downloaded from SharePoint and returned as its contents (an image as an image, ' +
19
21
  'anything else as an embedded resource). The first file from a given SharePoint host may need ' +
20
22
  'opening once in Teams to mint a short-lived token; a file your account cannot open comes back as ' +
@@ -23,20 +25,23 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
23
25
  server.registerTool('teams_get_attachment', {
24
26
  title: 'Get a Teams message attachment',
25
27
  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) ' +
28
+ 'teams_list_messages / teams_list_unread_messages. An inline image (attachments.images[].ref) ' +
27
29
  'is returned as the image itself. A shared file (attachments.files[].name) is downloaded ' +
28
30
  'from SharePoint and returned as its contents: an image as the image, anything else as an ' +
29
31
  'embedded resource carrying the bytes. The first file from a given SharePoint host in a ' +
30
32
  'session may need opening once in Teams to mint a short-lived token; a file your account ' +
31
33
  '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.' +
34
+ 'instead of failing. Its caption names the conversation beside its id: title (as teams_list_conversations ' +
35
+ 'names it — an untitled group chat by its participants, a 1:1 by the other person) and participants. ' +
36
+ 'Does not mark anything read.' +
33
37
  UNTRUSTED_DESCRIPTION_SUFFIX,
34
38
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
39
+ _meta: workMeta('other', { aliases: ['attachment', 'image', 'file', 'screenshot'] }),
35
40
  inputSchema: {
36
41
  conversation: z
37
42
  .string()
38
43
  .min(1)
39
- .describe('The conversation id the message is in (from teams_read_conversation or teams_get_unread).'),
44
+ .describe('The conversation id the message is in (from teams_list_messages or teams_list_unread_messages).'),
40
45
  message_id: z.string().min(1).describe('The message id, exactly as a message listing returned it.'),
41
46
  ref: z
42
47
  .string()
@@ -53,11 +58,13 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
53
58
  const raw = fetched.find((m) => m.id === message_id);
54
59
  if (raw === undefined) {
55
60
  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.',
61
+ hint: 'Pass the conversation id and message id exactly as teams_list_messages returned them.',
57
62
  });
58
63
  }
59
64
  // Only the attachments are read, so whose message it is does not matter.
60
65
  const message = normaliseMessage(raw, '');
66
+ // Named while the attachment is fetched; naming never throws, so it never fails the call.
67
+ const naming = nameConversations(chatsvc, [conversation]).then((names) => nameFields(names.get(conversation)));
61
68
  const image = message.attachments.images.find((i) => i.ref === ref);
62
69
  if (image !== undefined) {
63
70
  const { mimeType, data } = await chatsvc.fetchImage(image.url);
@@ -68,6 +75,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
68
75
  ref,
69
76
  message_id,
70
77
  conversation,
78
+ ...(await naming),
71
79
  sender: message.sender,
72
80
  time: message.time,
73
81
  mimeType,
@@ -79,12 +87,12 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
79
87
  }
80
88
  const file = message.attachments.files.find((f) => f.name === ref);
81
89
  if (file !== undefined) {
82
- return downloadSharedFile(sharepoint, file, message, { conversation, message_id });
90
+ return downloadSharedFile(sharepoint, file, message, { conversation, message_id }, naming);
83
91
  }
84
92
  const { images, files } = message.attachments;
85
93
  throw new McpToolError(`Message ${message_id} has no attachment "${ref}".`, {
86
94
  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.',
95
+ 'image ref or a file name exactly as teams_list_messages listed it.',
88
96
  });
89
97
  }
90
98
  catch (err) {
@@ -99,7 +107,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
99
107
  * `downloadFile` error and returns today's metadata result with a hint saying
100
108
  * why. A file with no `url` at all (nothing to download) takes the same path.
101
109
  */
102
- async function downloadSharedFile(sharepoint, file, message, ids) {
110
+ async function downloadSharedFile(sharepoint, file, message, ids, naming) {
103
111
  if (file.url === undefined) {
104
112
  return untrustedResult({ ...file, content_available: false, hint: FILE_HINT });
105
113
  }
@@ -119,6 +127,7 @@ async function downloadSharedFile(sharepoint, file, message, ids) {
119
127
  time: message.time,
120
128
  message_id: ids.message_id,
121
129
  conversation: ids.conversation,
130
+ ...(await naming),
122
131
  });
123
132
  if (mimeType.startsWith('image/')) {
124
133
  return { content: [{ type: 'image', data: data.toString('base64'), mimeType }, ...caption.content] };
@@ -144,8 +153,13 @@ async function downloadSharedFile(sharepoint, file, message, ids) {
144
153
  return untrustedResult({ ...file, content_available: false, hint: degradeHint(err, hostOf(file.url)) });
145
154
  }
146
155
  }
156
+ function nameFields(n) {
157
+ if (n === undefined)
158
+ return {};
159
+ return { title: n.title, ...(n.participants !== undefined ? { participants: n.participants } : {}) };
160
+ }
147
161
  /** The host of the file's url, for the degrade hint; a stand-in if it will not parse. */
148
- function hostOf(url) {
162
+ export function hostOf(url) {
149
163
  try {
150
164
  return new URL(url).hostname;
151
165
  }
@@ -154,12 +168,13 @@ function hostOf(url) {
154
168
  }
155
169
  }
156
170
  /**
157
- * Why a shared file degraded to metadata + link, as a user-facing hint.
171
+ * Why a shared file degraded to metadata + link, as a user-facing hint (also
172
+ * why `teams_export_messages` skipped one).
158
173
  * `SharePointClient` throws `McpToolError`s carrying `status`/`kind`/`hint`; a
159
174
  * token-capture failure arrives as a plain `Error`. Branch on structure, not
160
175
  * message text (fleet convention).
161
176
  */
162
- function degradeHint(err, host) {
177
+ export function degradeHint(err, host) {
163
178
  if (errorStatusOf(err) === 403) {
164
179
  return (`Your account cannot open this file, or it is on a SharePoint host (${host}) your captured ` +
165
180
  'token does not cover. Open it once in a signed-in Teams tab, then retry.');
@@ -3,12 +3,13 @@ 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';
10
10
  import { DEFAULT_LIMIT, limitArg } from './limit.js';
11
11
  import { KIND_FILTERS } from './unread.js';
12
+ import { workMeta } from './hints.js';
12
13
  const MAX_CONVERSATIONS = 200;
13
14
  /** How far back a call with no cursor looks. */
14
15
  export const DEFAULT_WINDOW_MS = 86_400_000;
@@ -28,7 +29,7 @@ export function encodeChangesCursor(t) {
28
29
  function badCursor(cursor) {
29
30
  return new McpToolError(`"${cursor}" is not a changes cursor.`, {
30
31
  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
+ 'A message id (digits) is not a changes cursor: pass it to teams_list_messages as after_message_id.',
32
33
  });
33
34
  }
34
35
  /** The epoch ms a `cursor` names: a token from {@link encodeChangesCursor}, or an ISO 8601 time. */
@@ -96,8 +97,34 @@ async function readChanges(chatsvc, summary, t, me) {
96
97
  truncated: capped,
97
98
  };
98
99
  }
100
+ /** The longest line `view: 'brief'` answers (the context-groups contract). */
101
+ export const BRIEF_MAX = 120;
102
+ /** A changed conversation's brief status: how many messages arrived, and how many of them from others. */
103
+ function briefStatus(read) {
104
+ return `${read.count}${read.truncated ? '+' : ''} new, ${read.fromOthers} from others`;
105
+ }
106
+ /**
107
+ * One brief line, `title — <ISO date | no date> — <status>`, at most
108
+ * {@link BRIEF_MAX} characters: the title is flattened to one line (a chat
109
+ * topic can carry newlines) and shortened, never the date or the status.
110
+ */
111
+ export function briefLine(title, time, status) {
112
+ const tail = ` — ${time ?? 'no date'} — ${status}`;
113
+ const flat = title.replace(/\s+/g, ' ').trim() || '(untitled)';
114
+ const room = BRIEF_MAX - tail.length;
115
+ const shown = flat.length > room ? `${flat.slice(0, Math.max(room - 1, 0)).trimEnd()}…` : flat;
116
+ return `${shown}${tail}`;
117
+ }
118
+ /**
119
+ * The brief answer as plain text, one line per item. It carries no message
120
+ * text — only conversation titles (which other people can set), counts and
121
+ * times — and the tool's description keeps the untrusted-content warning.
122
+ */
123
+ function briefResult(lines) {
124
+ return { content: [{ type: 'text', text: lines.join('\n') }] };
125
+ }
99
126
  export function registerChangesTools(server, { chatsvc }) {
100
- server.registerTool('teams_get_changes', {
127
+ server.registerTool('teams_list_changed_conversations', {
101
128
  title: 'Get Teams conversations with new messages',
102
129
  description: 'List the chats and channels that got new messages since a cursor, most recent first — counts, not ' +
103
130
  'the messages: each with its summary (id, kind, title, team), new_message_count (real messages ' +
@@ -105,10 +132,10 @@ export function registerChangesTools(server, { chatsvc }) {
105
132
  'new_from_others_count, newest_time and, for a channel, threads: one { root_id, new_root, ' +
106
133
  'new_reply_count } per thread the new messages landed in, including a thread whose root post is ' +
107
134
  '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> }). ' +
135
+ 'teams_list_messages({ conversation: <its id>, after_message_id: <its after_message_id> }). ' +
109
136
  '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 ' +
137
+ 'teams_list_changed_conversations only and is not a message id; after_message_id is a message-id cursor (ids are ' +
138
+ 'arrival ms, so it is the cursor time as an id) for teams_list_messages (or teams_list_unread_messages ' +
112
139
  'cursors). Without cursor it looks back 24 hours. next_cursor is an opaque token — pass it back as ' +
113
140
  'cursor to get only what arrived since this call (cursor also takes a plain ISO 8601 time). It is ' +
114
141
  'at-least-once: a conversation can come back again but none is skipped; it stays at the input ' +
@@ -123,14 +150,18 @@ export function registerChangesTools(server, { chatsvc }) {
123
150
  'This does NOT mark anything read — the user\'s Teams unread badges are unaffected. ' +
124
151
  UNTRUSTED_DESCRIPTION_SUFFIX,
125
152
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
153
+ _meta: workMeta('whats-new', {
154
+ canonical: true,
155
+ aliases: ['work', 'teams', 'new messages', 'chats', 'messages', 'anything new', 'what did i miss'],
156
+ }),
126
157
  inputSchema: {
127
158
  cursor: z
128
159
  .string()
129
160
  .min(1)
130
161
  .optional()
131
- .describe("A previous teams_get_changes result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): " +
162
+ .describe("A previous teams_list_changed_conversations result's next_cursor, or an ISO 8601 time (e.g. 2026-10-12T09:00:00Z): " +
132
163
  'only messages that arrived after it count. Default: 24 hours ago. Not a message id, and not ' +
133
- "teams_read_conversation's next_cursor."),
164
+ "teams_list_messages's next_cursor."),
134
165
  kinds: z
135
166
  .array(z.enum(Object.keys(KIND_FILTERS)))
136
167
  .min(1)
@@ -139,8 +170,14 @@ export function registerChangesTools(server, { chatsvc }) {
139
170
  'chat; channel; meeting = meeting chats only; oneOnOne = 1:1 chats only.'),
140
171
  include_hidden: includeHiddenArg.describe('Also include channels the user has hidden in Teams (default false: Teams shows them nowhere).'),
141
172
  limit: limitArg(MAX_CONVERSATIONS, 'conversations', 'most recent activity first kept'),
173
+ view: z
174
+ .enum(['full', 'brief'])
175
+ .optional()
176
+ .describe('"full" (default) returns the result described above; "brief" returns plain text, one line per ' +
177
+ 'changed conversation (limit does not apply): title — newest_time (ISO 8601, or "no date") — ' +
178
+ '"<n> new, <m> from others", or "could not read" for a conversation whose read failed.'),
142
179
  },
143
- }, async ({ cursor, kinds, include_hidden, limit }) => {
180
+ }, async ({ cursor, kinds, include_hidden, limit, view }) => {
144
181
  try {
145
182
  const t = cursor !== undefined ? decodeChangesCursor(cursor) : Date.now() - DEFAULT_WINDOW_MS;
146
183
  const fetched_at = new Date().toISOString();
@@ -194,7 +231,7 @@ export function registerChangesTools(server, { chatsvc }) {
194
231
  ...rest.map((c) => c.summary),
195
232
  ...failed.map((f) => f.summary),
196
233
  ]);
197
- // The read_conversation hand-off: a message id is its arrival ms, so the cursor time as an id
234
+ // The list_messages hand-off: a message id is its arrival ms, so the cursor time as an id
198
235
  // stops that read exactly where this one stopped counting.
199
236
  const after_message_id = String(Math.floor(t));
200
237
  const conversations = shown.map(({ read }, i) => ({
@@ -209,9 +246,16 @@ export function registerChangesTools(server, { chatsvc }) {
209
246
  const more = rest.map(({ read }, i) => ({
210
247
  id: titled[shown.length + i].id,
211
248
  title: titled[shown.length + i].title,
249
+ ...participantsOf(titled[shown.length + i]),
212
250
  new_message_count: read.count,
213
251
  after_message_id,
214
252
  }));
253
+ if (view === 'brief') {
254
+ return briefResult([
255
+ ...changed.map(({ read }, i) => briefLine(titled[i].title, read.newestTime, briefStatus(read))),
256
+ ...failed.map((_, i) => briefLine(titled[changed.length + i].title, undefined, 'could not read')),
257
+ ]);
258
+ }
215
259
  const errors = failed.map((f, i) => ({
216
260
  conversation: titled[changed.length + i],
217
261
  error: wrapApiError(f.error, 'read this conversation').message,
@@ -3,6 +3,7 @@ import { wrapApiError } from './errors.js';
3
3
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
4
4
  import { limitArg, trimRows } from './limit.js';
5
5
  import { FAVORITES_DESCRIPTION, favoritesFirst, includeHiddenArg, listSinceDaysArg, listSummaries, MATCH_REASON_DESCRIPTION, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
6
+ import { workMeta } from './hints.js';
6
7
  /** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
7
8
  const MAX_CHANNELS = 500;
8
9
  /**
@@ -24,13 +25,13 @@ function byTeamThenTitle(a, b) {
24
25
  return a.title.localeCompare(b.title, undefined, { sensitivity: 'base' });
25
26
  }
26
27
  export function registerChannelTools(server, { chatsvc }) {
27
- server.registerTool('teams_list_teams_and_channels', {
28
+ server.registerTool('teams_list_channels', {
28
29
  title: 'List Teams channels',
29
30
  description: 'List every channel the signed-in user is in, across all their teams, sorted by team ' +
30
31
  'name then channel title. Each has an id, title, team (when Teams makes it ' +
31
32
  'determinable), unread hint, last-activity time (ISO 8601), and a last-message preview ' +
32
33
  '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
+ 'hidden: true. Pass an id (or the channel name) to teams_list_messages to read its ' +
34
35
  'posts and replies. Use unread_only for channels with real posts the user has not read, ' +
35
36
  'each confirmed by reading past the read marker (a channel that is gone or no longer ' +
36
37
  'readable is skipped and counted in skipped_unreachable); hidden channels are left out ' +
@@ -44,6 +45,7 @@ export function registerChannelTools(server, { chatsvc }) {
44
45
  FAVORITES_DESCRIPTION +
45
46
  UNTRUSTED_DESCRIPTION_SUFFIX,
46
47
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
48
+ _meta: workMeta('lookup', { aliases: ['channels', 'teams', 'team channels'] }),
47
49
  inputSchema: {
48
50
  unread_only: unreadOnlyArg,
49
51
  since_days: listSinceDaysArg,
@@ -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