@chrischall/microsoft-teams-mcp 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,16 @@
1
1
  import { z } from 'zod';
2
- import { toolAnnotations } from '@chrischall/mcp-utils';
2
+ import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, toolAnnotations } from '@chrischall/mcp-utils';
3
3
  import { conversationSummary, matchConversations, normaliseMessage, oldestFirst, } from '../model.js';
4
- import { groupThreads } from './conversation.js';
5
- import { confirmedSummary, confirmUnreadCandidates, olderUnreadReport, sinceCutoff, sinceDaysArg } from './confirm.js';
6
- import { GROUP_TITLE_DESCRIPTION, includeHiddenArg, isUnreadCandidateFor } from './listing.js';
4
+ import { confirmedSummary, confirmUnreadCandidates, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
5
+ import { GROUP_TITLE_DESCRIPTION, includeHiddenArg, isUnreadCandidateFor, MATCH_REASON_DESCRIPTION } from './listing.js';
7
6
  import { enrichTitles } from './titles.js';
8
7
  import { wrapApiError } from './errors.js';
9
8
  import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
9
+ import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
10
+ import { CURSOR_NO_CACHE_DESCRIPTION, cursorsArg, newestId } from './cursor.js';
11
+ import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
12
+ import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
13
+ import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
10
14
  const MAX_PER_CONVERSATION = 200;
11
15
  const DEFAULT_PER_CONVERSATION = 50;
12
16
  const MAX_CONVERSATIONS = 50;
@@ -16,13 +20,22 @@ const DEFAULT_CONVERSATIONS = 20;
16
20
  * read horizon; this only caps a backlog of nothing but system events.
17
21
  */
18
22
  const MAX_RAW_MESSAGES = 4000;
23
+ /** Channels whose outside-window roots are fetched at once (each fetch is itself bounded, `roots.ts`). */
24
+ const ROOT_CONVERSATION_CONCURRENCY = 4;
19
25
  /** The `kinds` filter: `chat` is every non-channel chat; the others narrow to one kind. */
20
- const KIND_FILTERS = {
26
+ export const KIND_FILTERS = {
21
27
  chat: ['group', 'meeting', 'oneOnOne'],
22
28
  channel: ['channel'],
23
29
  meeting: ['meeting'],
24
30
  oneOnOne: ['oneOnOne'],
25
31
  };
32
+ /** What `mark_read` reports for a conversation `per_conversation_limit` cut: its marker is left alone. */
33
+ const TRUNCATED_SKIP = {
34
+ skipped: 'truncated',
35
+ hint: 'The read marker was left where it was: per_conversation_limit cut this read, so unread messages older ' +
36
+ `than those returned were not returned. Read again with a larger per_conversation_limit (max ${MAX_PER_CONVERSATION}) ` +
37
+ 'or with teams_read_conversation (unread_only) to mark it read, or use teams_mark_read to mark it all read deliberately.',
38
+ };
26
39
  /** Newest activity first; a conversation with no messages at all sorts last. */
27
40
  function byLastActivityDesc(a, b) {
28
41
  return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
@@ -34,7 +47,9 @@ export function registerUnreadTools(server, { chatsvc }) {
34
47
  '(or those matching kinds / query), grouped by conversation, most recent activity ' +
35
48
  'first. Each conversation comes with its summary (id, kind, title, team) and only the ' +
36
49
  'messages the user has not read, oldest first; a channel\'s are grouped as threads ' +
37
- 'under their root post (a root the user already read is marked missing). Exact, as in ' +
50
+ 'under their root post. A root the user already read is fetched and marked outside_window: true ' +
51
+ `(it is context, not unread or counted); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and ` +
52
+ 'any beyond that or that cannot be fetched is { id, missing: true }. Exact, as in ' +
38
53
  'Teams: every conversation with activity past its read marker (or never opened) is read ' +
39
54
  'past the marker and kept only if it holds a real message from someone else, so a call ' +
40
55
  'recording, transcript or other system event never makes a conversation unread. Channels ' +
@@ -42,17 +57,38 @@ export function registerUnreadTools(server, { chatsvc }) {
42
57
  'or no longer readable (404/403) is skipped and counted in skipped_unreachable. Only ' +
43
58
  'conversations whose newest unread message is from the last 14 days are returned by ' +
44
59
  'default (since_days widens or narrows it); older unread conversations — typically dormant ' +
45
- 'channels — are not read past their marker and are counted in older_unread_skipped. ' +
60
+ 'channels — are not read past their marker and are counted in older_unread_skipped; ' +
61
+ 'older_unread: true also lists them in older_unread_conversations (id, kind, title, team, ' +
62
+ 'lastActivity, and unread_count only for those already read — unread_count_known: false ' +
63
+ 'otherwise). Chats the user muted in Teams (muted: true) are left out too and counted in ' +
64
+ 'muted_skipped, without being read; include_muted adds them. ' +
46
65
  'Unread conversations past max_conversations are listed by id, title and unread_count in ' +
47
66
  'more_unread_conversations; read one with teams_read_conversation. A conversation that ' +
48
67
  'could not be read is listed in errors and the rest still come back. total_unread covers ' +
49
68
  'every unread conversation found; total_unread_exact is false when a per-conversation ' +
50
- 'limit truncated or a read failed. This does NOT mark anything read — the user\'s ' +
51
- 'Teams unread badges are unaffected. ' +
69
+ 'limit truncated or a read failed. cursors ({ conversationId: messageId }) returns only unread ' +
70
+ 'messages newer than each conversation\'s cursor (one with none is left out, and total_unread ' +
71
+ 'counts only those). Each returned conversation carries next_cursor, its newest returned message ' +
72
+ 'id; next_cursors is the cursors passed in updated with every returned conversation\'s next_cursor ' +
73
+ '(not those only in more_unread_conversations) — pass it back as cursors to get only what is new. ' +
74
+ CURSOR_NO_CACHE_DESCRIPTION +
75
+ FORMAT_DESCRIPTION +
76
+ MARK_READ_DESCRIPTION +
77
+ 'With mark_read each conversation returned with its messages (not more_unread_conversations) has its ' +
78
+ 'read marker moved up to its newest unread message returned (outside_window roots do not count) and ' +
79
+ 'carries marked_read (false with mark_read_warning when that move failed); one per_conversation_limit ' +
80
+ 'cut is not marked — marked_read: { skipped: "truncated", hint }; the user confirms first — a prompt where the client supports one, otherwise the ' +
81
+ 'first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. ' +
82
+ CONFIRM_INJECTION_RULE +
83
+ ' ' +
52
84
  GROUP_TITLE_DESCRIPTION +
53
- ' query also matches those participant names.' +
85
+ ' query also matches those participant names, and the last-message preview. ' +
86
+ MATCH_REASON_DESCRIPTION +
87
+ 'Message times are UTC (ISO 8601); ' +
88
+ TIME_ZONE_DESCRIPTION +
54
89
  UNTRUSTED_DESCRIPTION_SUFFIX,
55
- annotations: toolAnnotations({ readOnly: true, openWorld: true }),
90
+ // 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).
91
+ annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
56
92
  inputSchema: {
57
93
  kinds: z
58
94
  .array(z.enum(Object.keys(KIND_FILTERS)))
@@ -64,10 +100,16 @@ export function registerUnreadTools(server, { chatsvc }) {
64
100
  .string()
65
101
  .min(1)
66
102
  .optional()
67
- .describe('Case-insensitive substring of the chat title, channel name, team name or an untitled ' +
68
- "chat's participant names, or an exact conversation id."),
103
+ .describe('Case-insensitive substring of the chat title, channel name, team name, an untitled ' +
104
+ "chat's participant names or the last-message preview, or an exact conversation id."),
69
105
  include_hidden: includeHiddenArg,
106
+ include_muted: z
107
+ .boolean()
108
+ .optional()
109
+ .describe('Also return conversations the user has muted in Teams (default false: they are left out ' +
110
+ 'unread and counted in muted_skipped).'),
70
111
  since_days: sinceDaysArg(),
112
+ older_unread: olderUnreadArg(),
71
113
  per_conversation_limit: z
72
114
  .number()
73
115
  .int()
@@ -85,57 +127,114 @@ export function registerUnreadTools(server, { chatsvc }) {
85
127
  .describe(`Maximum unread conversations returned with their messages, most recent activity first ` +
86
128
  `(default ${DEFAULT_CONVERSATIONS}, max ${MAX_CONVERSATIONS}); the rest are listed in ` +
87
129
  'more_unread_conversations.'),
130
+ cursors: cursorsArg,
131
+ tz: tzArg,
132
+ format: formatArg,
133
+ mark_read: markReadArg,
134
+ confirmToken: confirmTokenParam,
88
135
  },
89
- }, async ({ kinds, query, include_hidden, since_days, per_conversation_limit, max_conversations }) => {
136
+ }, async ({ kinds, query, include_hidden, include_muted, since_days, older_unread, per_conversation_limit, max_conversations, cursors, tz, format, mark_read, confirmToken, }, ctx) => {
90
137
  try {
138
+ assertMarkReadFormat(mark_read, format);
139
+ const timeZone = resolveTimeZone(tz);
140
+ const fetched_at = new Date().toISOString();
91
141
  const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
92
142
  const allowed = new Set((kinds ?? ['chat', 'channel']).flatMap((k) => KIND_FILTERS[k]));
93
143
  // Summaries are built against the FULL listing so a channel can find its team's name.
94
144
  let candidates = raw
95
145
  .map((c) => conversationSummary(c, me, raw))
96
146
  .filter((s) => allowed.has(s.kind) && isUnreadCandidateFor(s, include_hidden));
97
- // A query can name a group chat or 1:1 by a participant, so every untitled candidate is titled first.
147
+ // A query can name a group chat or 1:1 by a participant, so every untitled candidate is titled
148
+ // first; it also matches the listing's last-message preview (no extra reads).
98
149
  if (query !== undefined)
99
- candidates = matchConversations(await enrichTitles(chatsvc, raw, me, candidates), query);
150
+ candidates = matchConversations(await enrichTitles(chatsvc, raw, me, candidates), query, {
151
+ messages: true,
152
+ });
153
+ // Muted chats are dropped after the query, so muted_skipped counts only what was asked about.
154
+ const mutedSkipped = include_muted ? 0 : candidates.filter((s) => s.muted).length;
155
+ if (!include_muted)
156
+ candidates = candidates.filter((s) => !s.muted);
100
157
  candidates.sort(byLastActivityDesc);
101
158
  const perLimit = per_conversation_limit ?? DEFAULT_PER_CONVERSATION;
102
- const outcome = await confirmUnreadCandidates(chatsvc, raw, me, candidates, { limit: perLimit, maxRaw: MAX_RAW_MESSAGES, since: sinceCutoff(since_days) });
103
- const { skippedUnreachable, olderSkipped } = outcome;
104
- // Only what is returned is titled: the unread conversations and those whose read failed.
159
+ const outcome = await confirmUnreadCandidates(chatsvc, raw, me, candidates, { limit: perLimit, maxRaw: MAX_RAW_MESSAGES, since: sinceCutoff(since_days), cursors });
160
+ const { skippedUnreachable, older } = outcome;
161
+ // Only what is returned is titled: the unread conversations, those whose read failed and,
162
+ // with older_unread, those the window left out.
163
+ const listedOlder = older_unread ? older : [];
105
164
  const retitled = await enrichTitles(chatsvc, raw, me, [
106
165
  ...outcome.confirmed.map((c) => c.summary),
107
166
  ...outcome.failed.map((f) => f.summary),
167
+ ...listedOlder.map((o) => o.summary),
108
168
  ]);
109
169
  const confirmed = outcome.confirmed.map((c, i) => ({ ...c, summary: retitled[i] }));
110
170
  const failed = outcome.failed.map((f, i) => ({ ...f, summary: retitled[outcome.confirmed.length + i] }));
171
+ const olderTitled = retitled.slice(outcome.confirmed.length + outcome.failed.length);
111
172
  const cap = max_conversations ?? DEFAULT_CONVERSATIONS;
112
- const conversations = confirmed.slice(0, cap).map(({ summary, read }) => {
113
- const messages = oldestFirst(read.messages).map((m) => normaliseMessage(m, me));
114
- const body = summary.kind === 'channel' ? { threads: groupThreads(messages) } : { messages };
115
- return {
116
- conversation: confirmedSummary(summary, true),
117
- unread_count: messages.length,
118
- ...body,
119
- ...(read.truncated
120
- ? {
121
- truncated: {
122
- returned: messages.length,
123
- hint: `Only the newest ${messages.length} unread messages were returned; pass a larger ` +
124
- `per_conversation_limit (max ${MAX_PER_CONVERSATION}) or read the conversation ` +
125
- 'with teams_read_conversation (unread_only).',
126
- },
127
- }
128
- : {}),
129
- };
130
- });
173
+ const returned = confirmed.slice(0, cap);
174
+ // Marked before roots are fetched, so a call that stops at the confirmation preview fetches none.
175
+ let marks;
176
+ if (mark_read) {
177
+ const byId = new Map(raw.map((c) => [c.id, c]));
178
+ const plans = [];
179
+ for (const { summary, read } of returned) {
180
+ // A cut read left older unread messages out: those are not the caller's to mark (see TRUNCATED_SKIP).
181
+ if (read.truncated)
182
+ continue;
183
+ const conv = byId.get(summary.id) ?? { id: summary.id };
184
+ const target = newestId(read.messages);
185
+ if (advancesHorizon(conv, target))
186
+ plans.push({ summary, previous: horizonMessageId(conv), target });
187
+ }
188
+ if (plans.length > 0) {
189
+ const gate = await confirmMarks(ctx, { tool: 'teams_get_unread', me, plans, confirmToken });
190
+ if (gate)
191
+ return gate;
192
+ }
193
+ marks = await applyMarks(chatsvc, plans);
194
+ }
195
+ const budget = rootBudget();
196
+ // Channels claim root fetches in the order returned, so the most recent activity gets them first.
197
+ const shown = returned.map(({ summary, read }) => ({
198
+ summary,
199
+ read,
200
+ messages: oldestFirst(read.messages).map((m) => normaliseMessage(m, me, { timeZone })),
201
+ }));
202
+ const roots = await mapWithConcurrency(shown, ROOT_CONVERSATION_CONCURRENCY, ({ summary, messages }) => summary.kind === 'channel'
203
+ ? fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget, timeZone })
204
+ : Promise.resolve(undefined));
205
+ const conversations = shown.map(({ summary, read, messages }, i) => ({
206
+ conversation: formatConversation(confirmedSummary(summary, true), format ?? 'full'),
207
+ unread_count: messages.length,
208
+ ...formatBody(summary.kind, messages, format ?? 'full', roots[i]),
209
+ // Every confirmed read holds at least one message, so there is always a newest.
210
+ next_cursor: newestId(read.messages),
211
+ ...(read.truncated
212
+ ? {
213
+ truncated: {
214
+ returned: messages.length,
215
+ hint: `Only the newest ${messages.length} unread messages were returned; pass a larger ` +
216
+ `per_conversation_limit (max ${MAX_PER_CONVERSATION}) or read the conversation ` +
217
+ 'with teams_read_conversation (unread_only).',
218
+ },
219
+ }
220
+ : {}),
221
+ ...(marks !== undefined
222
+ ? (marks.get(summary.id) ?? { marked_read: read.truncated ? TRUNCATED_SKIP : false })
223
+ : {}),
224
+ }));
131
225
  const rest = confirmed.slice(cap);
226
+ const next_cursors = { ...cursors };
227
+ for (const c of conversations)
228
+ next_cursors[c.conversation.id] = c.next_cursor;
132
229
  const exact = failed.length === 0 && confirmed.every((c) => !c.read.truncated);
133
230
  return untrustedResult({
134
231
  total_unread: confirmed.reduce((n, c) => n + c.read.messages.length, 0),
135
232
  total_unread_exact: exact,
136
233
  conversations,
137
234
  skipped_unreachable: skippedUnreachable,
138
- ...olderUnreadReport(olderSkipped, since_days),
235
+ muted_skipped: mutedSkipped,
236
+ ...olderUnreadReport(older.length, since_days),
237
+ ...olderUnreadConversations(listedOlder, olderTitled),
139
238
  ...(failed.length > 0
140
239
  ? {
141
240
  errors: failed.map((f) => ({
@@ -153,6 +252,8 @@ export function registerUnreadTools(server, { chatsvc }) {
153
252
  })),
154
253
  }
155
254
  : {}),
255
+ next_cursors,
256
+ fetched_at,
156
257
  });
157
258
  }
158
259
  catch (err) {
package/dist/version.js CHANGED
@@ -10,4 +10,4 @@
10
10
  * line below and nowhere else — not even in prose.
11
11
  */
12
12
  export const PACKAGE_NAME = 'microsoft-teams-mcp';
13
- export const VERSION = '0.4.0'; // x-release-please-version
13
+ export const VERSION = '0.5.0'; // x-release-please-version
package/mint.yaml CHANGED
@@ -67,6 +67,16 @@ env:
67
67
  help: >-
68
68
  Path to the cached token file. Defaults to
69
69
  ~/.microsoft-teams-mcp/token.json.
70
+ - name: TEAMS_TIME_ZONE
71
+ required: false
72
+ help: >-
73
+ Default IANA time zone (e.g. America/New_York) for the tz argument of
74
+ the read tools; messages then carry time_local. Unset means UTC only.
75
+ - name: TEAMS_SUBSTRATE_TOKEN_FILE
76
+ required: false
77
+ help: >-
78
+ Path to the cached Substrate search token file. Defaults to
79
+ ~/.microsoft-teams-mcp/substrate-token.json.
70
80
  state:
71
81
  dataDir: true
72
82
  reason: >-
@@ -79,7 +89,9 @@ egress:
79
89
  # teams.cloud.microsoft serves the chat-service API (src/chatsvc.ts). Inline
80
90
  # images download from Teams' image store on a regional *.asm.skype.com host
81
91
  # (us-api.asm.skype.com and the like) — the client sends its token nowhere
82
- # else.
92
+ # else. Message search goes to Microsoft Substrate (src/substrate.ts) with
93
+ # its own token.
83
94
  allow:
84
95
  - teams.cloud.microsoft
85
96
  - '*.asm.skype.com'
97
+ - substrate.office.com
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chrischall/microsoft-teams-mcp",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "mcpName": "io.github.chrischall/microsoft-teams-mcp",
5
5
  "description": "Microsoft Teams MCP server for Claude — developed and maintained by AI (Claude Code)",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/microsoft-teams-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "0.4.0",
9
+ "version": "0.5.0",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "@chrischall/microsoft-teams-mcp",
14
- "version": "0.4.0",
14
+ "version": "0.5.0",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -86,9 +86,16 @@
86
86
  "format": "string",
87
87
  "isSecret": false
88
88
  },
89
+ {
90
+ "name": "TEAMS_TIME_ZONE",
91
+ "description": "Default IANA time zone (e.g. America/New_York) for time_local on read results. Unset means UTC only.",
92
+ "isRequired": false,
93
+ "format": "string",
94
+ "isSecret": false
95
+ },
89
96
  {
90
97
  "name": "MCP_CONFIRM_MODE",
91
- "description": "What teams_send_message and teams_react do on a client that cannot show a confirmation prompt (claude.ai, Claude Desktop): \"ask-user\" (default: the first call returns a preview and a confirmToken, and the model must get your approval in chat before using it), \"auto\" (the model may use the token after reviewing the preview itself) or \"refuse\". An unrecognised value is treated as refuse.",
98
+ "description": "What the writes (teams_send_message, teams_react, teams_mark_read and the read tools' mark_read) do on a client that cannot show a confirmation prompt (claude.ai, Claude Desktop): \"ask-user\" (default: the first call returns a preview and a confirmToken, and the model must get your approval in chat before using it), \"auto\" (the model may use the token after reviewing the preview itself) or \"refuse\". An unrecognised value is treated as refuse.",
92
99
  "isRequired": false,
93
100
  "format": "string",
94
101
  "isSecret": false
@@ -79,8 +79,11 @@ messages, read the Activity feed, fetch an inline image — are in
79
79
  the first `;` segment of the conversation's
80
80
  `properties.consumptionhorizon`, and that is not from you (your MRI is
81
81
  `8:orgid:<oid>` from the token's `oid` claim).
82
- - **Never PUT `consumptionhorizon`.** That is how Teams marks a chat read;
83
- reading messages through this API leaves the user's unread badges alone.
82
+ - **Never PUT `consumptionhorizon`** from a shell. That is how Teams marks a
83
+ chat read; reading messages through this API leaves the user's unread
84
+ badges alone. To mark a chat read, use the MCP's confirm-gated
85
+ **`teams_mark_read`** (or `mark_read` on its read tools), which never
86
+ moves the marker backwards.
84
87
  - **`48:*` conversation ids are system threads**, not chats — skip them when
85
88
  listing. Two are worth reading by id: `48:notes` (the self-chat) and
86
89
  `48:notifications` (the Activity feed; `48:mentions` is its mentions
@@ -93,7 +96,7 @@ messages, read the Activity feed, fetch an inline image — are in
93
96
  SharePoint (Graph and SharePoint both refuse it). `properties.files` is a
94
97
  JSON *string*; parse it for each file's name and `openUrl`.
95
98
 
96
- ## Writes (sending, reacting)
99
+ ## Writes (sending, reacting, marking read)
97
100
 
98
101
  Everything above only reads. To post a message or a reaction, prefer the
99
102
  MCP's **`teams_send_message`** and **`teams_react`**: they show the user a