@chrischall/microsoft-teams-mcp 0.5.1 → 0.6.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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +31 -2
- package/dist/bundle.js +239 -18
- package/dist/chatsvc.js +10 -3
- package/dist/model.js +10 -0
- package/dist/tools/changes.js +1 -7
- package/dist/tools/conversation.js +54 -3
- package/dist/tools/format.js +10 -0
- package/dist/tools/from.js +143 -0
- package/dist/tools/unread.js +144 -5
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/server.json +2 -2
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
},
|
|
8
8
|
"metadata": {
|
|
9
9
|
"description": "MCP server for Microsoft Teams — read any chat or channel, your unread messages, and their attachments, and send messages and reactions (each confirmed first)",
|
|
10
|
-
"version": "0.
|
|
10
|
+
"version": "0.6.0"
|
|
11
11
|
},
|
|
12
12
|
"plugins": [
|
|
13
13
|
{
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
"displayName": "Microsoft Teams",
|
|
16
16
|
"source": "./",
|
|
17
17
|
"description": "MCP server for Microsoft Teams — read any chat or channel, your unread messages, and their attachments, and send messages and reactions (each confirmed first), via your signed-in browser session",
|
|
18
|
-
"version": "0.
|
|
18
|
+
"version": "0.6.0",
|
|
19
19
|
"author": {
|
|
20
20
|
"name": "Chris Hall"
|
|
21
21
|
},
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "microsoft-teams-mcp",
|
|
3
3
|
"displayName": "Microsoft Teams",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.6.0",
|
|
5
5
|
"description": "Microsoft Teams for Claude — read any chat or channel, your unread messages, and their attachments, and send messages and reactions (each confirmed first), using your signed-in browser session",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Chris Hall",
|
package/README.md
CHANGED
|
@@ -269,7 +269,9 @@ Everything is optional — by default the token is captured from your browser.
|
|
|
269
269
|
is new — so passing it back as `after_message_id` reads only what arrived
|
|
270
270
|
since. `after_message_id` takes message ids only: to read what
|
|
271
271
|
`teams_get_changes` counted, pass that row's `after_message_id`, not its
|
|
272
|
-
`next_cursor`. See [Cursors](#cursors-only-what-is-new).
|
|
272
|
+
`next_cursor`. See [Cursors](#cursors-only-what-is-new). `from` pages
|
|
273
|
+
oldest first from a UTC time instead — see
|
|
274
|
+
[Paging from a time](#paging-from-a-time).
|
|
273
275
|
`format` sets how much comes back: `full` (default, everything above),
|
|
274
276
|
`compact` (each message only `id`, `time`, `time_local`, `sender`, `text`,
|
|
275
277
|
plus `subject` when set — no reactions, attachments or edited/deleted
|
|
@@ -299,7 +301,9 @@ Everything is optional — by default the token is captured from your browser.
|
|
|
299
301
|
only messages you had already read still marks). An empty read, or an
|
|
300
302
|
`after_message_id` with nothing new, marks nothing (`marked_read: false`).
|
|
301
303
|
- `teams_get_unread` — every unread message across your chats and channels,
|
|
302
|
-
grouped by conversation, most recent first
|
|
304
|
+
grouped by conversation, most recent first (or, with `from`, one
|
|
305
|
+
oldest-first list across them all — see
|
|
306
|
+
[Paging from a time](#paging-from-a-time)). Filter by `kinds` (`chat`,
|
|
303
307
|
`channel`, `meeting`, `oneOnOne`) or `query` (title, channel or team
|
|
304
308
|
name, an untitled chat's participant name, or the last-message preview —
|
|
305
309
|
each conversation then carries `match_reason`, as in `teams_list_chats`);
|
|
@@ -554,6 +558,31 @@ instead.
|
|
|
554
558
|
id. Each of its conversation rows carries the message-id cursor to hand on,
|
|
555
559
|
`after_message_id`, for `teams_read_conversation` (or `teams_get_unread`'s
|
|
556
560
|
`cursors`). Each tool rejects the other kind.
|
|
561
|
+
- <a id="paging-from-a-time"></a>**Paging from a time (ingestion and
|
|
562
|
+
backfill).** `teams_read_conversation` and `teams_get_unread` take `from`:
|
|
563
|
+
a UTC time (ISO 8601; one with no zone is read as UTC) or a previous
|
|
564
|
+
result's `next_from`. They return what arrived at or after it **oldest
|
|
565
|
+
first**, at most `limit` (default 50; `teams_get_unread` pools every
|
|
566
|
+
conversation into one `messages` list, each message carrying its
|
|
567
|
+
`conversation_id`), plus `has_more`, `next_from` and `next_from_time`.
|
|
568
|
+
Pass `next_from` back as `from` until `has_more` is false; it is returned
|
|
569
|
+
on the last (and an empty) page too, so the same call keeps polling for
|
|
570
|
+
what arrives later. Messages sharing a millisecond are never split or
|
|
571
|
+
repeated across pages; delivery is otherwise at-least-once (`next_from`
|
|
572
|
+
never moves past the newest change the listing knew of, and not at all
|
|
573
|
+
while a read failed), so dedupe on message id. **Cost:** Teams serves
|
|
574
|
+
messages newest first with no way to seek, so each call reads everything
|
|
575
|
+
that changed since its `from` — a deep backfill gets faster as it catches
|
|
576
|
+
up — and a conversation with more than 20,000 messages since `from`
|
|
577
|
+
cannot be paged oldest first: `teams_read_conversation` reports an error
|
|
578
|
+
rather than skip any, and `teams_get_unread` returns what arrived after the
|
|
579
|
+
oldest point it reached, names the stretch it could not read in
|
|
580
|
+
`incomplete` (`unread_not_read_from` / `unread_not_read_until`), and keeps
|
|
581
|
+
`next_from` moving — so one oversized conversation never stalls the stream.
|
|
582
|
+
`from` replaces `since` /
|
|
583
|
+
`after_message_id` / `mark_read` (and, for `teams_get_unread`, `since_days`,
|
|
584
|
+
`cursors`, the per-conversation limits, `older_unread` and
|
|
585
|
+
`format: "summary"`).
|
|
557
586
|
|
|
558
587
|
- **Results are framed as untrusted.** Every data tool returns
|
|
559
588
|
`{ untrusted_content: true, note, ... }` and says in its description that
|
package/dist/bundle.js
CHANGED
|
@@ -20542,10 +20542,10 @@ var init_v4 = __esm({
|
|
|
20542
20542
|
}
|
|
20543
20543
|
});
|
|
20544
20544
|
|
|
20545
|
-
// node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs
|
|
20545
|
+
// node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs
|
|
20546
20546
|
var LATEST_PROTOCOL_VERSION, SUPPORTED_PROTOCOL_VERSIONS, RELATED_TASK_META_KEY, PROTOCOL_VERSION_META_KEY, CLIENT_INFO_META_KEY, SERVER_INFO_META_KEY, CLIENT_CAPABILITIES_META_KEY, SUBSCRIPTION_ID_META_KEY, LOG_LEVEL_META_KEY, JSONRPC_VERSION, JSONValueSchema, JSONObjectSchema, JSONArraySchema, ProgressTokenSchema, CursorSchema, TaskMetadataSchema, RelatedTaskMetadataSchema, RequestMetaSchema, BaseRequestParamsSchema, TaskAugmentedRequestParamsSchema, RequestSchema, NotificationsParamsSchema, NotificationSchema, ResultMetaObjectSchema, ResultSchema, RequestIdSchema, JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema, JSONRPCMessageSchema, JSONRPCResponseSchema, EmptyResultSchema, CancelledNotificationParamsSchema, CancelledNotificationSchema, IconSchema, IconsSchema, BaseMetadataSchema, ImplementationSchema, FormElicitationCapabilitySchema, ElicitationCapabilitySchema, ClientTasksCapabilitySchema, ServerTasksCapabilitySchema, ClientCapabilitiesSchema, InitializeRequestParamsSchema, InitializeRequestSchema, ServerCapabilitiesSchema, InitializeResultSchema, InitializedNotificationSchema, DiscoverRequestSchema, DiscoverResultSchema, PingRequestSchema, ProgressSchema, ProgressNotificationParamsSchema, ProgressNotificationSchema, PaginatedRequestParamsSchema, PaginatedRequestSchema, PaginatedResultSchema, ResourceContentsSchema, TextResourceContentsSchema, Base64Schema, BlobResourceContentsSchema, RoleSchema, AnnotationsSchema, ResourceSchema, ResourceTemplateSchema, ListResourcesRequestSchema, ListResourcesResultSchema, ListResourceTemplatesRequestSchema, ListResourceTemplatesResultSchema, ResourceRequestParamsSchema, ReadResourceRequestParamsSchema, ReadResourceRequestSchema, ReadResourceResultSchema, ResourceListChangedNotificationSchema, SubscribeRequestParamsSchema, SubscribeRequestSchema, UnsubscribeRequestParamsSchema, UnsubscribeRequestSchema, SubscriptionFilterSchema, SubscriptionsListenRequestParamsSchema, SubscriptionsListenRequestSchema, SubscriptionsAcknowledgedNotificationParamsSchema, SubscriptionsAcknowledgedNotificationSchema, SubscriptionsListenResultMetaSchema, SubscriptionsListenResultSchema, ResourceUpdatedNotificationParamsSchema, ResourceUpdatedNotificationSchema, PromptArgumentSchema, PromptSchema, ListPromptsRequestSchema, ListPromptsResultSchema, GetPromptRequestParamsSchema, GetPromptRequestSchema, TextContentSchema, ImageContentSchema, AudioContentSchema, ToolUseContentSchema, EmbeddedResourceSchema, ResourceLinkSchema, ContentBlockSchema, PromptMessageSchema, GetPromptResultSchema, PromptListChangedNotificationSchema, ToolAnnotationsSchema, ToolExecutionSchema, ToolSchema, ListToolsRequestSchema, ListToolsResultSchema, CallToolResultSchema, CompatibilityCallToolResultSchema, CallToolRequestParamsSchema, CallToolRequestSchema, ToolListChangedNotificationSchema, ListChangedOptionsBaseSchema, LoggingLevelSchema, SetLevelRequestParamsSchema, SetLevelRequestSchema, LoggingMessageNotificationParamsSchema, LoggingMessageNotificationSchema, ModelHintSchema, ModelPreferencesSchema, ToolChoiceSchema, ToolResultContentSchema, SamplingContentSchema, SamplingMessageContentBlockSchema, SamplingMessageSchema, CreateMessageRequestParamsSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema, UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema, LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema, EnumSchemaSchema, PrimitiveSchemaDefinitionSchema, ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema, ElicitRequestParamsSchema, ElicitRequestSchema, ElicitationCompleteNotificationParamsSchema, ElicitationCompleteNotificationSchema, ElicitResultSchema, ResourceTemplateReferenceSchema, PromptReferenceSchema, CompleteRequestParamsSchema, CompleteRequestSchema, CompleteResultSchema, RootSchema, ListRootsRequestSchema, ListRootsResultSchema, RootsListChangedNotificationSchema, TaskCreationParamsSchema, TaskStatusSchema, TaskSchema, CreateTaskResultSchema, TaskStatusNotificationParamsSchema, TaskStatusNotificationSchema, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, GetTaskPayloadResultSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, ClientRequestSchema, ClientNotificationSchema, ClientResultSchema, ServerRequestSchema, ServerNotificationSchema, ServerResultSchema, SafeUrlSchema, OAuthProtectedResourceMetadataSchema, OAuthMetadataSchema, OpenIdProviderMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, OAuthTokensSchema, IdJagTokenExchangeResponseSchema, OAuthErrorResponseSchema, OptionalSafeUrlSchema, OAuthClientMetadataSchema, OAuthClientInformationSchema, OAuthClientInformationFullSchema, OAuthClientRegistrationErrorSchema, OAuthTokenRevocationRequestSchema;
|
|
20547
20547
|
var init_auth_BNDyLTqp = __esm({
|
|
20548
|
-
"node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs"() {
|
|
20548
|
+
"node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/auth-BNDyLTqp.mjs"() {
|
|
20549
20549
|
init_v4();
|
|
20550
20550
|
LATEST_PROTOCOL_VERSION = "2025-11-25";
|
|
20551
20551
|
SUPPORTED_PROTOCOL_VERSIONS = [
|
|
@@ -21489,9 +21489,9 @@ var init_auth_BNDyLTqp = __esm({
|
|
|
21489
21489
|
}
|
|
21490
21490
|
});
|
|
21491
21491
|
|
|
21492
|
-
// node_modules/@modelcontextprotocol/core/dist/internal.mjs
|
|
21492
|
+
// node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/internal.mjs
|
|
21493
21493
|
var init_internal = __esm({
|
|
21494
|
-
"node_modules/@modelcontextprotocol/core/dist/internal.mjs"() {
|
|
21494
|
+
"node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/dist/internal.mjs"() {
|
|
21495
21495
|
init_auth_BNDyLTqp();
|
|
21496
21496
|
}
|
|
21497
21497
|
});
|
|
@@ -37080,7 +37080,7 @@ var init_version = __esm({
|
|
|
37080
37080
|
"src/version.ts"() {
|
|
37081
37081
|
"use strict";
|
|
37082
37082
|
PACKAGE_NAME = "microsoft-teams-mcp";
|
|
37083
|
-
VERSION = "0.
|
|
37083
|
+
VERSION = "0.6.0";
|
|
37084
37084
|
}
|
|
37085
37085
|
});
|
|
37086
37086
|
|
|
@@ -48618,6 +48618,11 @@ function localIsoTime(iso, timeZone) {
|
|
|
48618
48618
|
const abs = Math.abs(offsetMin);
|
|
48619
48619
|
return `${pad(get("year"), 4)}-${pad(get("month"))}-${pad(get("day"))}T${pad(get("hour"))}:${pad(get("minute"))}:${pad(get("second"))}.${pad(millis, 3)}${sign2}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`;
|
|
48620
48620
|
}
|
|
48621
|
+
function changedMs(m) {
|
|
48622
|
+
const v = Number(m.version);
|
|
48623
|
+
const id = Number(m.id);
|
|
48624
|
+
return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
|
|
48625
|
+
}
|
|
48621
48626
|
function normaliseMessage(m, meMri, opts = {}) {
|
|
48622
48627
|
const props = m.properties ?? {};
|
|
48623
48628
|
const mri = senderMri(m.from);
|
|
@@ -48925,16 +48930,17 @@ var ChatServiceClient = class {
|
|
|
48925
48930
|
}
|
|
48926
48931
|
/**
|
|
48927
48932
|
* A conversation's messages, newest first, paging back until `stopAt`
|
|
48928
|
-
* accepts a message, `max` are collected, the pages run out, or
|
|
48929
|
-
* have been read.
|
|
48933
|
+
* accepts a message, `max` are collected, the pages run out, or `maxPages`
|
|
48934
|
+
* (default 20) have been read.
|
|
48930
48935
|
*/
|
|
48931
48936
|
async getMessages(id, opts) {
|
|
48932
48937
|
this.#requireConfigured();
|
|
48933
48938
|
const out = [];
|
|
48934
48939
|
if (!(opts.max > 0)) return out;
|
|
48940
|
+
const seen = /* @__PURE__ */ new Set();
|
|
48935
48941
|
let url2 = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
|
|
48936
48942
|
for (let page = 0; url2 !== void 0; page++) {
|
|
48937
|
-
if (page >= MAX_MESSAGE_PAGES) {
|
|
48943
|
+
if (page >= (opts.maxPages ?? MAX_MESSAGE_PAGES)) {
|
|
48938
48944
|
opts.onCapped?.();
|
|
48939
48945
|
break;
|
|
48940
48946
|
}
|
|
@@ -48943,6 +48949,8 @@ var ChatServiceClient = class {
|
|
|
48943
48949
|
if (msgs.length === 0) break;
|
|
48944
48950
|
let stopped = false;
|
|
48945
48951
|
for (const m of msgs) {
|
|
48952
|
+
if (seen.has(m.id)) continue;
|
|
48953
|
+
seen.add(m.id);
|
|
48946
48954
|
if (opts.stopAt?.(m)) {
|
|
48947
48955
|
stopped = true;
|
|
48948
48956
|
continue;
|
|
@@ -50440,6 +50448,10 @@ function compactMessage(m) {
|
|
|
50440
50448
|
...m.subject !== void 0 ? { subject: m.subject } : {}
|
|
50441
50449
|
};
|
|
50442
50450
|
}
|
|
50451
|
+
function formatFlatMessage(m, format) {
|
|
50452
|
+
if (format === "full") return m;
|
|
50453
|
+
return { ...compactMessage(m), ...m.replyTo !== void 0 ? { replyTo: m.replyTo } : {} };
|
|
50454
|
+
}
|
|
50443
50455
|
var isMissing = (root) => "missing" in root;
|
|
50444
50456
|
var isOutside = (root) => "outside_window" in root;
|
|
50445
50457
|
function newestTime(messages) {
|
|
@@ -50493,6 +50505,85 @@ function formatBody(kind, messages, format, roots = NO_ROOTS) {
|
|
|
50493
50505
|
return channel ? { threads: groupThreads(messages, roots) } : { messages: [...messages] };
|
|
50494
50506
|
}
|
|
50495
50507
|
|
|
50508
|
+
// src/tools/from.ts
|
|
50509
|
+
init_zod();
|
|
50510
|
+
init_dist2();
|
|
50511
|
+
var FROM_MAX_RAW = 2e4;
|
|
50512
|
+
var FROM_MAX_PAGES = 100;
|
|
50513
|
+
var fromArg = external_exports.string().min(1).optional().describe(
|
|
50514
|
+
"Page oldest first from here: a UTC time (ISO 8601, e.g. 2026-10-01T00:00:00Z; one with no zone is read as UTC) or a previous result's next_from, unchanged. Returns messages that arrived at or after it, oldest first, up to limit, with next_from (pass it back as from for the next page \u2014 also once has_more is false, to pick up what arrives later) and has_more."
|
|
50515
|
+
);
|
|
50516
|
+
var FROM_DESCRIPTION = `from pages oldest first for ingestion and backfill: messages that arrived at or after a UTC time (or a previous result's next_from), oldest first, at most limit; next_from (always returned, with next_from_time) resumes after the last message returned and has_more says whether more are already waiting. Pass an old from and keep passing next_from to backfill; once has_more is false the same next_from picks up what arrives later. Delivery is at-least-once: dedupe on message id. Teams pages newest first, so a from call reads everything since from (up to ${FROM_MAX_RAW} raw messages per conversation, past which it never skips silently: it says what it could not read): the further back from is, the slower the call. `;
|
|
50517
|
+
function badFrom(from) {
|
|
50518
|
+
return new McpToolError(`"${from}" is not a from position.`, {
|
|
50519
|
+
hint: "Pass a UTC time such as 2026-10-01T00:00:00Z, or a previous result's next_from unchanged."
|
|
50520
|
+
});
|
|
50521
|
+
}
|
|
50522
|
+
function decodeFrom(from) {
|
|
50523
|
+
if (/^[A-Za-z0-9_-]+$/.test(from)) {
|
|
50524
|
+
let parsed;
|
|
50525
|
+
try {
|
|
50526
|
+
parsed = JSON.parse(Buffer.from(from, "base64url").toString("utf8"));
|
|
50527
|
+
} catch {
|
|
50528
|
+
parsed = void 0;
|
|
50529
|
+
}
|
|
50530
|
+
if (parsed !== void 0) {
|
|
50531
|
+
const { t: t2, s } = parsed ?? {};
|
|
50532
|
+
const seen = s === void 0 ? [] : s;
|
|
50533
|
+
if (typeof t2 === "number" && Number.isFinite(t2) && t2 >= 0 && Array.isArray(seen) && seen.every((k) => typeof k === "string")) {
|
|
50534
|
+
return { t: t2, seen };
|
|
50535
|
+
}
|
|
50536
|
+
throw badFrom(from);
|
|
50537
|
+
}
|
|
50538
|
+
}
|
|
50539
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(from)) throw badFrom(from);
|
|
50540
|
+
const zoned = /T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(from) ? `${from}Z` : from;
|
|
50541
|
+
const t = Date.parse(zoned);
|
|
50542
|
+
if (Number.isNaN(t)) throw badFrom(from);
|
|
50543
|
+
return { t, seen: [] };
|
|
50544
|
+
}
|
|
50545
|
+
function encodeFrom({ t, seen }) {
|
|
50546
|
+
return Buffer.from(JSON.stringify(seen.length > 0 ? { t, s: seen } : { t }), "utf8").toString("base64url");
|
|
50547
|
+
}
|
|
50548
|
+
function takePage(items, pos, limit, ceiling) {
|
|
50549
|
+
const seen = new Set(pos.seen);
|
|
50550
|
+
const pending = items.filter((i) => i.ms > pos.t || i.ms === pos.t && !seen.has(i.key)).sort((a, b) => a.ms - b.ms || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
50551
|
+
const page = pending.slice(0, limit);
|
|
50552
|
+
const last = page.at(-1);
|
|
50553
|
+
let next = pos;
|
|
50554
|
+
if (last !== void 0) {
|
|
50555
|
+
const t = Math.max(pos.t, ceiling !== void 0 ? Math.min(last.ms, ceiling) : last.ms);
|
|
50556
|
+
const atT = page.filter((i) => i.ms === t).map((i) => i.key);
|
|
50557
|
+
next = { t, seen: t === pos.t ? [...pos.seen, ...atT] : atT };
|
|
50558
|
+
}
|
|
50559
|
+
return { page: page.map((i) => i.item), has_more: pending.length > page.length, remaining: pending.length - page.length, next };
|
|
50560
|
+
}
|
|
50561
|
+
function fromReport(pos, next, hasMore) {
|
|
50562
|
+
return {
|
|
50563
|
+
from_time: new Date(pos.t).toISOString(),
|
|
50564
|
+
has_more: hasMore,
|
|
50565
|
+
next_from: encodeFrom(next),
|
|
50566
|
+
next_from_time: new Date(next.t).toISOString()
|
|
50567
|
+
};
|
|
50568
|
+
}
|
|
50569
|
+
async function readFrom(chatsvc, id, boundary) {
|
|
50570
|
+
let capped = false;
|
|
50571
|
+
const messages = await chatsvc.getMessages(id, {
|
|
50572
|
+
stopAt: (m) => changedMs(m) < boundary,
|
|
50573
|
+
max: FROM_MAX_RAW,
|
|
50574
|
+
maxPages: FROM_MAX_PAGES,
|
|
50575
|
+
onCapped: () => capped = true
|
|
50576
|
+
});
|
|
50577
|
+
if (!capped) return { messages };
|
|
50578
|
+
return { messages, reachedMs: Math.min(...messages.map(changedMs)) };
|
|
50579
|
+
}
|
|
50580
|
+
function tooBusy(boundary, reachedMs) {
|
|
50581
|
+
return {
|
|
50582
|
+
error: `More than ${FROM_MAX_RAW} messages changed in this conversation since ${new Date(boundary).toISOString()}: a read reached back only to ${new Date(reachedMs).toISOString()}, as Teams pages newest first.`,
|
|
50583
|
+
hint: "Pass a later from."
|
|
50584
|
+
};
|
|
50585
|
+
}
|
|
50586
|
+
|
|
50496
50587
|
// src/tools/roots.ts
|
|
50497
50588
|
init_dist2();
|
|
50498
50589
|
var MAX_ROOT_FETCHES = 25;
|
|
@@ -50960,7 +51051,37 @@ async function resolveListed(chatsvc, raw, me, conversation, verb) {
|
|
|
50960
51051
|
}
|
|
50961
51052
|
var MAX_CONVERSATIONS = 20;
|
|
50962
51053
|
var READ_CONCURRENCY = 4;
|
|
50963
|
-
async function
|
|
51054
|
+
async function readOneFrom(chatsvc, raw, me, summary, pos, { unreadOnly, limit, timeZone, format, roots }) {
|
|
51055
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
51056
|
+
const horizon = readHorizon(conv);
|
|
51057
|
+
const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
|
|
51058
|
+
const boundary = unreadOnly ? Math.max(pos.t, horizon + 1) : pos.t;
|
|
51059
|
+
const { messages: fetched, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
|
|
51060
|
+
if (reachedMs !== void 0) {
|
|
51061
|
+
const { error: error62, hint } = tooBusy(boundary, reachedMs);
|
|
51062
|
+
throw new McpToolError(error62, { hint });
|
|
51063
|
+
}
|
|
51064
|
+
const { page, has_more, next } = takePage(
|
|
51065
|
+
fetched.filter(wanted).map((m) => ({ ms: arrivalMs(m), key: m.id, item: m })),
|
|
51066
|
+
pos,
|
|
51067
|
+
limit
|
|
51068
|
+
);
|
|
51069
|
+
const messages = page.map((m) => normaliseMessage(m, me, { timeZone }));
|
|
51070
|
+
const outsideRoots = summary.kind === "channel" ? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone }) : void 0;
|
|
51071
|
+
return {
|
|
51072
|
+
summary,
|
|
51073
|
+
conv,
|
|
51074
|
+
newest: newestId(page),
|
|
51075
|
+
result: {
|
|
51076
|
+
conversation: formatConversation(summary, format),
|
|
51077
|
+
...formatBody(summary.kind, messages, format, outsideRoots),
|
|
51078
|
+
...fromReport(pos, next, has_more)
|
|
51079
|
+
}
|
|
51080
|
+
};
|
|
51081
|
+
}
|
|
51082
|
+
async function readOne(chatsvc, raw, me, summary, opts) {
|
|
51083
|
+
if (opts.from !== void 0) return readOneFrom(chatsvc, raw, me, summary, opts.from, opts);
|
|
51084
|
+
const { unreadOnly, since, afterMessageId, limit, timeZone, format, roots } = opts;
|
|
50964
51085
|
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
50965
51086
|
const horizon = readHorizon(conv);
|
|
50966
51087
|
const cutoff = since !== void 0 ? Date.parse(since) : void 0;
|
|
@@ -51069,7 +51190,7 @@ function registerConversationTools(server, { chatsvc }) {
|
|
|
51069
51190
|
"teams_read_conversation",
|
|
51070
51191
|
{
|
|
51071
51192
|
title: "Read a Teams chat or channel",
|
|
51072
|
-
description: `Read the messages of any chat or channel the signed-in user is in, by id (from teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in Teams. "48:notes" (or the name "notes" / "self") is the user's own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, each root post with its replies. A root older than the window is fetched and marked outside_window: true (it is context, not counted or cursored); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. unread_only returns just the messages the user has not read; since stops at a time; limit keeps the newest (truncated says when more exist; unread_count_scope "window" says unread_count only covers what limit/since/after_message_id let through). after_message_id returns only messages newer than that id; next_cursor is the newest returned message id (or after_message_id when nothing is new) \u2014 pass it back as after_message_id to read only what arrived since. after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then { conversations: [...], errors, fetched_at }, one single-read result per conversation (the other arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ... } object a single read returns, and one that cannot be resolved or read is listed in errors while the rest still come back. ` + MARK_READ_DESCRIPTION + "With mark_read the read marker of each conversation read moves up to the newest message returned (never backwards; outside_window roots do not count) and its result says marked_read; one whose limit or since cut off unread messages older than those returned is not marked (marked_read: { skipped, hint }), while a limit that cut only already-read messages does not stop it; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. " + CONFIRM_INJECTION_RULE + " Attachments are listed per message (images by ref, files by name) and fetched with teams_get_attachment. A name that matches several conversations is not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each with id, title, kind, team, lastActivity and match_reason), hint} and no messages \u2014 read again with one candidate's id. " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51193
|
+
description: `Read the messages of any chat or channel the signed-in user is in, by id (from teams_list_chats / teams_list_teams_and_channels) or by name, without opening it in Teams. "48:notes" (or the name "notes" / "self") is the user's own notes self-chat. Messages come oldest first, each with id, time (UTC, ISO 8601), sender, fromMe, text (never truncated; table cells separated by " | "), subject, edited/deleted flags and attachments; a channel is returned as threads, each root post with its replies. A root older than the window is fetched and marked outside_window: true (it is context, not counted or cursored); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. unread_only returns just the messages the user has not read; since stops at a time; limit keeps the newest (truncated says when more exist; unread_count_scope "window" says unread_count only covers what limit/since/after_message_id let through). after_message_id returns only messages newer than that id; next_cursor is the newest returned message id (or after_message_id when nothing is new) \u2014 pass it back as after_message_id to read only what arrived since. after_message_id takes message-id cursors only: to read what teams_get_changes counted, pass that row's after_message_id, never teams_get_changes' next_cursor (a time token for teams_get_changes). ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + `conversation may also be an array of up to ${MAX_CONVERSATIONS} ids/names: the result is then { conversations: [...], errors, fetched_at }, one single-read result per conversation (the other arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ... } object a single read returns, and one that cannot be resolved or read is listed in errors while the rest still come back. ` + FROM_DESCRIPTION + "With from, limit keeps the OLDEST messages, unread_only pages only unread ones, and since, after_message_id and mark_read cannot be used; the result carries from_time, has_more, next_from and next_from_time in place of unread_count and next_cursor. " + MARK_READ_DESCRIPTION + "With mark_read the read marker of each conversation read moves up to the newest message returned (never backwards; outside_window roots do not count) and its result says marked_read; one whose limit or since cut off unread messages older than those returned is not marked (marked_read: { skipped, hint }), while a limit that cut only already-read messages does not stop it; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. " + CONFIRM_INJECTION_RULE + " Attachments are listed per message (images by ref, files by name) and fetched with teams_get_attachment. A name that matches several conversations is not an error: the result is {ambiguous: true, query, match_count, candidates (up to 10, each with id, title, kind, team, lastActivity and match_reason), hint} and no messages \u2014 read again with one candidate's id. " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51073
51194
|
// 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).
|
|
51074
51195
|
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
51075
51196
|
inputSchema: {
|
|
@@ -51079,20 +51200,30 @@ function registerConversationTools(server, { chatsvc }) {
|
|
|
51079
51200
|
unread_only: external_exports.boolean().optional().describe("Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set."),
|
|
51080
51201
|
since: sinceArg,
|
|
51081
51202
|
after_message_id: afterMessageIdArg,
|
|
51082
|
-
|
|
51203
|
+
from: fromArg,
|
|
51204
|
+
limit: limitArg(MAX_MESSAGES, "messages", "newest first kept; with from, oldest first kept"),
|
|
51083
51205
|
tz: tzArg,
|
|
51084
51206
|
format: formatArg,
|
|
51085
51207
|
mark_read: markReadArg,
|
|
51086
51208
|
confirmToken: confirmTokenParam
|
|
51087
51209
|
}
|
|
51088
51210
|
},
|
|
51089
|
-
async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
51211
|
+
async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
51090
51212
|
try {
|
|
51091
51213
|
assertMarkReadFormat(mark_read, format);
|
|
51214
|
+
if (from !== void 0) {
|
|
51215
|
+
const clash = since !== void 0 ? "since" : after_message_id !== void 0 ? "after_message_id" : mark_read ? "mark_read" : void 0;
|
|
51216
|
+
if (clash !== void 0) {
|
|
51217
|
+
throw new McpToolError(`from cannot be combined with ${clash}.`, {
|
|
51218
|
+
hint: "from is its own position: pass a previous next_from to go on. To mark what was paged read, use teams_mark_read."
|
|
51219
|
+
});
|
|
51220
|
+
}
|
|
51221
|
+
}
|
|
51092
51222
|
const opts = {
|
|
51093
51223
|
unreadOnly: unread_only ?? false,
|
|
51094
51224
|
since,
|
|
51095
51225
|
afterMessageId: after_message_id,
|
|
51226
|
+
from: from !== void 0 ? decodeFrom(from) : void 0,
|
|
51096
51227
|
limit: limit ?? DEFAULT_LIMIT,
|
|
51097
51228
|
timeZone: resolveTimeZone(tz),
|
|
51098
51229
|
format: format ?? "full",
|
|
@@ -51147,6 +51278,7 @@ var MAX_PER_CONVERSATION = 200;
|
|
|
51147
51278
|
var DEFAULT_PER_CONVERSATION = 50;
|
|
51148
51279
|
var MAX_CONVERSATIONS2 = 50;
|
|
51149
51280
|
var DEFAULT_CONVERSATIONS = 20;
|
|
51281
|
+
var MAX_FROM_MESSAGES = 500;
|
|
51150
51282
|
var MAX_RAW_MESSAGES2 = 4e3;
|
|
51151
51283
|
var ROOT_CONVERSATION_CONCURRENCY = 4;
|
|
51152
51284
|
var KIND_FILTERS = {
|
|
@@ -51162,12 +51294,77 @@ var TRUNCATED_SKIP = {
|
|
|
51162
51294
|
function byLastActivityDesc2(a, b) {
|
|
51163
51295
|
return (b.lastActivity ?? "").localeCompare(a.lastActivity ?? "");
|
|
51164
51296
|
}
|
|
51297
|
+
async function unreadFrom(chatsvc, raw, me, candidates, pos, { limit, timeZone, format }) {
|
|
51298
|
+
const byId = new Map(raw.map((c) => [c.id, c]));
|
|
51299
|
+
const toRead = candidates.filter((s) => (lastChangeMs(byId.get(s.id) ?? { id: s.id }) ?? Infinity) >= pos.t);
|
|
51300
|
+
const results = await mapWithConcurrency(toRead, CONFIRM_CONCURRENCY, async (summary) => {
|
|
51301
|
+
const horizon = readHorizon(byId.get(summary.id) ?? { id: summary.id });
|
|
51302
|
+
try {
|
|
51303
|
+
const boundary = Math.max(pos.t, horizon + 1);
|
|
51304
|
+
const { messages, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
|
|
51305
|
+
const known = (m) => reachedMs === void 0 || arrivalMs(m) > reachedMs;
|
|
51306
|
+
return { kind: "read", messages: messages.filter((m) => isUnread(m, horizon, me) && known(m)), boundary, reachedMs };
|
|
51307
|
+
} catch (error62) {
|
|
51308
|
+
return isUnreachable(error62) ? { kind: "unreachable" } : { kind: "failed", error: error62 };
|
|
51309
|
+
}
|
|
51310
|
+
});
|
|
51311
|
+
let skippedUnreachable = 0;
|
|
51312
|
+
let anyRead = false;
|
|
51313
|
+
const items = [];
|
|
51314
|
+
const failed = [];
|
|
51315
|
+
const tooDeep = [];
|
|
51316
|
+
results.forEach((r, i) => {
|
|
51317
|
+
const summary = toRead[i];
|
|
51318
|
+
if (r.kind === "unreachable") skippedUnreachable++;
|
|
51319
|
+
else if (r.kind === "failed") failed.push({ summary, error: r.error });
|
|
51320
|
+
else {
|
|
51321
|
+
anyRead = true;
|
|
51322
|
+
if (r.reachedMs !== void 0) tooDeep.push({ summary, boundary: r.boundary, reachedMs: r.reachedMs });
|
|
51323
|
+
for (const m of r.messages) items.push({ ms: arrivalMs(m), key: `${summary.id}/${m.id}`, item: { summary, m } });
|
|
51324
|
+
}
|
|
51325
|
+
});
|
|
51326
|
+
if (failed.length > 0 && !anyRead) throw failed[0].error;
|
|
51327
|
+
const listed = Math.max(pos.t, ...raw.map((c) => lastChangeMs(c) ?? 0));
|
|
51328
|
+
const { page, has_more, remaining, next } = takePage(items, pos, limit, failed.length > 0 ? pos.t : listed);
|
|
51329
|
+
const shown = [...new Map(page.map(({ summary }) => [summary.id, summary])).values()];
|
|
51330
|
+
const titled = await enrichTitles(chatsvc, raw, me, [
|
|
51331
|
+
...shown,
|
|
51332
|
+
...failed.map((f) => f.summary),
|
|
51333
|
+
...tooDeep.map((d) => d.summary)
|
|
51334
|
+
]);
|
|
51335
|
+
const titledDeep = titled.slice(shown.length + failed.length);
|
|
51336
|
+
return {
|
|
51337
|
+
total_unread: page.length + remaining,
|
|
51338
|
+
messages: page.map(({ summary, m }) => ({
|
|
51339
|
+
conversation_id: summary.id,
|
|
51340
|
+
...formatFlatMessage(normaliseMessage(m, me, { timeZone }), format)
|
|
51341
|
+
})),
|
|
51342
|
+
conversations: titled.slice(0, shown.length).map((s) => formatConversation(confirmedSummary(s, true), format)),
|
|
51343
|
+
...fromReport(pos, next, has_more),
|
|
51344
|
+
skipped_unreachable: skippedUnreachable,
|
|
51345
|
+
...failed.length > 0 ? {
|
|
51346
|
+
errors: failed.map((f, i) => ({
|
|
51347
|
+
conversation: titled[shown.length + i],
|
|
51348
|
+
error: wrapApiError(f.error, "read this conversation").message
|
|
51349
|
+
}))
|
|
51350
|
+
} : {},
|
|
51351
|
+
...tooDeep.length > 0 ? {
|
|
51352
|
+
incomplete: tooDeep.map((d, i) => ({
|
|
51353
|
+
conversation: titledDeep[i],
|
|
51354
|
+
unread_not_read_from: new Date(d.boundary).toISOString(),
|
|
51355
|
+
unread_not_read_until: new Date(d.reachedMs).toISOString(),
|
|
51356
|
+
...tooBusy(d.boundary, d.reachedMs)
|
|
51357
|
+
}))
|
|
51358
|
+
} : {}
|
|
51359
|
+
};
|
|
51360
|
+
}
|
|
51361
|
+
var NOT_WITH_FROM = ["since_days", "cursors", "per_conversation_limit", "max_conversations", "mark_read", "older_unread"];
|
|
51165
51362
|
function registerUnreadTools(server, { chatsvc }) {
|
|
51166
51363
|
server.registerTool(
|
|
51167
51364
|
"teams_get_unread",
|
|
51168
51365
|
{
|
|
51169
51366
|
title: "Get unread Teams messages",
|
|
51170
|
-
description: `Get every unread message across all the chats and channels the signed-in user is in (or those matching kinds / query), grouped by conversation, most recent activity first. Each conversation comes with its summary (id, kind, title, team) and only the messages the user has not read, oldest first; a channel's are grouped as threads under their root post. A root the user already read is fetched and marked outside_window: true (it is context, not unread or counted); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. Exact, as in Teams: every conversation with activity past its read marker (or never opened) is read past the marker and kept only if it holds a real message from someone else, so a call recording, transcript or other system event never makes a conversation unread. Channels the user has hidden in Teams are left out (include_hidden adds them); one that is gone or no longer readable (404/403) is skipped and counted in skipped_unreachable. Only conversations whose newest unread message is from the last 14 days are returned by default (since_days widens or narrows it); older unread conversations \u2014 typically dormant channels \u2014 are not read past their marker and are counted in older_unread_skipped; older_unread: true also lists them in older_unread_conversations (id, kind, title, team, lastActivity, and unread_count only for those already read \u2014 unread_count_known: false otherwise). Chats the user muted in Teams (muted: true) are left out too and counted in muted_skipped, without being read; include_muted adds them. Unread conversations past max_conversations are listed by id, title and unread_count in more_unread_conversations; read one with teams_read_conversation. A conversation that could not be read is listed in errors and the rest still come back. total_unread covers every unread conversation found; total_unread_exact is false when a per-conversation limit truncated or a read failed. cursors ({ conversationId: messageId }) returns only unread messages newer than each conversation's cursor (one with none is left out, and total_unread counts only those). Each returned conversation carries next_cursor, its newest returned message id; next_cursors is the cursors passed in updated with every returned conversation's next_cursor (not those only in more_unread_conversations) \u2014 pass it back as cursors to get only what is new. ` + CURSOR_NO_CACHE_DESCRIPTION + FORMAT_DESCRIPTION + MARK_READ_DESCRIPTION + 'With mark_read each conversation returned with its messages (not more_unread_conversations) has its read marker moved up to its newest unread message returned (outside_window roots do not count) and carries marked_read (false with mark_read_warning when that move failed); one per_conversation_limit cut is not marked \u2014 marked_read: { skipped: "truncated", hint }; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. ' + CONFIRM_INJECTION_RULE + " " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names, and the last-message preview. " + MATCH_REASON_DESCRIPTION + "Message times are UTC (ISO 8601); " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51367
|
+
description: `Get every unread message across all the chats and channels the signed-in user is in (or those matching kinds / query), grouped by conversation, most recent activity first. Each conversation comes with its summary (id, kind, title, team) and only the messages the user has not read, oldest first; a channel's are grouped as threads under their root post. A root the user already read is fetched and marked outside_window: true (it is context, not unread or counted); up to ${MAX_ROOT_FETCHES} roots are fetched per call, and any beyond that or that cannot be fetched is { id, missing: true }. Exact, as in Teams: every conversation with activity past its read marker (or never opened) is read past the marker and kept only if it holds a real message from someone else, so a call recording, transcript or other system event never makes a conversation unread. Channels the user has hidden in Teams are left out (include_hidden adds them); one that is gone or no longer readable (404/403) is skipped and counted in skipped_unreachable. Only conversations whose newest unread message is from the last 14 days are returned by default (since_days widens or narrows it); older unread conversations \u2014 typically dormant channels \u2014 are not read past their marker and are counted in older_unread_skipped; older_unread: true also lists them in older_unread_conversations (id, kind, title, team, lastActivity, and unread_count only for those already read \u2014 unread_count_known: false otherwise). Chats the user muted in Teams (muted: true) are left out too and counted in muted_skipped, without being read; include_muted adds them. Unread conversations past max_conversations are listed by id, title and unread_count in more_unread_conversations; read one with teams_read_conversation. A conversation that could not be read is listed in errors and the rest still come back. total_unread covers every unread conversation found; total_unread_exact is false when a per-conversation limit truncated or a read failed. cursors ({ conversationId: messageId }) returns only unread messages newer than each conversation's cursor (one with none is left out, and total_unread counts only those). Each returned conversation carries next_cursor, its newest returned message id; next_cursors is the cursors passed in updated with every returned conversation's next_cursor (not those only in more_unread_conversations) \u2014 pass it back as cursors to get only what is new. ` + CURSOR_NO_CACHE_DESCRIPTION + FROM_DESCRIPTION + "With from the result is one list across every conversation instead: messages (each with its conversation_id; a channel reply keeps replyTo), oldest first, at most limit; conversations (the summary of each one on the page); total_unread (every unread message past from, this page and later ones); from_time, has_more, next_from, next_from_time; skipped_unreachable, muted_skipped and errors. next_from does not move while a read failed (call again). A conversation with more messages since from than a read can reach is listed in incomplete instead (unread_not_read_from / unread_not_read_until name the stretch not read; what arrived after it is returned) and does not hold next_from. from takes the place of since_days, cursors, per_conversation_limit, max_conversations, older_unread and mark_read, and format summary does not apply. " + FORMAT_DESCRIPTION + MARK_READ_DESCRIPTION + 'With mark_read each conversation returned with its messages (not more_unread_conversations) has its read marker moved up to its newest unread message returned (outside_window roots do not count) and carries marked_read (false with mark_read_warning when that move failed); one per_conversation_limit cut is not marked \u2014 marked_read: { skipped: "truncated", hint }; the user confirms first \u2014 a prompt where the client supports one, otherwise the first call returns only a preview and a confirmToken, and the repeat call with it reads and marks. ' + CONFIRM_INJECTION_RULE + " " + GROUP_TITLE_DESCRIPTION + " query also matches those participant names, and the last-message preview. " + MATCH_REASON_DESCRIPTION + "Message times are UTC (ISO 8601); " + TIME_ZONE_DESCRIPTION + UNTRUSTED_DESCRIPTION_SUFFIX2,
|
|
51171
51368
|
// 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).
|
|
51172
51369
|
annotations: toolAnnotations({ readOnly: false, destructive: false, idempotent: true, openWorld: true }),
|
|
51173
51370
|
inputSchema: {
|
|
@@ -51190,6 +51387,10 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
51190
51387
|
`Maximum unread conversations returned with their messages, most recent activity first (default ${DEFAULT_CONVERSATIONS}, max ${MAX_CONVERSATIONS2}); the rest are listed in more_unread_conversations.`
|
|
51191
51388
|
),
|
|
51192
51389
|
cursors: cursorsArg,
|
|
51390
|
+
from: fromArg,
|
|
51391
|
+
limit: external_exports.number().int().min(1).max(MAX_FROM_MESSAGES).optional().describe(
|
|
51392
|
+
`With from only: maximum messages returned across every conversation, oldest first (default ${DEFAULT_LIMIT}, max ${MAX_FROM_MESSAGES}).`
|
|
51393
|
+
),
|
|
51193
51394
|
tz: tzArg,
|
|
51194
51395
|
format: formatArg,
|
|
51195
51396
|
mark_read: markReadArg,
|
|
@@ -51206,6 +51407,8 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
51206
51407
|
per_conversation_limit,
|
|
51207
51408
|
max_conversations,
|
|
51208
51409
|
cursors,
|
|
51410
|
+
from,
|
|
51411
|
+
limit,
|
|
51209
51412
|
tz,
|
|
51210
51413
|
format,
|
|
51211
51414
|
mark_read,
|
|
@@ -51213,6 +51416,21 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
51213
51416
|
}, ctx) => {
|
|
51214
51417
|
try {
|
|
51215
51418
|
assertMarkReadFormat(mark_read, format);
|
|
51419
|
+
if (from === void 0 && limit !== void 0) {
|
|
51420
|
+
throw new McpToolError("limit applies only with from.", {
|
|
51421
|
+
hint: "Without from, use per_conversation_limit and max_conversations."
|
|
51422
|
+
});
|
|
51423
|
+
}
|
|
51424
|
+
if (from !== void 0) {
|
|
51425
|
+
const args = { since_days, cursors, per_conversation_limit, max_conversations, mark_read, older_unread };
|
|
51426
|
+
const clash = NOT_WITH_FROM.find((k) => args[k] !== void 0 && args[k] !== false);
|
|
51427
|
+
if (clash !== void 0 || format === "summary") {
|
|
51428
|
+
throw new McpToolError(`from cannot be combined with ${clash ?? "format summary"}.`, {
|
|
51429
|
+
hint: "from pages one oldest-first list across every conversation: pass a previous next_from to go on, and use teams_mark_read to mark what was paged read."
|
|
51430
|
+
});
|
|
51431
|
+
}
|
|
51432
|
+
}
|
|
51433
|
+
const pos = from !== void 0 ? decodeFrom(from) : void 0;
|
|
51216
51434
|
const timeZone = resolveTimeZone(tz);
|
|
51217
51435
|
const fetched_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
51218
51436
|
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
@@ -51224,6 +51442,14 @@ function registerUnreadTools(server, { chatsvc }) {
|
|
|
51224
51442
|
const mutedSkipped = include_muted ? 0 : candidates.filter((s) => s.muted).length;
|
|
51225
51443
|
if (!include_muted) candidates = candidates.filter((s) => !s.muted);
|
|
51226
51444
|
candidates.sort(byLastActivityDesc2);
|
|
51445
|
+
if (pos !== void 0) {
|
|
51446
|
+
const page = await unreadFrom(chatsvc, raw, me, candidates, pos, {
|
|
51447
|
+
limit: limit ?? DEFAULT_LIMIT,
|
|
51448
|
+
timeZone,
|
|
51449
|
+
format: format === "compact" ? "compact" : "full"
|
|
51450
|
+
});
|
|
51451
|
+
return untrustedResult2({ ...page, muted_skipped: mutedSkipped, fetched_at });
|
|
51452
|
+
}
|
|
51227
51453
|
const perLimit = per_conversation_limit ?? DEFAULT_PER_CONVERSATION;
|
|
51228
51454
|
const outcome = await confirmUnreadCandidates(
|
|
51229
51455
|
chatsvc,
|
|
@@ -51354,11 +51580,6 @@ function decodeChangesCursor(cursor) {
|
|
|
51354
51580
|
if (Number.isNaN(t)) throw badCursor(cursor);
|
|
51355
51581
|
return t;
|
|
51356
51582
|
}
|
|
51357
|
-
function changedMs(m) {
|
|
51358
|
-
const v = Number(m.version);
|
|
51359
|
-
const id = Number(m.id);
|
|
51360
|
-
return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
|
|
51361
|
-
}
|
|
51362
51583
|
async function readChanges(chatsvc, summary, t, me) {
|
|
51363
51584
|
let capped = false;
|
|
51364
51585
|
const fetched = await chatsvc.getMessages(summary.id, {
|
package/dist/chatsvc.js
CHANGED
|
@@ -257,18 +257,19 @@ export class ChatServiceClient {
|
|
|
257
257
|
}
|
|
258
258
|
/**
|
|
259
259
|
* A conversation's messages, newest first, paging back until `stopAt`
|
|
260
|
-
* accepts a message, `max` are collected, the pages run out, or
|
|
261
|
-
* have been read.
|
|
260
|
+
* accepts a message, `max` are collected, the pages run out, or `maxPages`
|
|
261
|
+
* (default 20) have been read.
|
|
262
262
|
*/
|
|
263
263
|
async getMessages(id, opts) {
|
|
264
264
|
this.#requireConfigured();
|
|
265
265
|
const out = [];
|
|
266
266
|
if (!(opts.max > 0))
|
|
267
267
|
return out;
|
|
268
|
+
const seen = new Set();
|
|
268
269
|
let url = `${this.#baseUrl}/users/ME/conversations/${encodeURIComponent(id)}/messages` +
|
|
269
270
|
`?view=msnp24Equivalent|supportsMessageProperties&pageSize=${opts.pageSize ?? DEFAULT_MESSAGE_PAGE_SIZE}&startTime=1`;
|
|
270
271
|
for (let page = 0; url !== undefined; page++) {
|
|
271
|
-
if (page >= MAX_MESSAGE_PAGES) {
|
|
272
|
+
if (page >= (opts.maxPages ?? MAX_MESSAGE_PAGES)) {
|
|
272
273
|
opts.onCapped?.();
|
|
273
274
|
break;
|
|
274
275
|
}
|
|
@@ -281,6 +282,12 @@ export class ChatServiceClient {
|
|
|
281
282
|
// each message it rejects — and only the NEXT page is not fetched.
|
|
282
283
|
let stopped = false;
|
|
283
284
|
for (const m of msgs) {
|
|
285
|
+
// Live (2026-10-14) the service served one message — same id, same version — on two pages
|
|
286
|
+
// (2 of 567). The first copy stands; a repeat is neither returned nor shown to `stopAt`,
|
|
287
|
+
// whose limit counting would otherwise count it twice.
|
|
288
|
+
if (seen.has(m.id))
|
|
289
|
+
continue;
|
|
290
|
+
seen.add(m.id);
|
|
284
291
|
if (opts.stopAt?.(m)) {
|
|
285
292
|
stopped = true;
|
|
286
293
|
continue;
|
package/dist/model.js
CHANGED
|
@@ -512,6 +512,16 @@ export function localIsoTime(iso, timeZone) {
|
|
|
512
512
|
return (`${pad(get('year'), 4)}-${pad(get('month'))}-${pad(get('day'))}T${pad(get('hour'))}:${pad(get('minute'))}:` +
|
|
513
513
|
`${pad(get('second'))}.${pad(millis, 3)}${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`);
|
|
514
514
|
}
|
|
515
|
+
/**
|
|
516
|
+
* A message's last change (epoch ms): its `version`, else its arrival (the id).
|
|
517
|
+
* Live (2026-10-12), pages come newest CHANGE first, so a read that must not
|
|
518
|
+
* miss what arrived after a time stops on this, never on arrival.
|
|
519
|
+
*/
|
|
520
|
+
export function changedMs(m) {
|
|
521
|
+
const v = Number(m.version);
|
|
522
|
+
const id = Number(m.id);
|
|
523
|
+
return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
|
|
524
|
+
}
|
|
515
525
|
export function normaliseMessage(m, meMri, opts = {}) {
|
|
516
526
|
const props = m.properties ?? {};
|
|
517
527
|
const mri = senderMri(m.from);
|
package/dist/tools/changes.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { mapWithConcurrency, McpToolError, toolAnnotations } from '@chrischall/mcp-utils';
|
|
3
|
-
import { conversationSummary, isUserMessage, lastChangeMs, normaliseMessage, } from '../model.js';
|
|
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
6
|
import { enrichTitles } from './titles.js';
|
|
@@ -54,12 +54,6 @@ export function decodeChangesCursor(cursor) {
|
|
|
54
54
|
throw badCursor(cursor);
|
|
55
55
|
return t;
|
|
56
56
|
}
|
|
57
|
-
/** A message's last change (epoch ms): its `version`, else its arrival (the id). */
|
|
58
|
-
function changedMs(m) {
|
|
59
|
-
const v = Number(m.version);
|
|
60
|
-
const id = Number(m.id);
|
|
61
|
-
return Math.max(Number.isFinite(v) ? v : 0, Number.isFinite(id) ? id : 0);
|
|
62
|
-
}
|
|
63
57
|
/** Read one conversation down to `t` and count what arrived after it. */
|
|
64
58
|
async function readChanges(chatsvc, summary, t, me) {
|
|
65
59
|
let capped = false;
|
|
@@ -9,6 +9,7 @@ import { DEFAULT_LIMIT, limitArg, makeLimitedStopAt, sinceArg } from './limit.js
|
|
|
9
9
|
import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
|
|
10
10
|
import { afterMessageIdArg, CURSOR_NO_CACHE_DESCRIPTION, newestId } from './cursor.js';
|
|
11
11
|
import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
|
|
12
|
+
import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage, tooBusy } from './from.js';
|
|
12
13
|
import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
|
|
13
14
|
import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
|
|
14
15
|
const MAX_MESSAGES = 500;
|
|
@@ -130,8 +131,43 @@ export async function resolveListed(chatsvc, raw, me, conversation, verb) {
|
|
|
130
131
|
export const MAX_CONVERSATIONS = 20;
|
|
131
132
|
/** Conversations read at once in a multi-conversation read. */
|
|
132
133
|
export const READ_CONCURRENCY = 4;
|
|
134
|
+
/**
|
|
135
|
+
* One page of a conversation from a `from` position: everything since it read
|
|
136
|
+
* (`readFrom`), its real messages (unread ones with `unreadOnly`) taken oldest
|
|
137
|
+
* first (`takePage`).
|
|
138
|
+
*/
|
|
139
|
+
async function readOneFrom(chatsvc, raw, me, summary, pos, { unreadOnly, limit, timeZone, format, roots }) {
|
|
140
|
+
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
141
|
+
const horizon = readHorizon(conv);
|
|
142
|
+
const wanted = (m) => isUserMessage(m) && (!unreadOnly || isUnread(m, horizon, me));
|
|
143
|
+
const boundary = unreadOnly ? Math.max(pos.t, horizon + 1) : pos.t;
|
|
144
|
+
const { messages: fetched, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
|
|
145
|
+
// Its oldest messages are unknown, and a page taken from what was read would skip them.
|
|
146
|
+
if (reachedMs !== undefined) {
|
|
147
|
+
const { error, hint } = tooBusy(boundary, reachedMs);
|
|
148
|
+
throw new McpToolError(error, { hint });
|
|
149
|
+
}
|
|
150
|
+
const { page, has_more, next } = takePage(fetched.filter(wanted).map((m) => ({ ms: arrivalMs(m), key: m.id, item: m })), pos, limit);
|
|
151
|
+
const messages = page.map((m) => normaliseMessage(m, me, { timeZone }));
|
|
152
|
+
const outsideRoots = summary.kind === 'channel'
|
|
153
|
+
? await fetchOutsideRoots(chatsvc, summary.id, messages, me, { budget: roots, timeZone })
|
|
154
|
+
: undefined;
|
|
155
|
+
return {
|
|
156
|
+
summary,
|
|
157
|
+
conv,
|
|
158
|
+
newest: newestId(page),
|
|
159
|
+
result: {
|
|
160
|
+
conversation: formatConversation(summary, format),
|
|
161
|
+
...formatBody(summary.kind, messages, format, outsideRoots),
|
|
162
|
+
...fromReport(pos, next, has_more),
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
133
166
|
/** Read one resolved conversation. */
|
|
134
|
-
async function readOne(chatsvc, raw, me, summary,
|
|
167
|
+
async function readOne(chatsvc, raw, me, summary, opts) {
|
|
168
|
+
if (opts.from !== undefined)
|
|
169
|
+
return readOneFrom(chatsvc, raw, me, summary, opts.from, opts);
|
|
170
|
+
const { unreadOnly, since, afterMessageId, limit, timeZone, format, roots } = opts;
|
|
135
171
|
// The self-chat resolves even when the listing does not carry it.
|
|
136
172
|
const conv = raw.find((c) => c.id === summary.id) ?? { id: summary.id };
|
|
137
173
|
const horizon = readHorizon(conv);
|
|
@@ -299,6 +335,10 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
299
335
|
'arguments apply to each); an ambiguous name takes its place among them as the same { ambiguous: true, ' +
|
|
300
336
|
'... } object a single read returns, and one that cannot be resolved or read is listed in errors ' +
|
|
301
337
|
'while the rest still come back. ' +
|
|
338
|
+
FROM_DESCRIPTION +
|
|
339
|
+
'With from, limit keeps the OLDEST messages, unread_only pages only unread ones, and since, ' +
|
|
340
|
+
'after_message_id and mark_read cannot be used; the result carries from_time, has_more, next_from and ' +
|
|
341
|
+
'next_from_time in place of unread_count and next_cursor. ' +
|
|
302
342
|
MARK_READ_DESCRIPTION +
|
|
303
343
|
'With mark_read the read marker of each conversation read moves up to the newest message returned ' +
|
|
304
344
|
'(never backwards; outside_window roots do not count) and its result says marked_read; one whose limit ' +
|
|
@@ -328,19 +368,30 @@ export function registerConversationTools(server, { chatsvc }) {
|
|
|
328
368
|
.describe('Only return messages the user has not read yet (default false). Does not mark them read unless mark_read is set.'),
|
|
329
369
|
since: sinceArg,
|
|
330
370
|
after_message_id: afterMessageIdArg,
|
|
331
|
-
|
|
371
|
+
from: fromArg,
|
|
372
|
+
limit: limitArg(MAX_MESSAGES, 'messages', 'newest first kept; with from, oldest first kept'),
|
|
332
373
|
tz: tzArg,
|
|
333
374
|
format: formatArg,
|
|
334
375
|
mark_read: markReadArg,
|
|
335
376
|
confirmToken: confirmTokenParam,
|
|
336
377
|
},
|
|
337
|
-
}, async ({ conversation, unread_only, since, after_message_id, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
378
|
+
}, async ({ conversation, unread_only, since, after_message_id, from, limit, tz, format, mark_read, confirmToken }, ctx) => {
|
|
338
379
|
try {
|
|
339
380
|
assertMarkReadFormat(mark_read, format);
|
|
381
|
+
if (from !== undefined) {
|
|
382
|
+
const clash = since !== undefined ? 'since' : after_message_id !== undefined ? 'after_message_id' : mark_read ? 'mark_read' : undefined;
|
|
383
|
+
if (clash !== undefined) {
|
|
384
|
+
throw new McpToolError(`from cannot be combined with ${clash}.`, {
|
|
385
|
+
hint: 'from is its own position: pass a previous next_from to go on. To mark what was paged read, use ' +
|
|
386
|
+
'teams_mark_read.',
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
}
|
|
340
390
|
const opts = {
|
|
341
391
|
unreadOnly: unread_only ?? false,
|
|
342
392
|
since,
|
|
343
393
|
afterMessageId: after_message_id,
|
|
394
|
+
from: from !== undefined ? decodeFrom(from) : undefined,
|
|
344
395
|
limit: limit ?? DEFAULT_LIMIT,
|
|
345
396
|
timeZone: resolveTimeZone(tz),
|
|
346
397
|
format: format ?? 'full',
|
package/dist/tools/format.js
CHANGED
|
@@ -69,6 +69,16 @@ function compactMessage(m) {
|
|
|
69
69
|
...(m.subject !== undefined ? { subject: m.subject } : {}),
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
+
/**
|
|
73
|
+
* One message of a flat, cross-conversation list (`teams_get_unread` with
|
|
74
|
+
* `from`): whole in full; compact, but keeping `replyTo`, since no thread
|
|
75
|
+
* grouping says what a channel reply answers. Summary has no messages.
|
|
76
|
+
*/
|
|
77
|
+
export function formatFlatMessage(m, format) {
|
|
78
|
+
if (format === 'full')
|
|
79
|
+
return m;
|
|
80
|
+
return { ...compactMessage(m), ...(m.replyTo !== undefined ? { replyTo: m.replyTo } : {}) };
|
|
81
|
+
}
|
|
72
82
|
const isMissing = (root) => 'missing' in root;
|
|
73
83
|
const isOutside = (root) => 'outside_window' in root;
|
|
74
84
|
/** The newest of oldest-first `messages`, as `newest_time` (and `newest_time_local`); nothing for none. */
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Oldest-first paging from a time: `from` in, `next_from` out.
|
|
3
|
+
*
|
|
4
|
+
* A caller ingesting messages passes a UTC time as `from` and gets what
|
|
5
|
+
* arrived at or after it, OLDEST first, at most `limit`; `next_from` is where
|
|
6
|
+
* the page ended, and passing it back as `from` returns the next page. It is
|
|
7
|
+
* always returned — on the last page too, and on an empty one (the position
|
|
8
|
+
* unchanged) — so the same loop that backfills history keeps polling for what
|
|
9
|
+
* is new. The server keeps no state: the position is the token.
|
|
10
|
+
*
|
|
11
|
+
* A position is a time plus the keys already returned AT that time (`seen`),
|
|
12
|
+
* so messages sharing a millisecond — across conversations, say — are neither
|
|
13
|
+
* skipped nor repeated when a page ends among them. The token is base64url
|
|
14
|
+
* JSON `{ t, s? }`; a plain ISO 8601 time is a position with nothing seen.
|
|
15
|
+
*
|
|
16
|
+
* The chat service pages newest first, so a page from `from` is found by
|
|
17
|
+
* reading everything that changed since `from` and taking its oldest: a call
|
|
18
|
+
* costs what has happened since its `from`, not its `limit`. Reads therefore
|
|
19
|
+
* stop on a message's last change, not its arrival (`changedMs`, as
|
|
20
|
+
* `teams_get_changes` learned), and run deeper than other reads
|
|
21
|
+
* ({@link FROM_MAX_RAW}); a conversation busier than that since `from` cannot
|
|
22
|
+
* be paged oldest first and says so.
|
|
23
|
+
*/
|
|
24
|
+
import { z } from 'zod';
|
|
25
|
+
import { McpToolError } from '@chrischall/mcp-utils';
|
|
26
|
+
import { changedMs } from '../model.js';
|
|
27
|
+
/** Raw messages a `from` read may page through per conversation (100 pages of 200). */
|
|
28
|
+
export const FROM_MAX_RAW = 20_000;
|
|
29
|
+
export const FROM_MAX_PAGES = 100;
|
|
30
|
+
export const fromArg = z
|
|
31
|
+
.string()
|
|
32
|
+
.min(1)
|
|
33
|
+
.optional()
|
|
34
|
+
.describe('Page oldest first from here: a UTC time (ISO 8601, e.g. 2026-10-01T00:00:00Z; one with no zone is read ' +
|
|
35
|
+
"as UTC) or a previous result's next_from, unchanged. Returns messages that arrived at or after it, " +
|
|
36
|
+
'oldest first, up to limit, with next_from (pass it back as from for the next page — also once has_more ' +
|
|
37
|
+
'is false, to pick up what arrives later) and has_more.');
|
|
38
|
+
/** Shared description text for `from` paging. */
|
|
39
|
+
export const FROM_DESCRIPTION = 'from pages oldest first for ingestion and backfill: messages that arrived at or after a UTC time (or a ' +
|
|
40
|
+
"previous result's next_from), oldest first, at most limit; next_from (always returned, with next_from_time) " +
|
|
41
|
+
'resumes after the last message returned and has_more says whether more are already waiting. Pass an old ' +
|
|
42
|
+
'from and keep passing next_from to backfill; once has_more is false the same next_from picks up what ' +
|
|
43
|
+
'arrives later. Delivery is at-least-once: dedupe on message id. Teams pages newest first, so a from call ' +
|
|
44
|
+
`reads everything since from (up to ${FROM_MAX_RAW} raw messages per conversation, past which it never ` +
|
|
45
|
+
'skips silently: it says what it could not read): the further back from is, the slower the call. ';
|
|
46
|
+
function badFrom(from) {
|
|
47
|
+
return new McpToolError(`"${from}" is not a from position.`, {
|
|
48
|
+
hint: "Pass a UTC time such as 2026-10-01T00:00:00Z, or a previous result's next_from unchanged.",
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
/** The position a `from` names: a {@link encodeFrom} token, or an ISO 8601 time (UTC when it names no zone). */
|
|
52
|
+
export function decodeFrom(from) {
|
|
53
|
+
if (/^[A-Za-z0-9_-]+$/.test(from)) {
|
|
54
|
+
let parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = JSON.parse(Buffer.from(from, 'base64url').toString('utf8'));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
parsed = undefined;
|
|
60
|
+
}
|
|
61
|
+
if (parsed !== undefined) {
|
|
62
|
+
const { t, s } = (parsed ?? {});
|
|
63
|
+
const seen = s === undefined ? [] : s;
|
|
64
|
+
if (typeof t === 'number' &&
|
|
65
|
+
Number.isFinite(t) &&
|
|
66
|
+
t >= 0 &&
|
|
67
|
+
Array.isArray(seen) &&
|
|
68
|
+
seen.every((k) => typeof k === 'string')) {
|
|
69
|
+
return { t, seen: seen };
|
|
70
|
+
}
|
|
71
|
+
throw badFrom(from);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// Only a string that looks like a date: Date.parse is lenient with words. A date-time with no zone
|
|
75
|
+
// would parse as LOCAL time, so it is pinned to UTC.
|
|
76
|
+
if (!/^\d{4}-\d{2}-\d{2}/.test(from))
|
|
77
|
+
throw badFrom(from);
|
|
78
|
+
const zoned = /T\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(from) ? `${from}Z` : from;
|
|
79
|
+
const t = Date.parse(zoned);
|
|
80
|
+
if (Number.isNaN(t))
|
|
81
|
+
throw badFrom(from);
|
|
82
|
+
return { t, seen: [] };
|
|
83
|
+
}
|
|
84
|
+
export function encodeFrom({ t, seen }) {
|
|
85
|
+
return Buffer.from(JSON.stringify(seen.length > 0 ? { t, s: seen } : { t }), 'utf8').toString('base64url');
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The page at `pos`: the items not yet returned, oldest first (ties by key),
|
|
89
|
+
* the first `limit` of them, and the position after the last. `ceiling`
|
|
90
|
+
* (epoch ms) caps how far the position moves: an item newer than it is
|
|
91
|
+
* returned but will come again, because something that arrived as late as it
|
|
92
|
+
* may not have been read yet.
|
|
93
|
+
*/
|
|
94
|
+
export function takePage(items, pos, limit, ceiling) {
|
|
95
|
+
const seen = new Set(pos.seen);
|
|
96
|
+
const pending = items
|
|
97
|
+
.filter((i) => i.ms > pos.t || (i.ms === pos.t && !seen.has(i.key)))
|
|
98
|
+
.sort((a, b) => a.ms - b.ms || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
|
|
99
|
+
const page = pending.slice(0, limit);
|
|
100
|
+
const last = page.at(-1);
|
|
101
|
+
let next = pos;
|
|
102
|
+
if (last !== undefined) {
|
|
103
|
+
const t = Math.max(pos.t, ceiling !== undefined ? Math.min(last.ms, ceiling) : last.ms);
|
|
104
|
+
const atT = page.filter((i) => i.ms === t).map((i) => i.key);
|
|
105
|
+
next = { t, seen: t === pos.t ? [...pos.seen, ...atT] : atT };
|
|
106
|
+
}
|
|
107
|
+
return { page: page.map((i) => i.item), has_more: pending.length > page.length, remaining: pending.length - page.length, next };
|
|
108
|
+
}
|
|
109
|
+
/** What every `from` result carries about where it is and how to go on. */
|
|
110
|
+
export function fromReport(pos, next, hasMore) {
|
|
111
|
+
return {
|
|
112
|
+
from_time: new Date(pos.t).toISOString(),
|
|
113
|
+
has_more: hasMore,
|
|
114
|
+
next_from: encodeFrom(next),
|
|
115
|
+
next_from_time: new Date(next.t).toISOString(),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Every message of a conversation that changed at or after `boundary` (epoch
|
|
120
|
+
* ms), newest change first — so every message that ARRIVED at or after it,
|
|
121
|
+
* plus older ones edited or reacted to since — or, when that is more than a
|
|
122
|
+
* read can reach, as far back as it got (`reachedMs`).
|
|
123
|
+
*/
|
|
124
|
+
export async function readFrom(chatsvc, id, boundary) {
|
|
125
|
+
let capped = false;
|
|
126
|
+
const messages = await chatsvc.getMessages(id, {
|
|
127
|
+
stopAt: (m) => changedMs(m) < boundary,
|
|
128
|
+
max: FROM_MAX_RAW,
|
|
129
|
+
maxPages: FROM_MAX_PAGES,
|
|
130
|
+
onCapped: () => (capped = true),
|
|
131
|
+
});
|
|
132
|
+
if (!capped)
|
|
133
|
+
return { messages };
|
|
134
|
+
return { messages, reachedMs: Math.min(...messages.map(changedMs)) };
|
|
135
|
+
}
|
|
136
|
+
/** Why a conversation cannot be paged oldest first from `boundary`, and what to do. */
|
|
137
|
+
export function tooBusy(boundary, reachedMs) {
|
|
138
|
+
return {
|
|
139
|
+
error: `More than ${FROM_MAX_RAW} messages changed in this conversation since ${new Date(boundary).toISOString()}: ` +
|
|
140
|
+
`a read reached back only to ${new Date(reachedMs).toISOString()}, as Teams pages newest first.`,
|
|
141
|
+
hint: 'Pass a later from.',
|
|
142
|
+
};
|
|
143
|
+
}
|
package/dist/tools/unread.js
CHANGED
|
@@ -1,20 +1,25 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, toolAnnotations } from '@chrischall/mcp-utils';
|
|
3
|
-
import { conversationSummary, matchConversations, normaliseMessage, oldestFirst, } from '../model.js';
|
|
4
|
-
import { confirmedSummary, confirmUnreadCandidates, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
|
|
2
|
+
import { CONFIRM_INJECTION_RULE, confirmTokenParam, mapWithConcurrency, McpToolError, toolAnnotations, } from '@chrischall/mcp-utils';
|
|
3
|
+
import { conversationSummary, isUnread, lastChangeMs, matchConversations, normaliseMessage, oldestFirst, readHorizon, } from '../model.js';
|
|
4
|
+
import { CONFIRM_CONCURRENCY, confirmedSummary, confirmUnreadCandidates, isUnreachable, olderUnreadArg, olderUnreadConversations, olderUnreadReport, sinceCutoff, sinceDaysArg, } from './confirm.js';
|
|
5
5
|
import { GROUP_TITLE_DESCRIPTION, includeHiddenArg, isUnreadCandidateFor, MATCH_REASON_DESCRIPTION } from './listing.js';
|
|
6
6
|
import { enrichTitles } from './titles.js';
|
|
7
7
|
import { wrapApiError } from './errors.js';
|
|
8
8
|
import { untrustedResult, UNTRUSTED_DESCRIPTION_SUFFIX } from './untrusted.js';
|
|
9
9
|
import { resolveTimeZone, TIME_ZONE_DESCRIPTION, tzArg } from './timezone.js';
|
|
10
10
|
import { CURSOR_NO_CACHE_DESCRIPTION, cursorsArg, newestId } from './cursor.js';
|
|
11
|
-
import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation } from './format.js';
|
|
11
|
+
import { FORMAT_DESCRIPTION, formatArg, formatBody, formatConversation, formatFlatMessage } from './format.js';
|
|
12
|
+
import { arrivalMs } from './conversation.js';
|
|
13
|
+
import { DEFAULT_LIMIT } from './limit.js';
|
|
14
|
+
import { decodeFrom, FROM_DESCRIPTION, fromArg, fromReport, readFrom, takePage, tooBusy, } from './from.js';
|
|
12
15
|
import { fetchOutsideRoots, MAX_ROOT_FETCHES, rootBudget } from './roots.js';
|
|
13
16
|
import { advancesHorizon, applyMarks, confirmMarks, horizonMessageId, MARK_READ_DESCRIPTION, markReadArg, assertMarkReadFormat, } from './markread.js';
|
|
14
17
|
const MAX_PER_CONVERSATION = 200;
|
|
15
18
|
const DEFAULT_PER_CONVERSATION = 50;
|
|
16
19
|
const MAX_CONVERSATIONS = 50;
|
|
17
20
|
const DEFAULT_CONVERSATIONS = 20;
|
|
21
|
+
/** Messages one `from` page may return, across every conversation. */
|
|
22
|
+
const MAX_FROM_MESSAGES = 500;
|
|
18
23
|
/**
|
|
19
24
|
* Raw messages read per conversation before giving up. The real bound is the
|
|
20
25
|
* read horizon; this only caps a backlog of nothing but system events.
|
|
@@ -40,6 +45,98 @@ const TRUNCATED_SKIP = {
|
|
|
40
45
|
function byLastActivityDesc(a, b) {
|
|
41
46
|
return (b.lastActivity ?? '').localeCompare(a.lastActivity ?? '');
|
|
42
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* One `from` page of unread messages across `candidates`: each read past the
|
|
50
|
+
* later of `from` and its own horizon (one with no change since `from` is not
|
|
51
|
+
* read), its real unread messages pooled and taken oldest first. The position
|
|
52
|
+
* never moves past the newest change the listing knew of — a message landing
|
|
53
|
+
* mid-call in a conversation already read is then not skipped — nor at all
|
|
54
|
+
* when a read failed, since that conversation may hold older unread messages.
|
|
55
|
+
*
|
|
56
|
+
* A conversation too busy to read back to `from` is not a failed read: that
|
|
57
|
+
* would recur on every call and hold the position for good. What arrived
|
|
58
|
+
* after the oldest point its read reached is complete, so it is paged like the
|
|
59
|
+
* rest; the stretch before it is named in `incomplete`, and the position moves.
|
|
60
|
+
*/
|
|
61
|
+
async function unreadFrom(chatsvc, raw, me, candidates, pos, { limit, timeZone, format }) {
|
|
62
|
+
const byId = new Map(raw.map((c) => [c.id, c]));
|
|
63
|
+
const toRead = candidates.filter((s) => (lastChangeMs(byId.get(s.id) ?? { id: s.id }) ?? Infinity) >= pos.t);
|
|
64
|
+
const results = await mapWithConcurrency(toRead, CONFIRM_CONCURRENCY, async (summary) => {
|
|
65
|
+
const horizon = readHorizon(byId.get(summary.id) ?? { id: summary.id });
|
|
66
|
+
try {
|
|
67
|
+
const boundary = Math.max(pos.t, horizon + 1);
|
|
68
|
+
const { messages, reachedMs } = await readFrom(chatsvc, summary.id, boundary);
|
|
69
|
+
// Past a too-busy read's reach only what arrived after it is known complete.
|
|
70
|
+
const known = (m) => reachedMs === undefined || arrivalMs(m) > reachedMs;
|
|
71
|
+
return { kind: 'read', messages: messages.filter((m) => isUnread(m, horizon, me) && known(m)), boundary, reachedMs };
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
return isUnreachable(error) ? { kind: 'unreachable' } : { kind: 'failed', error };
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
let skippedUnreachable = 0;
|
|
78
|
+
let anyRead = false;
|
|
79
|
+
const items = [];
|
|
80
|
+
const failed = [];
|
|
81
|
+
const tooDeep = [];
|
|
82
|
+
results.forEach((r, i) => {
|
|
83
|
+
const summary = toRead[i];
|
|
84
|
+
if (r.kind === 'unreachable')
|
|
85
|
+
skippedUnreachable++;
|
|
86
|
+
else if (r.kind === 'failed')
|
|
87
|
+
failed.push({ summary, error: r.error });
|
|
88
|
+
else {
|
|
89
|
+
anyRead = true;
|
|
90
|
+
if (r.reachedMs !== undefined)
|
|
91
|
+
tooDeep.push({ summary, boundary: r.boundary, reachedMs: r.reachedMs });
|
|
92
|
+
for (const m of r.messages)
|
|
93
|
+
items.push({ ms: arrivalMs(m), key: `${summary.id}/${m.id}`, item: { summary, m } });
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
// Every read failed: a failure of the call (a revoked token, a rate limit), not of one conversation.
|
|
97
|
+
if (failed.length > 0 && !anyRead)
|
|
98
|
+
throw failed[0].error;
|
|
99
|
+
const listed = Math.max(pos.t, ...raw.map((c) => lastChangeMs(c) ?? 0));
|
|
100
|
+
const { page, has_more, remaining, next } = takePage(items, pos, limit, failed.length > 0 ? pos.t : listed);
|
|
101
|
+
// Only what is returned is titled: the conversations on this page, those whose read failed and those too busy.
|
|
102
|
+
const shown = [...new Map(page.map(({ summary }) => [summary.id, summary])).values()];
|
|
103
|
+
const titled = await enrichTitles(chatsvc, raw, me, [
|
|
104
|
+
...shown,
|
|
105
|
+
...failed.map((f) => f.summary),
|
|
106
|
+
...tooDeep.map((d) => d.summary),
|
|
107
|
+
]);
|
|
108
|
+
const titledDeep = titled.slice(shown.length + failed.length);
|
|
109
|
+
return {
|
|
110
|
+
total_unread: page.length + remaining,
|
|
111
|
+
messages: page.map(({ summary, m }) => ({
|
|
112
|
+
conversation_id: summary.id,
|
|
113
|
+
...formatFlatMessage(normaliseMessage(m, me, { timeZone }), format),
|
|
114
|
+
})),
|
|
115
|
+
conversations: titled.slice(0, shown.length).map((s) => formatConversation(confirmedSummary(s, true), format)),
|
|
116
|
+
...fromReport(pos, next, has_more),
|
|
117
|
+
skipped_unreachable: skippedUnreachable,
|
|
118
|
+
...(failed.length > 0
|
|
119
|
+
? {
|
|
120
|
+
errors: failed.map((f, i) => ({
|
|
121
|
+
conversation: titled[shown.length + i],
|
|
122
|
+
error: wrapApiError(f.error, 'read this conversation').message,
|
|
123
|
+
})),
|
|
124
|
+
}
|
|
125
|
+
: {}),
|
|
126
|
+
...(tooDeep.length > 0
|
|
127
|
+
? {
|
|
128
|
+
incomplete: tooDeep.map((d, i) => ({
|
|
129
|
+
conversation: titledDeep[i],
|
|
130
|
+
unread_not_read_from: new Date(d.boundary).toISOString(),
|
|
131
|
+
unread_not_read_until: new Date(d.reachedMs).toISOString(),
|
|
132
|
+
...tooBusy(d.boundary, d.reachedMs),
|
|
133
|
+
})),
|
|
134
|
+
}
|
|
135
|
+
: {}),
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/** The arguments that shape a per-conversation answer, which a `from` page replaces. */
|
|
139
|
+
const NOT_WITH_FROM = ['since_days', 'cursors', 'per_conversation_limit', 'max_conversations', 'mark_read', 'older_unread'];
|
|
43
140
|
export function registerUnreadTools(server, { chatsvc }) {
|
|
44
141
|
server.registerTool('teams_get_unread', {
|
|
45
142
|
title: 'Get unread Teams messages',
|
|
@@ -72,6 +169,15 @@ export function registerUnreadTools(server, { chatsvc }) {
|
|
|
72
169
|
'id; next_cursors is the cursors passed in updated with every returned conversation\'s next_cursor ' +
|
|
73
170
|
'(not those only in more_unread_conversations) — pass it back as cursors to get only what is new. ' +
|
|
74
171
|
CURSOR_NO_CACHE_DESCRIPTION +
|
|
172
|
+
FROM_DESCRIPTION +
|
|
173
|
+
'With from the result is one list across every conversation instead: messages (each with its ' +
|
|
174
|
+
'conversation_id; a channel reply keeps replyTo), oldest first, at most limit; conversations (the summary ' +
|
|
175
|
+
'of each one on the page); total_unread (every unread message past from, this page and later ones); ' +
|
|
176
|
+
'from_time, has_more, next_from, next_from_time; skipped_unreachable, muted_skipped and errors. next_from ' +
|
|
177
|
+
'does not move while a read failed (call again). A conversation with more messages since from than a read ' +
|
|
178
|
+
'can reach is listed in incomplete instead (unread_not_read_from / unread_not_read_until name the stretch ' +
|
|
179
|
+
'not read; what arrived after it is returned) and does not hold next_from. from takes the place of since_days, cursors, ' +
|
|
180
|
+
'per_conversation_limit, max_conversations, older_unread and mark_read, and format summary does not apply. ' +
|
|
75
181
|
FORMAT_DESCRIPTION +
|
|
76
182
|
MARK_READ_DESCRIPTION +
|
|
77
183
|
'With mark_read each conversation returned with its messages (not more_unread_conversations) has its ' +
|
|
@@ -128,14 +234,39 @@ export function registerUnreadTools(server, { chatsvc }) {
|
|
|
128
234
|
`(default ${DEFAULT_CONVERSATIONS}, max ${MAX_CONVERSATIONS}); the rest are listed in ` +
|
|
129
235
|
'more_unread_conversations.'),
|
|
130
236
|
cursors: cursorsArg,
|
|
237
|
+
from: fromArg,
|
|
238
|
+
limit: z
|
|
239
|
+
.number()
|
|
240
|
+
.int()
|
|
241
|
+
.min(1)
|
|
242
|
+
.max(MAX_FROM_MESSAGES)
|
|
243
|
+
.optional()
|
|
244
|
+
.describe(`With from only: maximum messages returned across every conversation, oldest first (default ` +
|
|
245
|
+
`${DEFAULT_LIMIT}, max ${MAX_FROM_MESSAGES}).`),
|
|
131
246
|
tz: tzArg,
|
|
132
247
|
format: formatArg,
|
|
133
248
|
mark_read: markReadArg,
|
|
134
249
|
confirmToken: confirmTokenParam,
|
|
135
250
|
},
|
|
136
|
-
}, async ({ kinds, query, include_hidden, include_muted, since_days, older_unread, per_conversation_limit, max_conversations, cursors, tz, format, mark_read, confirmToken, }, ctx) => {
|
|
251
|
+
}, async ({ kinds, query, include_hidden, include_muted, since_days, older_unread, per_conversation_limit, max_conversations, cursors, from, limit, tz, format, mark_read, confirmToken, }, ctx) => {
|
|
137
252
|
try {
|
|
138
253
|
assertMarkReadFormat(mark_read, format);
|
|
254
|
+
if (from === undefined && limit !== undefined) {
|
|
255
|
+
throw new McpToolError('limit applies only with from.', {
|
|
256
|
+
hint: 'Without from, use per_conversation_limit and max_conversations.',
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
if (from !== undefined) {
|
|
260
|
+
const args = { since_days, cursors, per_conversation_limit, max_conversations, mark_read, older_unread };
|
|
261
|
+
const clash = NOT_WITH_FROM.find((k) => args[k] !== undefined && args[k] !== false);
|
|
262
|
+
if (clash !== undefined || format === 'summary') {
|
|
263
|
+
throw new McpToolError(`from cannot be combined with ${clash ?? 'format summary'}.`, {
|
|
264
|
+
hint: 'from pages one oldest-first list across every conversation: pass a previous next_from to go on, ' +
|
|
265
|
+
'and use teams_mark_read to mark what was paged read.',
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
const pos = from !== undefined ? decodeFrom(from) : undefined;
|
|
139
270
|
const timeZone = resolveTimeZone(tz);
|
|
140
271
|
const fetched_at = new Date().toISOString();
|
|
141
272
|
const [raw, me] = await Promise.all([chatsvc.listConversations(), chatsvc.meMri()]);
|
|
@@ -155,6 +286,14 @@ export function registerUnreadTools(server, { chatsvc }) {
|
|
|
155
286
|
if (!include_muted)
|
|
156
287
|
candidates = candidates.filter((s) => !s.muted);
|
|
157
288
|
candidates.sort(byLastActivityDesc);
|
|
289
|
+
if (pos !== undefined) {
|
|
290
|
+
const page = await unreadFrom(chatsvc, raw, me, candidates, pos, {
|
|
291
|
+
limit: limit ?? DEFAULT_LIMIT,
|
|
292
|
+
timeZone,
|
|
293
|
+
format: format === 'compact' ? 'compact' : 'full',
|
|
294
|
+
});
|
|
295
|
+
return untrustedResult({ ...page, muted_skipped: mutedSkipped, fetched_at });
|
|
296
|
+
}
|
|
158
297
|
const perLimit = per_conversation_limit ?? DEFAULT_PER_CONVERSATION;
|
|
159
298
|
const outcome = await confirmUnreadCandidates(chatsvc, raw, me, candidates, { limit: perLimit, maxRaw: MAX_RAW_MESSAGES, since: sinceCutoff(since_days), cursors });
|
|
160
299
|
const { skippedUnreachable, older } = outcome;
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@chrischall/microsoft-teams-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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.
|
|
9
|
+
"version": "0.6.0",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "@chrischall/microsoft-teams-mcp",
|
|
14
|
-
"version": "0.
|
|
14
|
+
"version": "0.6.0",
|
|
15
15
|
"transport": {
|
|
16
16
|
"type": "stdio"
|
|
17
17
|
},
|