@chrischall/microsoft-teams-mcp 0.7.0 → 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.
@@ -396,6 +399,38 @@ export class ChatServiceClient {
396
399
  }
397
400
  }
398
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
+ }
399
434
  async #getImage(target) {
400
435
  const { status, headers, body } = await this.#send(target.toString(), 'bytes', MAX_IMAGE_BYTES);
401
436
  this.#checkStatus(status);
package/dist/index.js CHANGED
@@ -17,6 +17,7 @@ import { registerActivityTools } from './tools/activity.js';
17
17
  import { registerSearchTools } from './tools/search.js';
18
18
  import { registerHealthcheckTool } from './tools/healthcheck.js';
19
19
  import { registerExportTools } from './tools/export.js';
20
+ import { registerTranscriptTools } from './tools/transcript.js';
20
21
  loadDotenvSafely();
21
22
  /**
22
23
  * Built HERE, in the caller, not inside a registrar — see office-outlook-mcp
@@ -50,6 +51,7 @@ await runMcp({
50
51
  registerActivityTools,
51
52
  registerSearchTools,
52
53
  registerExportTools,
54
+ registerTranscriptTools,
53
55
  registerHealthcheckTool,
54
56
  ],
55
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
  }
@@ -7,6 +7,7 @@ import { limitArg, trimRows } from './limit.js';
7
7
  import { conversationNamer } from './titles.js';
8
8
  import { wrapApiError } from './errors.js';
9
9
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
10
+ import { workMeta } from './hints.js';
10
11
  /** The chat-service conversation that holds the Activity feed. */
11
12
  export const ACTIVITY_FEED_ID = '48:notifications';
12
13
  const MAX_ROWS = 200;
@@ -131,6 +132,7 @@ export function registerActivityTools(server, { chatsvc }) {
131
132
  'to look. This does NOT mark anything read — the user\'s Activity badge is unaffected.' +
132
133
  UNTRUSTED_DESCRIPTION_SUFFIX,
133
134
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
135
+ _meta: workMeta('whats-new', { aliases: ['mentions', 'notifications', 'activity', 'missed calls', 'replies'] }),
134
136
  inputSchema: {
135
137
  unread_only: z
136
138
  .boolean()
@@ -4,6 +4,7 @@ import { normaliseMessage } from '../model.js';
4
4
  import { wrapApiError } from './errors.js';
5
5
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
6
6
  import { nameConversations } from './titles.js';
7
+ import { workMeta } from './hints.js';
7
8
  /**
8
9
  * Raw messages read looking for the one asked for (20 pages of 200). The
9
10
  * `stopAt` boundary — paging past the message's arrival time — is the real
@@ -35,6 +36,7 @@ export function registerAttachmentTools(server, { chatsvc, sharepoint }) {
35
36
  'Does not mark anything read.' +
36
37
  UNTRUSTED_DESCRIPTION_SUFFIX,
37
38
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
39
+ _meta: workMeta('other', { aliases: ['attachment', 'image', 'file', 'screenshot'] }),
38
40
  inputSchema: {
39
41
  conversation: z
40
42
  .string()
@@ -9,6 +9,7 @@ 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;
@@ -96,6 +97,32 @@ 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
127
  server.registerTool('teams_list_changed_conversations', {
101
128
  title: 'Get Teams conversations with new messages',
@@ -123,6 +150,10 @@ 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()
@@ -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();
@@ -213,6 +250,12 @@ export function registerChangesTools(server, { chatsvc }) {
213
250
  new_message_count: read.count,
214
251
  after_message_id,
215
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
+ }
216
259
  const errors = failed.map((f, i) => ({
217
260
  conversation: titled[changed.length + i],
218
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
  /**
@@ -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,
@@ -5,6 +5,7 @@ import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
5
5
  import { limitArg, trimRows } from './limit.js';
6
6
  import { SEARCH_FETCH_MESSAGES } from './chat-search.js';
7
7
  import { FAVORITES_DESCRIPTION, favoritesFirst, GROUP_TITLE_DESCRIPTION, listOlderUnreadArg, listSinceDaysArg, listSummaries, MATCH_REASON_DESCRIPTION, queryArg, UNREAD_HINT_DESCRIPTION, unreadOnlyArg, } from './listing.js';
8
+ import { workMeta } from './hints.js';
8
9
  /** Up to 10 pages of 200 come back; this bounds one result, not the listing. */
9
10
  const MAX_CHATS = 500;
10
11
  /** Newest activity first; a chat with no messages at all sorts last. */
@@ -76,6 +77,7 @@ export function registerChatTools(server, { chatsvc }) {
76
77
  ' Listing never marks anything read (teams_mark_read does). Channels are listed by teams_list_channels instead.' +
77
78
  UNTRUSTED_DESCRIPTION_SUFFIX,
78
79
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
80
+ _meta: workMeta('lookup', { aliases: ['chats', 'conversations', 'teams chats', 'who messaged me'] }),
79
81
  inputSchema: {
80
82
  unread_only: unreadOnlyArg,
81
83
  since_days: listSinceDaysArg,
@@ -12,6 +12,7 @@ import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from '.
12
12
  import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage, tooBusy } from './from.js';
13
13
  import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
14
14
  import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
15
+ import { workMeta } from './hints.js';
15
16
  const MAX_MESSAGES = 500;
16
17
  /**
17
18
  * Raw messages read before giving up (20 pages of 200). The real bound is the
@@ -361,6 +362,7 @@ export function registerConversationTools(server, { chatsvc }) {
361
362
  UNTRUSTED_DESCRIPTION_SUFFIX,
362
363
  // A write only with mark_read, but a write: it moves the user's read marker (never backwards, so a repeat is a no-op).
363
364
  annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
365
+ _meta: workMeta('lookup', { aliases: ['messages', 'chat history', 'read the chat', 'thread'] }),
364
366
  inputSchema: {
365
367
  conversation: z
366
368
  .union([z.string().min(1), z.array(z.string().min(1)).min(1).max(MAX_CONVERSATIONS)])
@@ -50,6 +50,7 @@ import { takePage } from './from.js';
50
50
  import { conversationName, enrichTitles } from './titles.js';
51
51
  import { resolveTimeZone, tzArg } from './timezone.js';
52
52
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
53
+ import { workMeta } from './hints.js';
53
54
  export const EXPORT_SERVER_NAME = 'microsoft-teams-mcp';
54
55
  export const EXPORT_OUTPUT_ENV = 'TEAMS_OUTPUT_DIR';
55
56
  export const DEFAULT_MAX_ITEMS = 5000;
@@ -497,6 +498,7 @@ export function registerExportTools(server, deps, opts = {}) {
497
498
  'open, no token yet, too large) is listed as skipped with the reason, never failing the export.' +
498
499
  UNTRUSTED_DESCRIPTION_SUFFIX,
499
500
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
501
+ _meta: workMeta('other', { aliases: ['export', 'save the chat', 'chat history'] }),
500
502
  inputSchema: {
501
503
  conversations: conversationsArg
502
504
  .optional()
@@ -0,0 +1,4 @@
1
+ /** `_meta` for a Teams tool. */
2
+ export function workMeta(intent, extra = {}) {
3
+ return { mint: { domain: 'work', intent, ...extra } };
4
+ }
@@ -6,6 +6,7 @@ import { confirmedSummary } from './confirm.js';
6
6
  import { resolveListed } from './conversation.js';
7
7
  import { wrapApiError } from './errors.js';
8
8
  import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
+ import { workMeta } from './hints.js';
9
10
  const TOOL = 'teams_mark_read';
10
11
  /** Messages read to find the newest one — one page; a page is not strictly ordered, so all of it is looked at. */
11
12
  const NEWEST_PAGE = 50;
@@ -143,6 +144,7 @@ export function registerMarkReadTools(server, { chatsvc }) {
143
144
  CONFIRM_INJECTION_RULE +
144
145
  UNTRUSTED_DESCRIPTION_SUFFIX,
145
146
  annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
147
+ _meta: workMeta('change', { aliases: ['mark read', 'mark as read', 'clear unread'] }),
146
148
  inputSchema: {
147
149
  conversation: z
148
150
  .string()
@@ -5,6 +5,7 @@ import { htmlToText, normaliseMessage, senderMri } from '../model.js';
5
5
  import { wrapApiError } from './errors.js';
6
6
  import { resolveTarget, SELF_CHAT } from './send.js';
7
7
  import { untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
8
+ import { workMeta } from './hints.js';
8
9
  const TOOL = 'teams_react';
9
10
  /**
10
11
  * The ✅ reaction's key, from the unicode-style key rule (see `KEY_RULE`) and
@@ -90,6 +91,7 @@ export function registerReactTools(server, { chatsvc }) {
90
91
  CONFIRM_INJECTION_RULE +
91
92
  UNTRUSTED_DESCRIPTION_SUFFIX,
92
93
  annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
94
+ _meta: workMeta('send', { aliases: ['react', 'like', 'thumbs up', 'reaction'] }),
93
95
  inputSchema: {
94
96
  conversation: z
95
97
  .string()
@@ -6,6 +6,7 @@ import { CONFIRM_CONCURRENCY, isUnreachable } from './confirm.js';
6
6
  import { conversationName, enrichTitles, participantsOf } from './titles.js';
7
7
  import { wrapApiError } from './errors.js';
8
8
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
+ import { workMeta } from './hints.js';
9
10
  const DEFAULT_LIMIT = 25;
10
11
  const MAX_LIMIT = 200;
11
12
  /** The window searched when `since` is not given. */
@@ -88,6 +89,7 @@ export function registerSearchTools(server, { chatsvc, substrate }) {
88
89
  'does NOT mark anything read.' +
89
90
  UNTRUSTED_DESCRIPTION_SUFFIX,
90
91
  annotations: toolAnnotations({ readOnly: true, openWorld: true }),
92
+ _meta: workMeta('lookup', { aliases: ['find a message', 'search teams', 'search chats'] }),
91
93
  inputSchema: {
92
94
  query: z
93
95
  .string()
@@ -5,6 +5,7 @@ import { htmlToText, isUserMessage, normaliseMessage, SELF_CHAT, senderMri } fro
5
5
  import { resolveListed } from './conversation.js';
6
6
  import { wrapApiError } from './errors.js';
7
7
  import { THIRD_PARTY_NAMES_NOTE, untrustedField, untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX, } from './untrusted.js';
8
+ import { workMeta } from './hints.js';
8
9
  const TOOL = 'teams_send_message';
9
10
  /**
10
11
  * The user's own notes chat — the one `48:*` system conversation that takes
@@ -162,6 +163,7 @@ export function registerSendTools(server, { chatsvc }) {
162
163
  CONFIRM_INJECTION_RULE +
163
164
  UNTRUSTED_DESCRIPTION_SUFFIX,
164
165
  annotations: toolAnnotations({ readOnly: false, destructive: true, idempotent: false, openWorld: true }),
166
+ _meta: workMeta('send', { aliases: ['message', 'send a message', 'reply', 'tell', 'post', 'chat'] }),
165
167
  inputSchema: {
166
168
  conversation: z
167
169
  .string()
@@ -0,0 +1,144 @@
1
+ import { z } from 'zod';
2
+ import { McpToolError, currentCallSignal, toolAnnotations } from '@chrischall/mcp-utils';
3
+ import { openExportSink, sanitizeExportFileName } from '@chrischall/mcp-utils/export';
4
+ import { listRecordings, parseRecording, parseVtt, renderTranscriptText, transcriptSpeakers } from '../transcript.js';
5
+ import { AmbiguousConversationError, ambiguousResult, resolveListed } from './conversation.js';
6
+ import { wrapApiError } from './errors.js';
7
+ import { workMeta } from './hints.js';
8
+ import { EXPORT_OUTPUT_ENV, EXPORT_SERVER_NAME } from './export.js';
9
+ import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
10
+ /** Messages read looking for recordings (newest first). */
11
+ export const MAX_SCAN = 2000;
12
+ /** Most transcript characters returned inline; past this, `save` it. */
13
+ export const MAX_INLINE_CHARS = 200_000;
14
+ /** Other recordings listed beside the one returned. */
15
+ const MAX_OTHERS = 20;
16
+ /** A recording as the result shows it: `recording_id`, never the internal object id. */
17
+ function shown(r) {
18
+ const { message_id, object_id: _objectId, has_transcript: _has, duration_seconds: _secs, ...rest } = r;
19
+ return { recording_id: message_id, ...rest };
20
+ }
21
+ export function registerTranscriptTools(server, { chatsvc }) {
22
+ server.registerTool('teams_get_transcript', {
23
+ title: 'Get a Teams meeting transcript',
24
+ description: 'Get the transcript of a recorded Teams meeting from its meeting chat (by id or by name, as ' +
25
+ 'teams_list_conversations lists it). Works even when the organizer disabled transcript download: it ' +
26
+ "reads Teams' own copy, the one the Recap tab shows. Returns the newest transcribed recording unless " +
27
+ 'recording_id names another (other_recordings lists the rest, newest first): its time, duration and ' +
28
+ 'play_url, the speakers, and the transcript — format "text" (default: one line per speaker turn, ' +
29
+ '"[hh:mm:ss] Name: words") or "vtt" (the WebVTT as Teams serves it). A transcript longer than ' +
30
+ `${MAX_INLINE_CHARS.toLocaleString('en-US')} characters is cut short (truncated: true). save: true writes ` +
31
+ `<meeting>-<time>.vtt and .txt instead (on a local install into a fresh folder under dest, else ${EXPORT_OUTPUT_ENV}, ` +
32
+ `else ~/Downloads/${EXPORT_SERVER_NAME}; on a hosted install as a zip behind a signed link) and returns where. ` +
33
+ "Teams' copy expires after some weeks: an expired one is an error, not another recording. " +
34
+ 'Does not mark anything read.' +
35
+ UNTRUSTED_DESCRIPTION_SUFFIX,
36
+ _meta: workMeta('lookup', { aliases: ['transcript', 'meeting transcript', 'recording', 'recap', 'vtt', 'what was said'] }),
37
+ // save writes a local file the user asked for; nothing in Teams changes.
38
+ annotations: toolAnnotations({ readOnly: true, openWorld: true }),
39
+ inputSchema: {
40
+ conversation: z
41
+ .string()
42
+ .min(1)
43
+ .describe("The meeting chat's id, or a case-insensitive substring of its title."),
44
+ recording_id: z
45
+ .string()
46
+ .min(1)
47
+ .optional()
48
+ .describe('A recording_id from a previous result (recording or other_recordings). Default: the newest.'),
49
+ format: z.enum(['text', 'vtt']).optional().describe('"text" (default, readable turns) or "vtt" (raw WebVTT).'),
50
+ save: z
51
+ .boolean()
52
+ .optional()
53
+ .describe('Write the transcript to files (.vtt and .txt) and return where, instead of the text. Default false.'),
54
+ dest: z
55
+ .string()
56
+ .min(1)
57
+ .optional()
58
+ .describe(`With save, on a local install: the folder to create the output folder in (under ${EXPORT_OUTPUT_ENV} when ` +
59
+ 'set, else under ~/Downloads, ~/Documents or ~/Desktop).'),
60
+ },
61
+ }, async ({ conversation, recording_id, format, save, dest }) => {
62
+ try {
63
+ const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
64
+ const summary = await resolveListed(chatsvc, raw, me, conversation, 'read the transcript of');
65
+ const messages = await chatsvc.getMessages(summary.id, { max: MAX_SCAN });
66
+ const recordings = listRecordings(messages);
67
+ if (recordings.length === 0) {
68
+ throw new McpToolError(`No meeting transcript was found in "${summary.title}".`, {
69
+ hint: `Read its newest ${MAX_SCAN} messages. A transcript is posted to a meeting's own chat once a recorded ` +
70
+ 'or transcribed meeting ends; pass the meeting chat (teams_list_conversations lists them).',
71
+ });
72
+ }
73
+ let chosen = recordings[0];
74
+ if (recording_id !== undefined) {
75
+ // Any message of a recording names it: a chunk posts several as its status moves.
76
+ const objectId = recordingObjectOf(messages, recording_id);
77
+ chosen = recordings.find((r) => r.message_id === recording_id || r.object_id === objectId);
78
+ if (chosen === undefined) {
79
+ throw new McpToolError(`No transcribed recording ${recording_id} in "${summary.title}".`, {
80
+ hint: `Its recordings, newest first: ${recordings
81
+ .slice(0, MAX_OTHERS)
82
+ .map((r) => `${r.message_id} (${r.time})`)
83
+ .join(', ')}.`,
84
+ });
85
+ }
86
+ }
87
+ const vtt = await chatsvc.fetchTranscript(chosen.object_id);
88
+ const cues = parseVtt(vtt);
89
+ const text = renderTranscriptText(cues);
90
+ const others = recordings.filter((r) => r !== chosen).slice(0, MAX_OTHERS).map(shown);
91
+ const base = {
92
+ conversation: summary.id,
93
+ title: summary.title,
94
+ recording: shown(chosen),
95
+ speakers: transcriptSpeakers(cues),
96
+ cue_count: cues.length,
97
+ ...(others.length > 0 ? { other_recordings: others } : {}),
98
+ };
99
+ if (save) {
100
+ const sink = await openExportSink({
101
+ name: EXPORT_SERVER_NAME,
102
+ envVar: EXPORT_OUTPUT_ENV,
103
+ baseName: 'teams-transcript',
104
+ ...(dest !== undefined ? { dest } : {}),
105
+ ...(currentCallSignal() !== undefined ? { signal: currentCallSignal() } : {}),
106
+ });
107
+ const stem = sanitizeExportFileName(`${chosen.title ?? summary.title}-${chosen.time.slice(0, 16).replace(':', '')}`);
108
+ const files = [await sink.addFile(`${stem}.vtt`, vtt, 'text/vtt'), await sink.addFile(`${stem}.txt`, `${text}\n`, 'text/plain')];
109
+ const loc = await sink.finish();
110
+ return untrustedResult({
111
+ ...base,
112
+ mode: loc.mode,
113
+ location: loc.location,
114
+ ...(loc.urlExpiresAt !== undefined ? { url_expires_at: loc.urlExpiresAt } : {}),
115
+ files: files.map((f) => ({ ...(f.path !== undefined ? { path: f.path } : { name: f.name }), bytes: f.bytes })),
116
+ });
117
+ }
118
+ const fmt = format ?? 'text';
119
+ const full = fmt === 'vtt' ? vtt : text;
120
+ const truncated = full.length > MAX_INLINE_CHARS;
121
+ return untrustedResult({
122
+ ...base,
123
+ format: fmt,
124
+ transcript: truncated ? full.slice(0, MAX_INLINE_CHARS) : full,
125
+ ...(truncated
126
+ ? {
127
+ truncated: true,
128
+ hint: `The transcript is ${full.length.toLocaleString('en-US')} characters; pass save: true to get all of it as files.`,
129
+ }
130
+ : {}),
131
+ });
132
+ }
133
+ catch (err) {
134
+ if (err instanceof AmbiguousConversationError)
135
+ return untrustedResult(ambiguousResult(err));
136
+ throw wrapApiError(err, 'get the transcript');
137
+ }
138
+ });
139
+ }
140
+ /** The object id of the recording message `id`, if it is one (any of a chunk's messages names it). */
141
+ function recordingObjectOf(messages, id) {
142
+ const m = messages.find((x) => x.id === id);
143
+ return m === undefined ? undefined : parseRecording(m)?.object_id;
144
+ }
@@ -14,6 +14,7 @@ import { DEFAULT_LIMIT } from './limit.js';
14
14
  import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage, tooBusy, } from './from.js';
15
15
  import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
16
16
  import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
17
+ import { workMeta } from './hints.js';
17
18
  const MAX_PER_CONVERSATION = 200;
18
19
  const DEFAULT_PER_CONVERSATION = 50;
19
20
  const MAX_CONVERSATIONS = 50;
@@ -195,6 +196,7 @@ export function registerUnreadTools(server, { chatsvc }) {
195
196
  UNTRUSTED_DESCRIPTION_SUFFIX,
196
197
  // A write only with mark_read, but a write: it moves the user's read markers (never backwards, so a repeat is a no-op).
197
198
  annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
199
+ _meta: workMeta('whats-new', { aliases: ['unread', 'unread messages', 'what did i miss', 'new messages'] }),
198
200
  inputSchema: {
199
201
  kinds: z
200
202
  .array(z.enum(Object.keys(KIND_FILTERS)))